diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 121ace9..66bfb3c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,29 +1,34 @@ name: CI on: push: - branches: - - main + branches-ignore: + - 'generated' + - 'codegen/**' + - 'integrated/**' + - 'stl-preview-head/**' + - 'stl-preview-base/**' pull_request: - branches: - - main - - next + branches-ignore: + - 'stl-preview-head/**' + - 'stl-preview-base/**' jobs: lint: + timeout-minutes: 15 name: lint - runs-on: ubuntu-latest - + runs-on: ${{ github.repository == 'stainless-sdks/arcade-engine-java' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} + if: github.event_name == 'push' || github.event.pull_request.head.repo.fork steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Set up Java - uses: actions/setup-java@v4 + uses: actions/setup-java@v5 with: distribution: temurin java-version: | 8 - 17 + 21 cache: gradle - name: Set up Gradle @@ -31,20 +36,64 @@ jobs: - name: Run lints run: ./scripts/lint + + build: + timeout-minutes: 15 + name: build + permissions: + contents: read + id-token: write + runs-on: ${{ github.repository == 'stainless-sdks/arcade-engine-java' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} + if: github.event_name == 'push' || github.event.pull_request.head.repo.fork + + steps: + - uses: actions/checkout@v6 + + - name: Set up Java + uses: actions/setup-java@v5 + 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 + + - name: Get GitHub OIDC Token + if: github.repository == 'stainless-sdks/arcade-engine-java' + id: github-oidc + uses: actions/github-script@v8 + with: + script: core.setOutput('github_token', await core.getIDToken()); + + - name: Build and upload Maven artifacts + if: github.repository == 'stainless-sdks/arcade-engine-java' + env: + URL: https://pkg.stainless.com/s + AUTH: ${{ steps.github-oidc.outputs.github_token }} + SHA: ${{ github.sha }} + PROJECT: arcade-engine-java + run: ./scripts/upload-artifacts test: + timeout-minutes: 15 name: test - runs-on: ubuntu-latest - + runs-on: ${{ github.repository == 'stainless-sdks/arcade-engine-java' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} + if: github.event_name == 'push' || github.event.pull_request.head.repo.fork steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Set up Java - uses: actions/setup-java@v4 + uses: actions/setup-java@v5 with: distribution: temurin java-version: | 8 - 17 + 21 cache: gradle - name: Set up Gradle @@ -52,4 +101,3 @@ jobs: - name: Run tests run: ./scripts/test - diff --git a/.github/workflows/publish-sonatype.yml b/.github/workflows/publish-sonatype.yml index d1dfa7b..860cf22 100644 --- a/.github/workflows/publish-sonatype.yml +++ b/.github/workflows/publish-sonatype.yml @@ -14,15 +14,15 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Set up Java - uses: actions/setup-java@v3 + uses: actions/setup-java@v5 with: distribution: temurin java-version: | 8 - 17 + 21 cache: gradle - name: Set up Gradle @@ -33,7 +33,7 @@ jobs: 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 + ./gradlew publish --no-configuration-cache env: SONATYPE_USERNAME: ${{ secrets.ARCADE_SONATYPE_USERNAME || secrets.SONATYPE_USERNAME }} SONATYPE_PASSWORD: ${{ secrets.ARCADE_SONATYPE_PASSWORD || secrets.SONATYPE_PASSWORD }} diff --git a/.github/workflows/release-doctor.yml b/.github/workflows/release-doctor.yml index e8291d0..d50eefc 100644 --- a/.github/workflows/release-doctor.yml +++ b/.github/workflows/release-doctor.yml @@ -12,7 +12,7 @@ jobs: if: github.repository == 'ArcadeAI/arcade-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 + - uses: actions/checkout@v6 - name: Check release environment run: | diff --git a/.gitignore b/.gitignore index 39c31e3..b1346e6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ .prism.log .gradle .idea -build +.kotlin +build/ codegen.log kls_database.db diff --git a/.stats.yml b/.stats.yml index e73b28d..f7c06a5 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,4 @@ configured_endpoints: 30 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/arcade-ai%2Farcade-engine-4dc4e58ef402ce5362e0a8988b3928a8bfa0d5ba847f7ad8b14226a0cf282f28.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/arcade-ai%2Farcade-engine-6ff494eafa2c154892716407682bb2296cff4f18c45765c5fb16bdf36f452ae1.yml +openapi_spec_hash: 63dde2481a7d51042a241bfba232b0b0 +config_hash: bf64816643634a621cd0ffd93d9c4347 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..f910db9 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,64 @@ +## Modifying/Adding code + +Most of the SDK is generated code. Modifications to code will be persisted between generations, but may +result in merge conflicts between manual patches and changes from the generator. The generator will never +modify the contents of the `arcade-java/lib/` and `arcade-java-examples/` directories. + +## Adding and running examples + +Set the following environment variables: + +| ENV Var | Description | +|-------------------|-------------------------------------------------------------------------| +| `ARCADE_USER_ID` | Arcade user Id or email address | +| `ARCADE_API_KEY` | [Arcade API key](https://docs.arcade.dev/en/get-started/setup/api-keys) | +| `ARCADE_BASE_URL` | Arcade URL, defaults to: `https://api.arcade.dev` | + +Use `./gradlew :arcade-java-example:run -Pexample=` to run `Example` + +For example, if you have the `potify.ResumePlayback` tool configured, you can run: +```shell +export ARCADE_API_KEY='your-api-key' +export ARCADE_USER_ID='your-arcade-user' +./gradlew :arcade-java-example:run -Pexample=PlaySpotify +``` + +## Building the repository from source + +If you’d like to use the repository from source, you can build and install it from git: + +```sh +git clone git@github.com/ArcadeAI/arcade-java.git +SKIP_MOCK_TESTS=true ./gradlew build publishToMavenLocal # This will skip the integration tests, see below on info on how to run them. +``` +## Running tests + +Most tests require you to [run a mock server](https://github.com/stoplightio/prism) against the OpenAPI spec to run the tests. + +```sh +# you will need npm installed +./scripts/mock --daemon +``` + +The mock serer will run in the background allowing you to run tests from the command line `./gradlew test` or from your IDE. + +To stop the mock server run: +```shell +pkill -f prism +``` + +## Linting and formatting + +This repository uses [Spotless](https://github.com/diffplug/spotless/tree/main/plugin-gradle) to lint and format the code in the repository. + +To lint: + +```sh +$ ./scripts/lint +``` + +To format and fix all issues automatically: + +```sh +$ ./scripts/format +``` diff --git a/LICENSE b/LICENSE index 586b176..fed1c6e 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright 2025 Arcade +Copyright 2026 Arcade 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: diff --git a/README.md b/README.md index 4cfa7a6..2c2cbbf 100644 --- a/README.md +++ b/README.md @@ -3,14 +3,19 @@ [![Maven Central](https://img.shields.io/maven-central/v/dev.arcade/arcade-java)](https://central.sonatype.com/artifact/dev.arcade/arcade-java/0.1.0-alpha.1) +[![javadoc](https://javadoc.io/badge2/dev.arcade/arcade-java/0.1.0-alpha.1/javadoc.svg)](https://javadoc.io/doc/dev.arcade/arcade-java/0.1.0-alpha.1) -The Arcade Java SDK provides convenient access to the Arcade REST API from applications written in Java. +The Arcade Java SDK provides convenient access to the [Arcade REST API](https://docs.arcade.dev) from applications written in Java. -It is generated with [Stainless](https://www.stainlessapi.com/). +It is generated with [Stainless](https://www.stainless.com/). -The REST API documentation can be found on [docs.arcade.dev](https://docs.arcade.dev). + + +The REST API documentation can be found on [docs.arcade.dev](https://docs.arcade.dev). Javadocs are available on [javadoc.io](https://javadoc.io/doc/dev.arcade/arcade-java/0.1.0-alpha.1). + + ## Installation @@ -26,9 +31,9 @@ implementation("dev.arcade:arcade-java:0.1.0-alpha.1") ```xml - dev.arcade - arcade-java - 0.1.0-alpha.1 + dev.arcade + arcade-java + 0.1.0-alpha.1 ``` @@ -43,30 +48,30 @@ This library requires Java 8 or later. ```java import dev.arcade.client.ArcadeClient; import dev.arcade.client.okhttp.ArcadeOkHttpClient; -import dev.arcade.models.ExecuteToolRequest; -import dev.arcade.models.ExecuteToolResponse; -import dev.arcade.models.ToolExecuteParams; +import dev.arcade.models.tools.ExecuteToolRequest; +import dev.arcade.models.tools.ExecuteToolResponse; +import dev.arcade.models.tools.ToolExecuteParams; -// Configures using the `ARCADE_API_KEY` environment variable +// Configures using the `arcade.apiKey` and `arcade.baseUrl` system properties +// Or configures using the `ARCADE_API_KEY` and `ARCADE_BASE_URL` environment variables ArcadeClient client = ArcadeOkHttpClient.fromEnv(); -ToolExecuteParams params = ToolExecuteParams.builder() - .executeToolRequest(ExecuteToolRequest.builder() - .toolName("tool_name") - .build()) +ExecuteToolRequest params = ExecuteToolRequest.builder() + .toolName("tool_name") .build(); ExecuteToolResponse executeToolResponse = client.tools().execute(params); ``` ## Client configuration -Configure the client using environment variables: +Configure the client using system properties or environment variables: ```java import dev.arcade.client.ArcadeClient; import dev.arcade.client.okhttp.ArcadeOkHttpClient; -// Configures using the `ARCADE_API_KEY` environment variable +// Configures using the `arcade.apiKey` and `arcade.baseUrl` system properties +// Or configures using the `ARCADE_API_KEY` and `ARCADE_BASE_URL` environment variables ArcadeClient client = ArcadeOkHttpClient.fromEnv(); ``` @@ -88,7 +93,8 @@ import dev.arcade.client.ArcadeClient; import dev.arcade.client.okhttp.ArcadeOkHttpClient; ArcadeClient client = ArcadeOkHttpClient.builder() - // Configures using the `ARCADE_API_KEY` environment variable + // Configures using the `arcade.apiKey` and `arcade.baseUrl` system properties + // Or configures using the `ARCADE_API_KEY` and `ARCADE_BASE_URL` environment variables .fromEnv() .apiKey("My API Key") .build(); @@ -96,14 +102,67 @@ ArcadeClient client = ArcadeOkHttpClient.builder() See this table for the available options: -| Setter | Environment variable | Required | Default value | -| -------- | -------------------- | -------- | ------------- | -| `apiKey` | `ARCADE_API_KEY` | true | - | +| Setter | System property | Environment variable | Required | Default value | +| --------- | ---------------- | -------------------- |----------| -------------------------- | +| `apiKey` | `arcade.apiKey` | `ARCADE_API_KEY` | true | - | +| `baseUrl` | `arcade.baseUrl` | `ARCADE_BASE_URL` | false | `"https://api.arcade.dev"` | + +System properties take precedence over environment variables. > [!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 + +To temporarily use a modified client configuration, while reusing the same connection and thread pools, call `withOptions()` on any client or service: + +```java +import dev.arcade.client.ArcadeClient; + +ArcadeClient clientWithOptions = client.withOptions(optionsBuilder -> { + optionsBuilder.baseUrl("https://example.com"); + optionsBuilder.maxRetries(42); +}); +``` + +The `withOptions()` method does not affect the original client or service. + +## User Authentication + +To initiate an OAuth 2 authenticated flow with a user, use the `AuthService.start` method: + +```java +import dev.arcade.client.ArcadeClient; +import dev.arcade.models.AuthorizationResponse; + +// See above on creating a client +ArcadeClient client; + +// get the auth service, and call start +AuthorizationResponse authResponse = client.auth().start( + "{arcade_user_id}", // email or user ID of an Arcade user + "{auth_provider}", // provider name + "oauth2", // provider type + List.of("{scope1}", "{scope2}")); // list of scopes + +// check the response status +authResponse.status() + .filter(status -> status != AuthorizationResponse.Status.COMPLETED) + .ifPresent(status -> + System.out.println("Click this link to authorize: " + authResponse.url().get())); +``` +```java +// if the authorization is NOT complete, you can wait using the following method: +client.auth().waitForCompletion(authResponse); +``` + +> [!CAUTION] +> This method should not be used in web applications as it will block the current thread. +> For web apps, you will need to poll the `status` endpoint by calling `client.auth.status(...)`. + +For more details, see the [Authorized Tool Calling](https://docs.arcade.dev/en/guides/tool-calling/custom-apps/auth-tool-calling) docs. + ## Requests and responses To send a request to the Arcade 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. @@ -125,18 +184,17 @@ The default client is synchronous. To switch to asynchronous execution, call the ```java import dev.arcade.client.ArcadeClient; import dev.arcade.client.okhttp.ArcadeOkHttpClient; -import dev.arcade.models.ExecuteToolRequest; -import dev.arcade.models.ExecuteToolResponse; -import dev.arcade.models.ToolExecuteParams; +import dev.arcade.models.tools.ExecuteToolRequest; +import dev.arcade.models.tools.ExecuteToolResponse; +import dev.arcade.models.tools.ToolExecuteParams; import java.util.concurrent.CompletableFuture; -// Configures using the `ARCADE_API_KEY` environment variable +// Configures using the `arcade.apiKey` and `arcade.baseUrl` system properties +// Or configures using the `ARCADE_API_KEY` and `ARCADE_BASE_URL` environment variables ArcadeClient client = ArcadeOkHttpClient.fromEnv(); -ToolExecuteParams params = ToolExecuteParams.builder() - .executeToolRequest(ExecuteToolRequest.builder() - .toolName("tool_name") - .build()) +ExecuteToolRequest params = ExecuteToolRequest.builder() + .toolName("tool_name") .build(); CompletableFuture executeToolResponse = client.async().tools().execute(params); ``` @@ -146,47 +204,176 @@ Or create an asynchronous client from the beginning: ```java import dev.arcade.client.ArcadeClientAsync; import dev.arcade.client.okhttp.ArcadeOkHttpClientAsync; -import dev.arcade.models.ExecuteToolRequest; -import dev.arcade.models.ExecuteToolResponse; -import dev.arcade.models.ToolExecuteParams; +import dev.arcade.models.tools.ExecuteToolRequest; +import dev.arcade.models.tools.ExecuteToolResponse; +import dev.arcade.models.tools.ToolExecuteParams; import java.util.concurrent.CompletableFuture; -// Configures using the `ARCADE_API_KEY` environment variable +// Configures using the `arcade.apiKey` and `arcade.baseUrl` system properties +// Or configures using the `ARCADE_API_KEY` and `ARCADE_BASE_URL` environment variables ArcadeClientAsync client = ArcadeOkHttpClientAsync.fromEnv(); -ToolExecuteParams params = ToolExecuteParams.builder() - .executeToolRequest(ExecuteToolRequest.builder() - .toolName("tool_name") - .build()) +ExecuteToolRequest params = ExecuteToolRequest.builder() + .toolName("tool_name") .build(); CompletableFuture executeToolResponse = client.tools().execute(params); ``` The asynchronous client supports the same options as the synchronous one, except most methods return `CompletableFuture`s. +## Raw responses + +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. + +To access this data, prefix any HTTP method call on a client or service with `withRawResponse()`: + +```java +import dev.arcade.core.http.Headers; +import dev.arcade.core.http.HttpResponseFor; +import dev.arcade.models.chat.ChatRequest; +import dev.arcade.models.chat.ChatResponse; +import dev.arcade.models.chat.completions.CompletionCreateParams; + +ChatRequest params = ChatRequest.builder().build(); +HttpResponseFor chatResponse = client.chat().completions().withRawResponse().create(params); + +int statusCode = chatResponse.statusCode(); +Headers headers = chatResponse.headers(); +``` + +You can still deserialize the response into an instance of a Java class if needed: + +```java +import dev.arcade.models.chat.ChatResponse; + +ChatResponse parsedChatResponse = chatResponse.parse(); +``` + ## Error handling The SDK throws custom unchecked exception types: - [`ArcadeServiceException`](arcade-java-core/src/main/kotlin/dev/arcade/errors/ArcadeServiceException.kt): Base class for HTTP errors. See this table for which exception subclass is thrown for each HTTP status code: - | Status | Exception | - | ------ | ------------------------------- | - | 400 | `BadRequestException` | - | 401 | `AuthenticationException` | - | 403 | `PermissionDeniedException` | - | 404 | `NotFoundException` | - | 422 | `UnprocessableEntityException` | - | 429 | `RateLimitException` | - | 5xx | `InternalServerException` | - | others | `UnexpectedStatusCodeException` | + | Status | Exception | + | ------ | ---------------------------------------------------------------------------------------------------------------------- | + | 400 | [`BadRequestException`](arcade-java-core/src/main/kotlin/dev/arcade/errors/BadRequestException.kt) | + | 401 | [`UnauthorizedException`](arcade-java-core/src/main/kotlin/dev/arcade/errors/UnauthorizedException.kt) | + | 403 | [`PermissionDeniedException`](arcade-java-core/src/main/kotlin/dev/arcade/errors/PermissionDeniedException.kt) | + | 404 | [`NotFoundException`](arcade-java-core/src/main/kotlin/dev/arcade/errors/NotFoundException.kt) | + | 422 | [`UnprocessableEntityException`](arcade-java-core/src/main/kotlin/dev/arcade/errors/UnprocessableEntityException.kt) | + | 429 | [`RateLimitException`](arcade-java-core/src/main/kotlin/dev/arcade/errors/RateLimitException.kt) | + | 5xx | [`InternalServerException`](arcade-java-core/src/main/kotlin/dev/arcade/errors/InternalServerException.kt) | + | others | [`UnexpectedStatusCodeException`](arcade-java-core/src/main/kotlin/dev/arcade/errors/UnexpectedStatusCodeException.kt) | - [`ArcadeIoException`](arcade-java-core/src/main/kotlin/dev/arcade/errors/ArcadeIoException.kt): I/O networking errors. +- [`ArcadeRetryableException`](arcade-java-core/src/main/kotlin/dev/arcade/errors/ArcadeRetryableException.kt): Generic error indicating a failure that could be retried by the client. + - [`ArcadeInvalidDataException`](arcade-java-core/src/main/kotlin/dev/arcade/errors/ArcadeInvalidDataException.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. - [`ArcadeException`](arcade-java-core/src/main/kotlin/dev/arcade/errors/ArcadeException.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. +## Pagination + +The SDK defines methods that return a paginated lists of results. It provides convenient ways to access the results either one page at a time or item-by-item across all pages. + +### Auto-pagination + +To iterate through all results across all pages, use the `autoPager()` method, which automatically fetches more pages as needed. + +When using the synchronous client, the method returns an [`Iterable`](https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html) + +```java +import dev.arcade.models.admin.userconnections.UserConnectionListPage; +import dev.arcade.models.admin.userconnections.UserConnectionResponse; + +UserConnectionListPage page = client.admin().userConnections().list(); + +// Process as an Iterable +for (UserConnectionResponse userConnection : page.autoPager()) { + System.out.println(userConnection); +} + +// Process as a Stream +page.autoPager() + .stream() + .limit(50) + .forEach(userConnection -> System.out.println(userConnection)); +``` + +When using the asynchronous client, the method returns an [`AsyncStreamResponse`](arcade-java-core/src/main/kotlin/dev/arcade/core/http/AsyncStreamResponse.kt): + +```java +import dev.arcade.core.http.AsyncStreamResponse; +import dev.arcade.models.admin.userconnections.UserConnectionListPageAsync; +import dev.arcade.models.admin.userconnections.UserConnectionResponse; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; + +CompletableFuture pageFuture = client.async().admin().userConnections().list(); + +pageFuture.thenRun(page -> page.autoPager().subscribe(userConnection -> { + System.out.println(userConnection); +})); + +// If you need to handle errors or completion of the stream +pageFuture.thenRun(page -> page.autoPager().subscribe(new AsyncStreamResponse.Handler<>() { + @Override + public void onNext(UserConnectionResponse userConnection) { + System.out.println(userConnection); + } + + @Override + public void onComplete(Optional error) { + if (error.isPresent()) { + System.out.println("Something went wrong!"); + throw new RuntimeException(error.get()); + } else { + System.out.println("No more!"); + } + } +})); + +// Or use futures +pageFuture.thenRun(page -> page.autoPager() + .subscribe(userConnection -> { + System.out.println(userConnection); + }) + .onCompleteFuture() + .whenComplete((unused, error) -> { + if (error != null) { + System.out.println("Something went wrong!"); + throw new RuntimeException(error); + } else { + System.out.println("No more!"); + } + })); +``` + +### Manual pagination + +To access individual page items and manually request the next page, use the `items()`, +`hasNextPage()`, and `nextPage()` methods: + +```java +import dev.arcade.models.admin.userconnections.UserConnectionListPage; +import dev.arcade.models.admin.userconnections.UserConnectionResponse; + +UserConnectionListPage page = client.admin().userConnections().list(); +while (true) { + for (UserConnectionResponse userConnection : page.items()) { + System.out.println(userConnection); + } + + if (!page.hasNextPage()) { + break; + } + + page = page.nextPage(); +} +``` + ## Logging The SDK uses the standard [OkHttp logging interceptor](https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor). @@ -194,20 +381,39 @@ The SDK uses the standard [OkHttp logging interceptor](https://github.com/square Enable logging by setting the `ARCADE_LOG` environment variable to `info`: ```sh -$ export ARCADE_LOG=info +export ARCADE_LOG=info ``` Or to `debug` for more verbose logging: ```sh -$ export ARCADE_LOG=debug +export ARCADE_LOG=debug ``` +## ProGuard and R8 + +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 `arcade-java-core` is published with a [configuration file](arcade-java-core/src/main/resources/META-INF/proguard/arcade-java-core.pro) containing [keep rules](https://www.guardsquare.com/manual/configuration/usage). + +ProGuard and R8 should automatically detect and use the published rules, but you can also manually copy the keep rules if necessary. + +## Jackson + +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. + +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). + +If the SDK threw an exception, but you're _certain_ the version is compatible, then disable the version check using the `checkJacksonVersionCompatibility` on [`ArcadeOkHttpClient`](arcade-java-client-okhttp/src/main/kotlin/dev/arcade/client/okhttp/ArcadeOkHttpClient.kt) or [`ArcadeOkHttpClientAsync`](arcade-java-client-okhttp/src/main/kotlin/dev/arcade/client/okhttp/ArcadeOkHttpClientAsync.kt). + +> [!CAUTION] +> We make no guarantee that the SDK works correctly when the Jackson version check is disabled. + +Also note that there are bugs in older Jackson versions that can affect the SDK. We don't work around all Jackson bugs ([example](https://github.com/FasterXML/jackson-databind/issues/3240)) and expect users to upgrade Jackson for those instead. + ## Network options ### Retries -The SDK automatically retries 2 times by default, with a short exponential backoff. +The SDK automatically retries 2 times by default, with a short exponential backoff between requests. Only the following error types are retried: @@ -217,7 +423,7 @@ Only the following error types are retried: - 429 Rate Limit - 5xx Internal -The API may also explicitly instruct the SDK to retry or not retry a response. +The API may also explicitly instruct the SDK to retry or not retry a request. To set a custom number of retries, configure the client using the `maxRetries` method: @@ -238,11 +444,9 @@ Requests time out after 1 minute by default. To set a custom timeout, configure the method call using the `timeout` method: ```java -import dev.arcade.models.ExecuteToolRequest; -import dev.arcade.models.ExecuteToolResponse; -import dev.arcade.models.ToolExecuteParams; +import dev.arcade.models.chat.ChatResponse; -ExecuteToolResponse executeToolResponse = client.tools().execute( +ChatResponse chatResponse = client.chat().completions().create( params, RequestOptions.builder().timeout(Duration.ofSeconds(30)).build() ); ``` @@ -280,6 +484,82 @@ ArcadeClient client = ArcadeOkHttpClient.builder() .build(); ``` +### Connection pooling + +To customize the underlying OkHttp connection pool, configure the client using the `maxIdleConnections` and `keepAliveDuration` methods: + +```java +import dev.arcade.client.ArcadeClient; +import dev.arcade.client.okhttp.ArcadeOkHttpClient; +import java.time.Duration; + +ArcadeClient client = ArcadeOkHttpClient.builder() + .fromEnv() + // If `maxIdleConnections` is set, then `keepAliveDuration` must be set, and vice versa. + .maxIdleConnections(10) + .keepAliveDuration(Duration.ofMinutes(2)) + .build(); +``` + +If both options are unset, OkHttp's default connection pool settings are used. + +### 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. + +To configure how HTTPS connections are secured, configure the client using the `sslSocketFactory`, `trustManager`, and `hostnameVerifier` methods: + +```java +import dev.arcade.client.ArcadeClient; +import dev.arcade.client.okhttp.ArcadeOkHttpClient; + +ArcadeClient client = ArcadeOkHttpClient.builder() + .fromEnv() + // If `sslSocketFactory` is set, then `trustManager` must be set, and vice versa. + .sslSocketFactory(yourSSLSocketFactory) + .trustManager(yourTrustManager) + .hostnameVerifier(yourHostnameVerifier) + .build(); +``` + +### Custom HTTP client + +The SDK consists of three artifacts: + +- `arcade-java-core` + - Contains core SDK logic + - Does not depend on [OkHttp](https://square.github.io/okhttp) + - Exposes [`ArcadeClient`](arcade-java-core/src/main/kotlin/dev/arcade/client/ArcadeClient.kt), [`ArcadeClientAsync`](arcade-java-core/src/main/kotlin/dev/arcade/client/ArcadeClientAsync.kt), [`ArcadeClientImpl`](arcade-java-core/src/main/kotlin/dev/arcade/client/ArcadeClientImpl.kt), and [`ArcadeClientAsyncImpl`](arcade-java-core/src/main/kotlin/dev/arcade/client/ArcadeClientAsyncImpl.kt), all of which can work with any HTTP client +- `arcade-java-client-okhttp` + - Depends on [OkHttp](https://square.github.io/okhttp) + - Exposes [`ArcadeOkHttpClient`](arcade-java-client-okhttp/src/main/kotlin/dev/arcade/client/okhttp/ArcadeOkHttpClient.kt) and [`ArcadeOkHttpClientAsync`](arcade-java-client-okhttp/src/main/kotlin/dev/arcade/client/okhttp/ArcadeOkHttpClientAsync.kt), which provide a way to construct [`ArcadeClientImpl`](arcade-java-core/src/main/kotlin/dev/arcade/client/ArcadeClientImpl.kt) and [`ArcadeClientAsyncImpl`](arcade-java-core/src/main/kotlin/dev/arcade/client/ArcadeClientAsyncImpl.kt), respectively, using OkHttp +- `arcade-java` + - Depends on and exposes the APIs of both `arcade-java-core` and `arcade-java-client-okhttp` + - Does not have its own logic + +This structure allows replacing the SDK's default HTTP client without pulling in unnecessary dependencies. + +#### Customized [`OkHttpClient`](https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.html) + +> [!TIP] +> Try the available [network options](#network-options) before replacing the default client. + +To use a customized `OkHttpClient`: + +1. Replace your [`arcade-java` dependency](#installation) with `arcade-java-core` +2. Copy `arcade-java-client-okhttp`'s [`OkHttpClient`](arcade-java-client-okhttp/src/main/kotlin/dev/arcade/client/okhttp/OkHttpClient.kt) class into your code and customize it +3. Construct [`ArcadeClientImpl`](arcade-java-core/src/main/kotlin/dev/arcade/client/ArcadeClientImpl.kt) or [`ArcadeClientAsyncImpl`](arcade-java-core/src/main/kotlin/dev/arcade/client/ArcadeClientAsyncImpl.kt), similarly to [`ArcadeOkHttpClient`](arcade-java-client-okhttp/src/main/kotlin/dev/arcade/client/okhttp/ArcadeOkHttpClient.kt) or [`ArcadeOkHttpClientAsync`](arcade-java-client-okhttp/src/main/kotlin/dev/arcade/client/okhttp/ArcadeOkHttpClientAsync.kt), using your customized client + +### Completely custom HTTP client + +To use a completely custom HTTP client: + +1. Replace your [`arcade-java` dependency](#installation) with `arcade-java-core` +2. Write a class that implements the [`HttpClient`](arcade-java-core/src/main/kotlin/dev/arcade/core/http/HttpClient.kt) interface +3. Construct [`ArcadeClientImpl`](arcade-java-core/src/main/kotlin/dev/arcade/client/ArcadeClientImpl.kt) or [`ArcadeClientAsyncImpl`](arcade-java-core/src/main/kotlin/dev/arcade/client/ArcadeClientAsyncImpl.kt), similarly to [`ArcadeOkHttpClient`](arcade-java-client-okhttp/src/main/kotlin/dev/arcade/client/okhttp/ArcadeOkHttpClient.kt) or [`ArcadeOkHttpClientAsync`](arcade-java-client-okhttp/src/main/kotlin/dev/arcade/client/okhttp/ArcadeOkHttpClientAsync.kt), using your new client class + ## Undocumented API functionality 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. @@ -290,7 +570,7 @@ To set undocumented parameters, call the `putAdditionalHeader`, `putAdditionalQu ```java import dev.arcade.core.JsonValue; -import dev.arcade.models.ToolExecuteParams; +import dev.arcade.models.tools.ToolExecuteParams; ToolExecuteParams params = ToolExecuteParams.builder() .putAdditionalHeader("Secret-Header", "42") @@ -299,18 +579,74 @@ ToolExecuteParams params = ToolExecuteParams.builder() .build(); ``` -These can be accessed on the built object later using the `_additionalHeaders()`, `_additionalQueryParams()`, and `_additionalBodyProperties()` methods. You can also set undocumented parameters on nested headers, query params, or body classes using the `putAdditionalProperty` method. These properties can be accessed on the built object later using the `_additionalProperties()` method. +These can be accessed on the built object later using the `_additionalHeaders()`, `_additionalQueryParams()`, and `_additionalBodyProperties()` methods. + +To set a documented parameter or property to an undocumented or not yet supported _value_, pass a [`JsonValue`](arcade-java-core/src/main/kotlin/dev/arcade/core/Values.kt) object to its setter: + +```java +import dev.arcade.models.tools.ExecuteToolRequest; +import dev.arcade.models.tools.ToolExecuteParams; + +ToolExecuteParams params = ToolExecuteParams.builder() + .executeToolRequest(ExecuteToolRequest.builder() + .toolName("tool_name") + .build()) + .build(); +``` + +The most straightforward way to create a [`JsonValue`](arcade-java-core/src/main/kotlin/dev/arcade/core/Values.kt) is using its `from(...)` method: + +```java +import dev.arcade.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!"); + +// 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 + ) +)); +``` + +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. -To set a documented parameter or property to an undocumented or not yet supported _value_, pass a [`JsonValue`](arcade-java-core/src/main/kotlin/dev/arcade/core/JsonValue.kt) object to its setter: +To forcibly omit a required parameter or property, pass [`JsonMissing`](arcade-java-core/src/main/kotlin/dev/arcade/core/Values.kt): ```java -import dev.arcade.models.ExecuteToolRequest; -import dev.arcade.models.ToolExecuteParams; +import dev.arcade.core.JsonMissing; +import dev.arcade.models.tools.ExecuteToolRequest; +import dev.arcade.models.tools.ToolExecuteParams; ToolExecuteParams params = ToolExecuteParams.builder() .executeToolRequest(ExecuteToolRequest.builder() .toolName("tool_name") .build()) + .toolName(JsonMissing.of()) .build(); ``` @@ -377,7 +713,7 @@ By default, the SDK will not throw an exception in this case. It will throw [`Ar If you would prefer to check that the response is completely well-typed upfront, then either call `validate()`: ```java -import dev.arcade.models.ExecuteToolResponse; +import dev.arcade.models.tools.ExecuteToolResponse; ExecuteToolResponse executeToolResponse = client.tools().execute(params).validate(); ``` @@ -385,9 +721,7 @@ ExecuteToolResponse executeToolResponse = client.tools().execute(params).validat Or configure the method call to validate the response using the `responseValidation` method: ```java -import dev.arcade.models.ExecuteToolRequest; -import dev.arcade.models.ExecuteToolResponse; -import dev.arcade.models.ToolExecuteParams; +import dev.arcade.models.tools.ExecuteToolResponse; ExecuteToolResponse executeToolResponse = client.tools().execute( params, RequestOptions.builder().responseValidation(true).build() @@ -406,6 +740,39 @@ ArcadeClient client = ArcadeOkHttpClient.builder() .build(); ``` +## Spring Boot Integration + +The `dev.arcade:arcade-spring-boot-starter` provides a configured `ArcadeClient` bean if the following configuration values are set: + +| Spring Property | Environment variable | Required | Default value | +|--------------------|----------------------|----------|--------------------------| +| `arcade.api-key` | `ARCADE_API_KEY` | true | - | +| `arcade.base-url` | `ARCADE_BASE_URL` | false | `"https://api.arcade.dev"` | + +Read the Spring Boot [Externalized Configuration](https://docs.spring.io/spring-boot/reference/features/external-config.html) docs for more ways to configure these properties. + +## Run the examples + +The examples in `arcade-java-example` can be run in your IDE or on the command line by running: + +```shell +# Configure the environment variables +export ARCADE_API_KEY="" +export ARCADE_USER_ID="arcade-userid-or-email" + +# run the example +./gradlew :arcade-java-example:run -Pexample= +``` + +| Example Name | Description | +|-------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `springboot.SpringBoot` | Calls an aArcade tool using Spring Boot | +| `springai.SpringAI` | Allows a Spring AI chat client to call Arcade Tools, you must configure an OpenAI key for this example: `export SPRING_AI_OPENAI_API_KEY=` | +| `Auth` | Demos how to handle an OAuth authorization response | +| `PlaySpotify` | Calls an Arcade tool without a plain Java application. | +> [!NOTE] +> The above Spring Boot (and Spring AI) examples are not web applications, but the demonstrated logic will work the same way in a web app. + ## FAQ ### Why don't you use plain `enum` classes? diff --git a/SECURITY.md b/SECURITY.md index 537fadc..c65353d 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,9 +2,9 @@ ## Reporting Security Issues -This SDK is generated by [Stainless Software Inc](http://stainlessapi.com). Stainless takes security seriously, and encourages you to report any security vulnerability promptly so that appropriate action can be taken. +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@stainlessapi.com. +To report a security issue, please contact the Stainless team at security@stainless.com. ## Responsible Disclosure @@ -16,11 +16,11 @@ 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 Arcade please follow the respective company's security reporting guidelines. +or products provided by Arcade, please follow the respective company's security reporting guidelines. ### Arcade Terms and Policies -Please contact dev@arcade.dev for any questions or concerns regarding security of our services. +Please contact dev@arcade.dev for any questions or concerns regarding the security of our services. --- diff --git a/arcade-java-client-okhttp/build.gradle.kts b/arcade-java-client-okhttp/build.gradle.kts index d6bc70f..72ac6cf 100644 --- a/arcade-java-client-okhttp/build.gradle.kts +++ b/arcade-java-client-okhttp/build.gradle.kts @@ -10,5 +10,6 @@ dependencies { implementation("com.squareup.okhttp3:logging-interceptor:4.12.0") testImplementation(kotlin("test")) - testImplementation("org.assertj:assertj-core:3.25.3") + testImplementation("org.assertj:assertj-core:3.27.7") + testImplementation("com.github.tomakehurst:wiremock-jre8:2.35.2") } diff --git a/arcade-java-client-okhttp/src/main/kotlin/dev/arcade/client/okhttp/ArcadeOkHttpClient.kt b/arcade-java-client-okhttp/src/main/kotlin/dev/arcade/client/okhttp/ArcadeOkHttpClient.kt index cab17e4..df8b6ec 100644 --- a/arcade-java-client-okhttp/src/main/kotlin/dev/arcade/client/okhttp/ArcadeOkHttpClient.kt +++ b/arcade-java-client-okhttp/src/main/kotlin/dev/arcade/client/okhttp/ArcadeOkHttpClient.kt @@ -6,18 +6,40 @@ import com.fasterxml.jackson.databind.json.JsonMapper import dev.arcade.client.ArcadeClient import dev.arcade.client.ArcadeClientImpl import dev.arcade.core.ClientOptions +import dev.arcade.core.Sleeper +import dev.arcade.core.Timeout +import dev.arcade.core.http.AsyncStreamResponse import dev.arcade.core.http.Headers +import dev.arcade.core.http.HttpClient import dev.arcade.core.http.QueryParams +import dev.arcade.core.jsonMapper import java.net.Proxy import java.time.Clock import java.time.Duration - +import java.util.Optional +import java.util.concurrent.Executor +import java.util.concurrent.ExecutorService +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 [ArcadeClient] with [OkHttpClient] as the underlying + * [HttpClient]. + */ class ArcadeOkHttpClient private constructor() { companion object { + /** Returns a mutable builder for constructing an instance of [ArcadeClient]. */ @JvmStatic fun builder() = Builder() + /** + * Returns a client configured using system properties and environment variables. + * + * @see ClientOptions.Builder.fromEnv + */ @JvmStatic fun fromEnv(): ArcadeClient = builder().fromEnv().build() } @@ -25,20 +47,233 @@ class ArcadeOkHttpClient private constructor() { class Builder internal constructor() { private var clientOptions: ClientOptions.Builder = ClientOptions.builder() - private var baseUrl: String = ClientOptions.PRODUCTION_URL - // The default timeout for the client is 1 minute. - private var timeout: Duration = Duration.ofSeconds(60) + private var dispatcherExecutorService: ExecutorService? = null private var proxy: Proxy? = null + private var maxIdleConnections: Int? = null + private var keepAliveDuration: Duration? = null + private var sslSocketFactory: SSLSocketFactory? = null + private var trustManager: X509TrustManager? = null + private var hostnameVerifier: HostnameVerifier? = null + + /** + * The executor service to use for running HTTP requests. + * + * Defaults to OkHttp's + * [default executor service](https://github.com/square/okhttp/blob/ace792f443b2ffb17974f5c0d1cecdf589309f26/okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dispatcher.kt#L98-L104). + * + * This class takes ownership of the executor service and shuts it down when closed. + */ + fun dispatcherExecutorService(dispatcherExecutorService: ExecutorService?) = apply { + this.dispatcherExecutorService = dispatcherExecutorService + } + + /** + * Alias for calling [Builder.dispatcherExecutorService] with + * `dispatcherExecutorService.orElse(null)`. + */ + fun dispatcherExecutorService(dispatcherExecutorService: Optional) = + dispatcherExecutorService(dispatcherExecutorService.getOrNull()) + + 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 maximum number of idle connections kept by the underlying OkHttp connection pool. + * + * If this is set, then [keepAliveDuration] must also be set. + * + * If unset, then OkHttp's default is used. + */ + fun maxIdleConnections(maxIdleConnections: Int?) = apply { + this.maxIdleConnections = maxIdleConnections + } + + /** + * Alias for [Builder.maxIdleConnections]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun maxIdleConnections(maxIdleConnections: Int) = + maxIdleConnections(maxIdleConnections as Int?) + + /** + * Alias for calling [Builder.maxIdleConnections] with `maxIdleConnections.orElse(null)`. + */ + fun maxIdleConnections(maxIdleConnections: Optional) = + maxIdleConnections(maxIdleConnections.getOrNull()) + + /** + * The keep-alive duration for idle connections in the underlying OkHttp connection pool. + * + * If this is set, then [maxIdleConnections] must also be set. + * + * If unset, then OkHttp's default is used. + */ + fun keepAliveDuration(keepAliveDuration: Duration?) = apply { + this.keepAliveDuration = keepAliveDuration + } + + /** Alias for calling [Builder.keepAliveDuration] with `keepAliveDuration.orElse(null)`. */ + fun keepAliveDuration(keepAliveDuration: Optional) = + keepAliveDuration(keepAliveDuration.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 + } - fun baseUrl(baseUrl: String) = apply { - clientOptions.baseUrl(baseUrl) - this.baseUrl = baseUrl + /** 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 [dev.arcade.core.jsonMapper]. The default is usually sufficient and rarely + * needs to be overridden. + */ fun jsonMapper(jsonMapper: JsonMapper) = apply { clientOptions.jsonMapper(jsonMapper) } + /** + * The executor to use for running [AsyncStreamResponse.Handler] callbacks. + * + * Defaults to a dedicated cached thread pool. + * + * This class takes ownership of the executor and shuts it down, if possible, when closed. + */ + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + clientOptions.streamHandlerExecutor(streamHandlerExecutor) + } + + /** + * The interface to use for delaying execution, like during retries. + * + * This is primarily useful for using fake delays in tests. + * + * Defaults to real execution delays. + * + * This class takes ownership of the sleeper and closes it when closed. + */ + fun sleeper(sleeper: Sleeper) = apply { clientOptions.sleeper(sleeper) } + + /** + * 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.arcade.dev`. + */ + 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) } + + /** API key used for authorization in header */ + fun apiKey(apiKey: String) = apply { clientOptions.apiKey(apiKey) } + fun headers(headers: Headers) = apply { clientOptions.headers(headers) } fun headers(headers: Map>) = apply { @@ -119,28 +354,31 @@ class ArcadeOkHttpClient private constructor() { clientOptions.removeAllQueryParams(keys) } - fun timeout(timeout: Duration) = apply { this.timeout = timeout } - - fun maxRetries(maxRetries: Int) = apply { clientOptions.maxRetries(maxRetries) } - - fun proxy(proxy: Proxy) = apply { this.proxy = proxy } - - fun responseValidation(responseValidation: Boolean) = apply { - clientOptions.responseValidation(responseValidation) - } - - fun apiKey(apiKey: String) = apply { clientOptions.apiKey(apiKey) } - + /** + * Updates configuration using system properties and environment variables. + * + * @see ClientOptions.Builder.fromEnv + */ fun fromEnv() = apply { clientOptions.fromEnv() } + /** + * Returns an immutable instance of [ArcadeClient]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): ArcadeClient = ArcadeClientImpl( clientOptions .httpClient( OkHttpClient.builder() - .baseUrl(baseUrl) - .timeout(timeout) + .timeout(clientOptions.timeout()) .proxy(proxy) + .maxIdleConnections(maxIdleConnections) + .keepAliveDuration(keepAliveDuration) + .dispatcherExecutorService(dispatcherExecutorService) + .sslSocketFactory(sslSocketFactory) + .trustManager(trustManager) + .hostnameVerifier(hostnameVerifier) .build() ) .build() diff --git a/arcade-java-client-okhttp/src/main/kotlin/dev/arcade/client/okhttp/ArcadeOkHttpClientAsync.kt b/arcade-java-client-okhttp/src/main/kotlin/dev/arcade/client/okhttp/ArcadeOkHttpClientAsync.kt index 97d2a32..5eee0ac 100644 --- a/arcade-java-client-okhttp/src/main/kotlin/dev/arcade/client/okhttp/ArcadeOkHttpClientAsync.kt +++ b/arcade-java-client-okhttp/src/main/kotlin/dev/arcade/client/okhttp/ArcadeOkHttpClientAsync.kt @@ -6,18 +6,40 @@ import com.fasterxml.jackson.databind.json.JsonMapper import dev.arcade.client.ArcadeClientAsync import dev.arcade.client.ArcadeClientAsyncImpl import dev.arcade.core.ClientOptions +import dev.arcade.core.Sleeper +import dev.arcade.core.Timeout +import dev.arcade.core.http.AsyncStreamResponse import dev.arcade.core.http.Headers +import dev.arcade.core.http.HttpClient import dev.arcade.core.http.QueryParams +import dev.arcade.core.jsonMapper import java.net.Proxy import java.time.Clock import java.time.Duration - +import java.util.Optional +import java.util.concurrent.Executor +import java.util.concurrent.ExecutorService +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 [ArcadeClientAsync] with [OkHttpClient] as the + * underlying [HttpClient]. + */ class ArcadeOkHttpClientAsync private constructor() { companion object { + /** Returns a mutable builder for constructing an instance of [ArcadeClientAsync]. */ @JvmStatic fun builder() = Builder() + /** + * Returns a client configured using system properties and environment variables. + * + * @see ClientOptions.Builder.fromEnv + */ @JvmStatic fun fromEnv(): ArcadeClientAsync = builder().fromEnv().build() } @@ -25,20 +47,233 @@ class ArcadeOkHttpClientAsync private constructor() { class Builder internal constructor() { private var clientOptions: ClientOptions.Builder = ClientOptions.builder() - private var baseUrl: String = ClientOptions.PRODUCTION_URL - // The default timeout for the client is 1 minute. - private var timeout: Duration = Duration.ofSeconds(60) + private var dispatcherExecutorService: ExecutorService? = null private var proxy: Proxy? = null + private var maxIdleConnections: Int? = null + private var keepAliveDuration: Duration? = null + private var sslSocketFactory: SSLSocketFactory? = null + private var trustManager: X509TrustManager? = null + private var hostnameVerifier: HostnameVerifier? = null + + /** + * The executor service to use for running HTTP requests. + * + * Defaults to OkHttp's + * [default executor service](https://github.com/square/okhttp/blob/ace792f443b2ffb17974f5c0d1cecdf589309f26/okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dispatcher.kt#L98-L104). + * + * This class takes ownership of the executor service and shuts it down when closed. + */ + fun dispatcherExecutorService(dispatcherExecutorService: ExecutorService?) = apply { + this.dispatcherExecutorService = dispatcherExecutorService + } + + /** + * Alias for calling [Builder.dispatcherExecutorService] with + * `dispatcherExecutorService.orElse(null)`. + */ + fun dispatcherExecutorService(dispatcherExecutorService: Optional) = + dispatcherExecutorService(dispatcherExecutorService.getOrNull()) + + 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 maximum number of idle connections kept by the underlying OkHttp connection pool. + * + * If this is set, then [keepAliveDuration] must also be set. + * + * If unset, then OkHttp's default is used. + */ + fun maxIdleConnections(maxIdleConnections: Int?) = apply { + this.maxIdleConnections = maxIdleConnections + } + + /** + * Alias for [Builder.maxIdleConnections]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun maxIdleConnections(maxIdleConnections: Int) = + maxIdleConnections(maxIdleConnections as Int?) + + /** + * Alias for calling [Builder.maxIdleConnections] with `maxIdleConnections.orElse(null)`. + */ + fun maxIdleConnections(maxIdleConnections: Optional) = + maxIdleConnections(maxIdleConnections.getOrNull()) + + /** + * The keep-alive duration for idle connections in the underlying OkHttp connection pool. + * + * If this is set, then [maxIdleConnections] must also be set. + * + * If unset, then OkHttp's default is used. + */ + fun keepAliveDuration(keepAliveDuration: Duration?) = apply { + this.keepAliveDuration = keepAliveDuration + } + + /** Alias for calling [Builder.keepAliveDuration] with `keepAliveDuration.orElse(null)`. */ + fun keepAliveDuration(keepAliveDuration: Optional) = + keepAliveDuration(keepAliveDuration.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 + } - fun baseUrl(baseUrl: String) = apply { - clientOptions.baseUrl(baseUrl) - this.baseUrl = baseUrl + /** 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 [dev.arcade.core.jsonMapper]. The default is usually sufficient and rarely + * needs to be overridden. + */ fun jsonMapper(jsonMapper: JsonMapper) = apply { clientOptions.jsonMapper(jsonMapper) } + /** + * The executor to use for running [AsyncStreamResponse.Handler] callbacks. + * + * Defaults to a dedicated cached thread pool. + * + * This class takes ownership of the executor and shuts it down, if possible, when closed. + */ + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + clientOptions.streamHandlerExecutor(streamHandlerExecutor) + } + + /** + * The interface to use for delaying execution, like during retries. + * + * This is primarily useful for using fake delays in tests. + * + * Defaults to real execution delays. + * + * This class takes ownership of the sleeper and closes it when closed. + */ + fun sleeper(sleeper: Sleeper) = apply { clientOptions.sleeper(sleeper) } + + /** + * 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.arcade.dev`. + */ + 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) } + + /** API key used for authorization in header */ + fun apiKey(apiKey: String) = apply { clientOptions.apiKey(apiKey) } + fun headers(headers: Headers) = apply { clientOptions.headers(headers) } fun headers(headers: Map>) = apply { @@ -119,28 +354,31 @@ class ArcadeOkHttpClientAsync private constructor() { clientOptions.removeAllQueryParams(keys) } - fun timeout(timeout: Duration) = apply { this.timeout = timeout } - - fun maxRetries(maxRetries: Int) = apply { clientOptions.maxRetries(maxRetries) } - - fun proxy(proxy: Proxy) = apply { this.proxy = proxy } - - fun responseValidation(responseValidation: Boolean) = apply { - clientOptions.responseValidation(responseValidation) - } - - fun apiKey(apiKey: String) = apply { clientOptions.apiKey(apiKey) } - + /** + * Updates configuration using system properties and environment variables. + * + * @see ClientOptions.Builder.fromEnv + */ fun fromEnv() = apply { clientOptions.fromEnv() } + /** + * Returns an immutable instance of [ArcadeClientAsync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): ArcadeClientAsync = ArcadeClientAsyncImpl( clientOptions .httpClient( OkHttpClient.builder() - .baseUrl(baseUrl) - .timeout(timeout) + .timeout(clientOptions.timeout()) .proxy(proxy) + .maxIdleConnections(maxIdleConnections) + .keepAliveDuration(keepAliveDuration) + .dispatcherExecutorService(dispatcherExecutorService) + .sslSocketFactory(sslSocketFactory) + .trustManager(trustManager) + .hostnameVerifier(hostnameVerifier) .build() ) .build() diff --git a/arcade-java-client-okhttp/src/main/kotlin/dev/arcade/client/okhttp/OkHttpClient.kt b/arcade-java-client-okhttp/src/main/kotlin/dev/arcade/client/okhttp/OkHttpClient.kt index 55a1501..decc575 100644 --- a/arcade-java-client-okhttp/src/main/kotlin/dev/arcade/client/okhttp/OkHttpClient.kt +++ b/arcade-java-client-okhttp/src/main/kotlin/dev/arcade/client/okhttp/OkHttpClient.kt @@ -1,7 +1,7 @@ package dev.arcade.client.okhttp import dev.arcade.core.RequestOptions -import dev.arcade.core.checkRequired +import dev.arcade.core.Timeout import dev.arcade.core.http.Headers import dev.arcade.core.http.HttpClient import dev.arcade.core.http.HttpMethod @@ -13,10 +13,17 @@ import java.io.IOException import java.io.InputStream import java.net.Proxy import java.time.Duration +import java.util.concurrent.CancellationException import java.util.concurrent.CompletableFuture +import java.util.concurrent.ExecutorService +import java.util.concurrent.TimeUnit +import javax.net.ssl.HostnameVerifier +import javax.net.ssl.SSLSocketFactory +import javax.net.ssl.X509TrustManager import okhttp3.Call import okhttp3.Callback -import okhttp3.HttpUrl +import okhttp3.ConnectionPool +import okhttp3.Dispatcher import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.MediaType import okhttp3.MediaType.Companion.toMediaType @@ -28,8 +35,7 @@ import okhttp3.logging.HttpLoggingInterceptor import okio.BufferedSink class OkHttpClient -private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val baseUrl: HttpUrl) : - HttpClient { +internal constructor(@JvmSynthetic internal val okHttpClient: okhttp3.OkHttpClient) : HttpClient { override fun execute(request: HttpRequest, requestOptions: RequestOptions): HttpResponse { val call = newCall(request, requestOptions) @@ -49,20 +55,25 @@ private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val ): 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()) - } + val call = newCall(request, requestOptions) + call.enqueue( + object : Callback { + override fun onResponse(call: Call, response: Response) { + future.complete(response.toResponse()) + } - override fun onFailure(call: Call, e: IOException) { - future.completeExceptionally(ArcadeIoException("Request failed", e)) - } + override fun onFailure(call: Call, e: IOException) { + future.completeExceptionally(ArcadeIoException("Request failed", e)) } - ) + } + ) + + future.whenComplete { _, e -> + if (e is CancellationException) { + call.cancel() + } + request.body?.close() + } return future } @@ -88,13 +99,12 @@ private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val ) } - val timeout = requestOptions.timeout - if (timeout != null) { + requestOptions.timeout?.let { clientBuilder - .connectTimeout(timeout) - .readTimeout(timeout) - .writeTimeout(timeout) - .callTimeout(if (timeout.seconds == 0L) timeout else timeout.plusSeconds(30)) + .connectTimeout(it.connect()) + .readTimeout(it.read()) + .writeTimeout(it.write()) + .callTimeout(it.request()) } val client = clientBuilder.build() @@ -109,19 +119,19 @@ private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val val builder = Request.Builder().url(toUrl()).method(method.name, body) headers.names().forEach { name -> - headers.values(name).forEach { builder.header(name, it) } + headers.values(name).forEach { builder.addHeader(name, it) } } if ( !headers.names().contains("X-Stainless-Read-Timeout") && client.readTimeoutMillis != 0 ) { - builder.header( + builder.addHeader( "X-Stainless-Read-Timeout", Duration.ofMillis(client.readTimeoutMillis.toLong()).seconds.toString(), ) } if (!headers.names().contains("X-Stainless-Timeout") && client.callTimeoutMillis != 0) { - builder.header( + builder.addHeader( "X-Stainless-Timeout", Duration.ofMillis(client.callTimeoutMillis.toLong()).seconds.toString(), ) @@ -140,11 +150,7 @@ private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val } private fun HttpRequest.toUrl(): String { - url?.let { - return it - } - - val builder = baseUrl.newBuilder() + val builder = baseUrl.toHttpUrl().newBuilder() pathSegments.forEach(builder::addPathSegment) queryParams.keys().forEach { key -> queryParams.values(key).forEach { builder.addQueryParameter(key, it) } @@ -194,27 +200,106 @@ private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val class Builder internal constructor() { - private var baseUrl: HttpUrl? = null - // The default timeout is 1 minute. - private var timeout: Duration = Duration.ofSeconds(60) + private var timeout: Timeout = Timeout.default() private var proxy: Proxy? = null + private var maxIdleConnections: Int? = null + private var keepAliveDuration: Duration? = null + private var dispatcherExecutorService: ExecutorService? = null + private var sslSocketFactory: SSLSocketFactory? = null + private var trustManager: X509TrustManager? = null + private var hostnameVerifier: HostnameVerifier? = null - fun baseUrl(baseUrl: String) = apply { this.baseUrl = baseUrl.toHttpUrl() } + fun timeout(timeout: Timeout) = apply { this.timeout = timeout } - fun timeout(timeout: Duration) = apply { this.timeout = timeout } + fun timeout(timeout: Duration) = timeout(Timeout.builder().request(timeout).build()) fun proxy(proxy: Proxy?) = apply { this.proxy = proxy } + /** + * Sets the maximum number of idle connections kept by the underlying [ConnectionPool]. + * + * If this is set, then [keepAliveDuration] must also be set. + * + * If unset, then OkHttp's default is used. + */ + fun maxIdleConnections(maxIdleConnections: Int?) = apply { + this.maxIdleConnections = maxIdleConnections + } + + /** + * Sets the keep-alive duration for idle connections in the underlying [ConnectionPool]. + * + * If this is set, then [maxIdleConnections] must also be set. + * + * If unset, then OkHttp's default is used. + */ + fun keepAliveDuration(keepAliveDuration: Duration?) = apply { + this.keepAliveDuration = keepAliveDuration + } + + fun dispatcherExecutorService(dispatcherExecutorService: ExecutorService?) = apply { + this.dispatcherExecutorService = dispatcherExecutorService + } + + 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) - .readTimeout(timeout) - .writeTimeout(timeout) - .callTimeout(if (timeout.seconds == 0L) timeout else timeout.plusSeconds(30)) + // `RetryingHttpClient` handles retries if the user enabled them. + .retryOnConnectionFailure(false) + .connectTimeout(timeout.connect()) + .readTimeout(timeout.read()) + .writeTimeout(timeout.write()) + .callTimeout(timeout.request()) .proxy(proxy) - .build(), - checkRequired("baseUrl", baseUrl), + .apply { + dispatcherExecutorService?.let { dispatcher(Dispatcher(it)) } + + val maxIdleConnections = maxIdleConnections + val keepAliveDuration = keepAliveDuration + if (maxIdleConnections != null && keepAliveDuration != null) { + connectionPool( + ConnectionPool( + maxIdleConnections, + keepAliveDuration.toNanos(), + TimeUnit.NANOSECONDS, + ) + ) + } else { + check((maxIdleConnections != null) == (keepAliveDuration != null)) { + "Both or none of `maxIdleConnections` and `keepAliveDuration` must be set, but only one was set" + } + } + + 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/arcade-java-client-okhttp/src/test/kotlin/dev/arcade/client/okhttp/OkHttpClientTest.kt b/arcade-java-client-okhttp/src/test/kotlin/dev/arcade/client/okhttp/OkHttpClientTest.kt new file mode 100644 index 0000000..fcd93ab --- /dev/null +++ b/arcade-java-client-okhttp/src/test/kotlin/dev/arcade/client/okhttp/OkHttpClientTest.kt @@ -0,0 +1,44 @@ +package dev.arcade.client.okhttp + +import com.github.tomakehurst.wiremock.client.WireMock.* +import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo +import com.github.tomakehurst.wiremock.junit5.WireMockTest +import dev.arcade.core.http.HttpMethod +import dev.arcade.core.http.HttpRequest +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.parallel.ResourceLock + +@WireMockTest +@ResourceLock("https://github.com/wiremock/wiremock/issues/169") +internal class OkHttpClientTest { + + private lateinit var baseUrl: String + private lateinit var httpClient: OkHttpClient + + @BeforeEach + fun beforeEach(wmRuntimeInfo: WireMockRuntimeInfo) { + baseUrl = wmRuntimeInfo.httpBaseUrl + httpClient = OkHttpClient.builder().build() + } + + @Test + fun executeAsync_whenFutureCancelled_cancelsUnderlyingCall() { + stubFor(post(urlPathEqualTo("/something")).willReturn(ok())) + val responseFuture = + httpClient.executeAsync( + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(baseUrl) + .addPathSegment("something") + .build() + ) + val call = httpClient.okHttpClient.dispatcher.runningCalls().single() + + responseFuture.cancel(false) + + // Should have cancelled the underlying call + assertThat(call.isCanceled()).isTrue() + } +} diff --git a/arcade-java-core/build.gradle.kts b/arcade-java-core/build.gradle.kts index fe1757b..6cd527c 100644 --- a/arcade-java-core/build.gradle.kts +++ b/arcade-java-core/build.gradle.kts @@ -3,23 +3,38 @@ plugins { id("arcade.publish") } +configurations.all { + resolutionStrategy { + // Compile and test against a lower Jackson version to ensure we're compatible with it. Note that + // we generally support 2.13.4, but test against 2.14.0 because 2.13.4 has some annoying (but + // niche) bugs (users should upgrade if they encounter them). 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.14.0") + force("com.fasterxml.jackson.core:jackson-databind:2.14.0") + force("com.fasterxml.jackson.core:jackson-annotations:2.14.0") + force("com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.14.0") + force("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.14.0") + force("com.fasterxml.jackson.module:jackson-module-kotlin:2.14.0") + } +} + dependencies { - api("com.fasterxml.jackson.core:jackson-core:2.18.1") - api("com.fasterxml.jackson.core:jackson-databind:2.18.1") + 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.1") - implementation("com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.18.1") - implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.18.1") - implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.18.1") - implementation("org.apache.httpcomponents.core5:httpcore5:5.2.4") - implementation("org.apache.httpcomponents.client5:httpclient5:5.3.1") + 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") testImplementation(kotlin("test")) testImplementation(project(":arcade-java-client-okhttp")) testImplementation("com.github.tomakehurst:wiremock-jre8:2.35.2") - testImplementation("org.assertj:assertj-core:3.25.3") + testImplementation("org.assertj:assertj-core:3.27.7") 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/arcade-java-core/src/main/kotlin/dev/arcade/client/ArcadeClient.kt b/arcade-java-core/src/main/kotlin/dev/arcade/client/ArcadeClient.kt index bf05325..167ce86 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/client/ArcadeClient.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/client/ArcadeClient.kt @@ -2,12 +2,14 @@ package dev.arcade.client +import dev.arcade.core.ClientOptions import dev.arcade.services.blocking.AdminService import dev.arcade.services.blocking.AuthService import dev.arcade.services.blocking.ChatService import dev.arcade.services.blocking.HealthService import dev.arcade.services.blocking.ToolService import dev.arcade.services.blocking.WorkerService +import java.util.function.Consumer /** * A client for interacting with the Arcade REST API synchronously. You can also switch to @@ -33,6 +35,18 @@ interface ArcadeClient { */ fun async(): ArcadeClientAsync + /** + * 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): ArcadeClient + fun admin(): AdminService fun auth(): AuthService @@ -57,4 +71,27 @@ interface ArcadeClient { * method. */ fun close() + + /** A view of [ArcadeClient] 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): ArcadeClient.WithRawResponse + + fun admin(): AdminService.WithRawResponse + + fun auth(): AuthService.WithRawResponse + + fun health(): HealthService.WithRawResponse + + fun chat(): ChatService.WithRawResponse + + fun tools(): ToolService.WithRawResponse + + fun workers(): WorkerService.WithRawResponse + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/client/ArcadeClientAsync.kt b/arcade-java-core/src/main/kotlin/dev/arcade/client/ArcadeClientAsync.kt index 9830ae4..fddb75a 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/client/ArcadeClientAsync.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/client/ArcadeClientAsync.kt @@ -2,12 +2,14 @@ package dev.arcade.client +import dev.arcade.core.ClientOptions import dev.arcade.services.async.AdminServiceAsync import dev.arcade.services.async.AuthServiceAsync import dev.arcade.services.async.ChatServiceAsync import dev.arcade.services.async.HealthServiceAsync import dev.arcade.services.async.ToolServiceAsync import dev.arcade.services.async.WorkerServiceAsync +import java.util.function.Consumer /** * A client for interacting with the Arcade REST API asynchronously. You can also switch to @@ -33,6 +35,18 @@ interface ArcadeClientAsync { */ fun sync(): ArcadeClient + /** + * 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): ArcadeClientAsync + fun admin(): AdminServiceAsync fun auth(): AuthServiceAsync @@ -57,4 +71,29 @@ interface ArcadeClientAsync { * method. */ fun close() + + /** A view of [ArcadeClientAsync] 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 + ): ArcadeClientAsync.WithRawResponse + + fun admin(): AdminServiceAsync.WithRawResponse + + fun auth(): AuthServiceAsync.WithRawResponse + + fun health(): HealthServiceAsync.WithRawResponse + + fun chat(): ChatServiceAsync.WithRawResponse + + fun tools(): ToolServiceAsync.WithRawResponse + + fun workers(): WorkerServiceAsync.WithRawResponse + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/client/ArcadeClientAsyncImpl.kt b/arcade-java-core/src/main/kotlin/dev/arcade/client/ArcadeClientAsyncImpl.kt index 7b822b1..b644fcb 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/client/ArcadeClientAsyncImpl.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/client/ArcadeClientAsyncImpl.kt @@ -16,6 +16,7 @@ import dev.arcade.services.async.ToolServiceAsync import dev.arcade.services.async.ToolServiceAsyncImpl import dev.arcade.services.async.WorkerServiceAsync import dev.arcade.services.async.WorkerServiceAsyncImpl +import java.util.function.Consumer class ArcadeClientAsyncImpl(private val clientOptions: ClientOptions) : ArcadeClientAsync { @@ -30,6 +31,10 @@ class ArcadeClientAsyncImpl(private val clientOptions: ClientOptions) : ArcadeCl // Pass the original clientOptions so that this client sets its own User-Agent. private val sync: ArcadeClient by lazy { ArcadeClientImpl(clientOptions) } + private val withRawResponse: ArcadeClientAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + private val admin: AdminServiceAsync by lazy { AdminServiceAsyncImpl(clientOptionsWithUserAgent) } @@ -50,6 +55,11 @@ class ArcadeClientAsyncImpl(private val clientOptions: ClientOptions) : ArcadeCl override fun sync(): ArcadeClient = sync + override fun withRawResponse(): ArcadeClientAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): ArcadeClientAsync = + ArcadeClientAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + override fun admin(): AdminServiceAsync = admin override fun auth(): AuthServiceAsync = auth @@ -62,5 +72,52 @@ class ArcadeClientAsyncImpl(private val clientOptions: ClientOptions) : ArcadeCl override fun workers(): WorkerServiceAsync = workers - override fun close() = clientOptions.httpClient.close() + override fun close() = clientOptions.close() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ArcadeClientAsync.WithRawResponse { + + private val admin: AdminServiceAsync.WithRawResponse by lazy { + AdminServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val auth: AuthServiceAsync.WithRawResponse by lazy { + AuthServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val health: HealthServiceAsync.WithRawResponse by lazy { + HealthServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val chat: ChatServiceAsync.WithRawResponse by lazy { + ChatServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val tools: ToolServiceAsync.WithRawResponse by lazy { + ToolServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val workers: WorkerServiceAsync.WithRawResponse by lazy { + WorkerServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + override fun withOptions( + modifier: Consumer + ): ArcadeClientAsync.WithRawResponse = + ArcadeClientAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun admin(): AdminServiceAsync.WithRawResponse = admin + + override fun auth(): AuthServiceAsync.WithRawResponse = auth + + override fun health(): HealthServiceAsync.WithRawResponse = health + + override fun chat(): ChatServiceAsync.WithRawResponse = chat + + override fun tools(): ToolServiceAsync.WithRawResponse = tools + + override fun workers(): WorkerServiceAsync.WithRawResponse = workers + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/client/ArcadeClientImpl.kt b/arcade-java-core/src/main/kotlin/dev/arcade/client/ArcadeClientImpl.kt index d8a7714..c399738 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/client/ArcadeClientImpl.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/client/ArcadeClientImpl.kt @@ -16,6 +16,7 @@ import dev.arcade.services.blocking.ToolService import dev.arcade.services.blocking.ToolServiceImpl import dev.arcade.services.blocking.WorkerService import dev.arcade.services.blocking.WorkerServiceImpl +import java.util.function.Consumer class ArcadeClientImpl(private val clientOptions: ClientOptions) : ArcadeClient { @@ -30,6 +31,10 @@ class ArcadeClientImpl(private val clientOptions: ClientOptions) : ArcadeClient // Pass the original clientOptions so that this client sets its own User-Agent. private val async: ArcadeClientAsync by lazy { ArcadeClientAsyncImpl(clientOptions) } + private val withRawResponse: ArcadeClient.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + private val admin: AdminService by lazy { AdminServiceImpl(clientOptionsWithUserAgent) } private val auth: AuthService by lazy { AuthServiceImpl(clientOptionsWithUserAgent) } @@ -44,6 +49,11 @@ class ArcadeClientImpl(private val clientOptions: ClientOptions) : ArcadeClient override fun async(): ArcadeClientAsync = async + override fun withRawResponse(): ArcadeClient.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): ArcadeClient = + ArcadeClientImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + override fun admin(): AdminService = admin override fun auth(): AuthService = auth @@ -56,5 +66,52 @@ class ArcadeClientImpl(private val clientOptions: ClientOptions) : ArcadeClient override fun workers(): WorkerService = workers - override fun close() = clientOptions.httpClient.close() + override fun close() = clientOptions.close() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ArcadeClient.WithRawResponse { + + private val admin: AdminService.WithRawResponse by lazy { + AdminServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val auth: AuthService.WithRawResponse by lazy { + AuthServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val health: HealthService.WithRawResponse by lazy { + HealthServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val chat: ChatService.WithRawResponse by lazy { + ChatServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val tools: ToolService.WithRawResponse by lazy { + ToolServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val workers: WorkerService.WithRawResponse by lazy { + WorkerServiceImpl.WithRawResponseImpl(clientOptions) + } + + override fun withOptions( + modifier: Consumer + ): ArcadeClient.WithRawResponse = + ArcadeClientImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun admin(): AdminService.WithRawResponse = admin + + override fun auth(): AuthService.WithRawResponse = auth + + override fun health(): HealthService.WithRawResponse = health + + override fun chat(): ChatService.WithRawResponse = chat + + override fun tools(): ToolService.WithRawResponse = tools + + override fun workers(): WorkerService.WithRawResponse = workers + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/core/AutoPager.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/AutoPager.kt new file mode 100644 index 0000000..1b8c446 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/AutoPager.kt @@ -0,0 +1,21 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.core + +import java.util.stream.Stream +import java.util.stream.StreamSupport + +class AutoPager private constructor(private val firstPage: Page) : Iterable { + + companion object { + + fun from(firstPage: Page): AutoPager = AutoPager(firstPage) + } + + override fun iterator(): Iterator = + generateSequence(firstPage) { if (it.hasNextPage()) it.nextPage() else null } + .flatMap { it.items() } + .iterator() + + fun stream(): Stream = StreamSupport.stream(spliterator(), false) +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/core/AutoPagerAsync.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/AutoPagerAsync.kt new file mode 100644 index 0000000..5732bb0 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/AutoPagerAsync.kt @@ -0,0 +1,88 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.core + +import dev.arcade.core.http.AsyncStreamResponse +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.concurrent.CompletionException +import java.util.concurrent.Executor +import java.util.concurrent.atomic.AtomicReference + +class AutoPagerAsync +private constructor(private val firstPage: PageAsync, private val defaultExecutor: Executor) : + AsyncStreamResponse { + + companion object { + + fun from(firstPage: PageAsync, defaultExecutor: Executor): AutoPagerAsync = + AutoPagerAsync(firstPage, defaultExecutor) + } + + private val onCompleteFuture = CompletableFuture() + private val state = AtomicReference(State.NEW) + + override fun subscribe(handler: AsyncStreamResponse.Handler): AsyncStreamResponse = + subscribe(handler, defaultExecutor) + + override fun subscribe( + handler: AsyncStreamResponse.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" + } + + fun PageAsync.handle(): CompletableFuture { + if (state.get() == State.CLOSED) { + return CompletableFuture.completedFuture(null) + } + + items().forEach { handler.onNext(it) } + return if (hasNextPage()) nextPage().thenCompose { it.handle() } + else CompletableFuture.completedFuture(null) + } + + executor.execute { + firstPage.handle().whenComplete { _, error -> + val actualError = + if (error is CompletionException && error.cause != null) error.cause else error + try { + handler.onComplete(Optional.ofNullable(actualError)) + } finally { + try { + if (actualError == null) { + onCompleteFuture.complete(null) + } else { + onCompleteFuture.completeExceptionally(actualError) + } + } finally { + close() + } + } + } + } + } + + override fun onCompleteFuture(): CompletableFuture = onCompleteFuture + + override fun close() { + val previousState = state.getAndSet(State.CLOSED) + if (previousState == State.CLOSED) { + return + } + + // 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/arcade-java-core/src/main/kotlin/dev/arcade/core/BaseDeserializer.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/BaseDeserializer.kt index 598a9c6..cfff911 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/core/BaseDeserializer.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/BaseDeserializer.kt @@ -7,7 +7,6 @@ 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.JsonMappingException import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.deser.ContextualDeserializer import com.fasterxml.jackson.databind.deser.std.StdDeserializer @@ -29,31 +28,17 @@ abstract class BaseDeserializer(type: KClass) : protected abstract fun ObjectCodec.deserialize(node: JsonNode): T - protected fun ObjectCodec.tryDeserialize( - node: JsonNode, - type: TypeReference, - validate: (T) -> Unit = {}, - ): T? { - return try { - readValue(treeAsTokens(node), type).apply(validate) - } catch (e: JsonMappingException) { - null - } catch (e: RuntimeException) { + 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, - validate: (T) -> Unit = {}, - ): T? { - return try { - readValue(treeAsTokens(node), type).apply(validate) - } catch (e: JsonMappingException) { - null - } catch (e: RuntimeException) { + protected fun ObjectCodec.tryDeserialize(node: JsonNode, type: JavaType): T? = + try { + readValue(treeAsTokens(node), type) + } catch (e: Exception) { null } - } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/core/Check.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/Check.kt index df8badc..45eecc4 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/core/Check.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/Check.kt @@ -2,9 +2,27 @@ package dev.arcade.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 { @@ -27,3 +45,52 @@ internal fun checkMaxLength(name: String, value: String, maxLength: Int): String "`$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/ArcadeAI/arcade-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/arcade-java-core/src/main/kotlin/dev/arcade/core/ClientOptions.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/ClientOptions.kt index a794feb..65f5de9 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/core/ClientOptions.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/ClientOptions.kt @@ -3,35 +3,149 @@ package dev.arcade.core import com.fasterxml.jackson.databind.json.JsonMapper +import dev.arcade.core.http.AsyncStreamResponse import dev.arcade.core.http.Headers import dev.arcade.core.http.HttpClient import dev.arcade.core.http.PhantomReachableClosingHttpClient import dev.arcade.core.http.QueryParams import dev.arcade.core.http.RetryingHttpClient import java.time.Clock - +import java.time.Duration +import java.util.Optional +import java.util.concurrent.Executor +import java.util.concurrent.ExecutorService +import java.util.concurrent.Executors +import java.util.concurrent.ThreadFactory +import java.util.concurrent.atomic.AtomicLong +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 `arcade-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 [dev.arcade.core.jsonMapper]. The default is usually sufficient and rarely needs + * to be overridden. + */ @get:JvmName("jsonMapper") val jsonMapper: JsonMapper, + /** + * The executor to use for running [AsyncStreamResponse.Handler] callbacks. + * + * Defaults to a dedicated cached thread pool. + * + * This class takes ownership of the executor and shuts it down, if possible, when closed. + */ + @get:JvmName("streamHandlerExecutor") val streamHandlerExecutor: Executor, + /** + * The interface to use for delaying execution, like during retries. + * + * This is primarily useful for using fake delays in tests. + * + * Defaults to real execution delays. + * + * This class takes ownership of the sleeper and closes it when closed. + */ + @get:JvmName("sleeper") val sleeper: Sleeper, + /** + * 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, - @get:JvmName("baseUrl") val baseUrl: String, + 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, + /** API key used for authorization in header */ @get:JvmName("apiKey") val apiKey: String, ) { + init { + if (checkJacksonVersionCompatibility) { + checkJacksonVersionCompatibility() + } + } + + /** + * The base URL to use for every request. + * + * Defaults to the production environment: `https://api.arcade.dev`. + */ + fun baseUrl(): String = baseUrl ?: PRODUCTION_URL + fun toBuilder() = Builder().from(this) companion object { const val PRODUCTION_URL = "https://api.arcade.dev" + /** + * Returns a mutable builder for constructing an instance of [ClientOptions]. + * + * The following fields are required: + * ```java + * .httpClient() + * .apiKey() + * ``` + */ @JvmStatic fun builder() = Builder() + /** + * Returns options configured using system properties and environment variables. + * + * @see Builder.fromEnv + */ @JvmStatic fun fromEnv(): ClientOptions = builder().fromEnv().build() } @@ -39,42 +153,155 @@ private constructor( class Builder internal constructor() { private var httpClient: HttpClient? = null + private var checkJacksonVersionCompatibility: Boolean = true private var jsonMapper: JsonMapper = jsonMapper() + private var streamHandlerExecutor: Executor? = null + private var sleeper: Sleeper? = null private var clock: Clock = Clock.systemUTC() - private var baseUrl: String = PRODUCTION_URL + 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 apiKey: String? = null @JvmSynthetic internal fun from(clientOptions: ClientOptions) = apply { httpClient = clientOptions.originalHttpClient + checkJacksonVersionCompatibility = clientOptions.checkJacksonVersionCompatibility jsonMapper = clientOptions.jsonMapper + streamHandlerExecutor = clientOptions.streamHandlerExecutor + sleeper = clientOptions.sleeper clock = clientOptions.clock baseUrl = clientOptions.baseUrl headers = clientOptions.headers.toBuilder() queryParams = clientOptions.queryParams.toBuilder() responseValidation = clientOptions.responseValidation + timeout = clientOptions.timeout maxRetries = clientOptions.maxRetries apiKey = clientOptions.apiKey } - fun httpClient(httpClient: HttpClient) = apply { this.httpClient = httpClient } + /** + * The HTTP client to use in the SDK. + * + * Use the one published in `arcade-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 [dev.arcade.core.jsonMapper]. The default is usually sufficient and rarely + * needs to be overridden. + */ fun jsonMapper(jsonMapper: JsonMapper) = apply { this.jsonMapper = jsonMapper } - fun clock(clock: Clock) = apply { this.clock = clock } + /** + * The executor to use for running [AsyncStreamResponse.Handler] callbacks. + * + * Defaults to a dedicated cached thread pool. + * + * This class takes ownership of the executor and shuts it down, if possible, when closed. + */ + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + this.streamHandlerExecutor = + if (streamHandlerExecutor is ExecutorService) + PhantomReachableExecutorService(streamHandlerExecutor) + else streamHandlerExecutor + } - fun baseUrl(baseUrl: String) = apply { this.baseUrl = baseUrl } + /** + * The interface to use for delaying execution, like during retries. + * + * This is primarily useful for using fake delays in tests. + * + * Defaults to real execution delays. + * + * This class takes ownership of the sleeper and closes it when closed. + */ + fun sleeper(sleeper: Sleeper) = apply { this.sleeper = PhantomReachableSleeper(sleeper) } + + /** + * 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.arcade.dev`. + */ + 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 } + /** API key used for authorization in header */ fun apiKey(apiKey: String) = apply { this.apiKey = apiKey } fun headers(headers: Headers) = apply { @@ -157,10 +384,63 @@ private constructor( fun removeAllQueryParams(keys: Set) = apply { queryParams.removeAll(keys) } - fun fromEnv() = apply { System.getenv("ARCADE_API_KEY")?.let { apiKey(it) } } + 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 | + * |---------|----------------|--------------------|--------|--------------------------| + * |`apiKey` |`arcade.apiKey` |`ARCADE_API_KEY` |true |- | + * |`baseUrl`|`arcade.baseUrl`|`ARCADE_BASE_URL` |true |`"https://api.arcade.dev"`| + * + * System properties take precedence over environment variables. + */ + fun fromEnv() = apply { + (System.getProperty("arcade.baseUrl") ?: System.getenv("ARCADE_BASE_URL"))?.let { + baseUrl(it) + } + (System.getProperty("arcade.apiKey") ?: System.getenv("ARCADE_API_KEY"))?.let { + apiKey(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() + * .apiKey() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): ClientOptions { val httpClient = checkRequired("httpClient", httpClient) + val streamHandlerExecutor = + streamHandlerExecutor + ?: PhantomReachableExecutorService( + Executors.newCachedThreadPool( + object : ThreadFactory { + + private val threadFactory: ThreadFactory = + Executors.defaultThreadFactory() + private val count = AtomicLong(0) + + override fun newThread(runnable: Runnable): Thread = + threadFactory.newThread(runnable).also { + it.name = + "arcade-stream-handler-thread-${count.getAndIncrement()}" + } + } + ) + ) + val sleeper = sleeper ?: PhantomReachableSleeper(DefaultSleeper()) val apiKey = checkRequired("apiKey", apiKey) val headers = Headers.builder() @@ -172,6 +452,7 @@ private constructor( headers.put("X-Stainless-Package-Version", getPackageVersion()) headers.put("X-Stainless-Runtime", "JRE") headers.put("X-Stainless-Runtime-Version", getJavaVersion()) + headers.put("X-Stainless-Kotlin-Version", KotlinVersion.CURRENT.toString()) apiKey.let { if (!it.isEmpty()) { headers.put("Authorization", it) @@ -182,22 +463,41 @@ private constructor( return ClientOptions( httpClient, - PhantomReachableClosingHttpClient( - RetryingHttpClient.builder() - .httpClient(httpClient) - .clock(clock) - .maxRetries(maxRetries) - .build() - ), + RetryingHttpClient.builder() + .httpClient(httpClient) + .sleeper(sleeper) + .clock(clock) + .maxRetries(maxRetries) + .build(), + checkJacksonVersionCompatibility, jsonMapper, + streamHandlerExecutor, + sleeper, clock, baseUrl, headers.build(), queryParams.build(), responseValidation, + timeout, maxRetries, apiKey, ) } } + + /** + * 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() + (streamHandlerExecutor as? ExecutorService)?.shutdown() + sleeper.close() + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/core/DefaultSleeper.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/DefaultSleeper.kt new file mode 100644 index 0000000..75b3383 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/DefaultSleeper.kt @@ -0,0 +1,28 @@ +package dev.arcade.core + +import java.time.Duration +import java.util.Timer +import java.util.TimerTask +import java.util.concurrent.CompletableFuture + +class DefaultSleeper : Sleeper { + + private val timer = Timer("DefaultSleeper", 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 + } + + override fun close() = timer.cancel() +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/core/HttpRequestBodies.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/HttpRequestBodies.kt deleted file mode 100644 index 18cb3ba..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/core/HttpRequestBodies.kt +++ /dev/null @@ -1,108 +0,0 @@ -@file:JvmName("HttpRequestBodies") - -package dev.arcade.core - -import com.fasterxml.jackson.databind.json.JsonMapper -import dev.arcade.core.http.HttpRequestBody -import dev.arcade.errors.ArcadeException -import java.io.ByteArrayOutputStream -import java.io.OutputStream -import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder - -@JvmSynthetic -internal inline fun json(jsonMapper: JsonMapper, value: T): HttpRequestBody { - return object : HttpRequestBody { - private var cachedBytes: ByteArray? = null - - private fun serialize(): ByteArray { - if (cachedBytes != null) return cachedBytes!! - - val buffer = ByteArrayOutputStream() - try { - jsonMapper.writeValue(buffer, value) - cachedBytes = buffer.toByteArray() - return cachedBytes!! - } catch (e: Exception) { - throw ArcadeException("Error writing request", e) - } - } - - override fun writeTo(outputStream: OutputStream) { - outputStream.write(serialize()) - } - - override fun contentType(): String = "application/json" - - override fun contentLength(): Long { - return serialize().size.toLong() - } - - override fun repeatable(): Boolean = true - - override fun close() {} - } -} - -@JvmSynthetic -internal fun multipartFormData( - jsonMapper: JsonMapper, - parts: Array?>, -): HttpRequestBody { - val builder = MultipartEntityBuilder.create() - parts.forEach { part -> - if (part?.value != null) { - when (part.value) { - is JsonValue -> { - val buffer = ByteArrayOutputStream() - try { - jsonMapper.writeValue(buffer, part.value) - } catch (e: Exception) { - throw ArcadeException("Error serializing value to json", e) - } - builder.addBinaryBody( - part.name, - buffer.toByteArray(), - part.contentType, - part.filename, - ) - } - is Boolean -> - builder.addTextBody( - part.name, - if (part.value) "true" else "false", - part.contentType, - ) - is Int -> builder.addTextBody(part.name, part.value.toString(), part.contentType) - is Long -> builder.addTextBody(part.name, part.value.toString(), part.contentType) - is Double -> builder.addTextBody(part.name, part.value.toString(), part.contentType) - is ByteArray -> - builder.addBinaryBody(part.name, part.value, part.contentType, part.filename) - is String -> builder.addTextBody(part.name, part.value, part.contentType) - is Enum -> builder.addTextBody(part.name, part.value.toString(), part.contentType) - else -> - throw IllegalArgumentException( - "Unsupported content type: ${part.value::class.java.simpleName}" - ) - } - } - } - val entity = builder.build() - - return object : HttpRequestBody { - override fun writeTo(outputStream: OutputStream) { - try { - return entity.writeTo(outputStream) - } catch (e: Exception) { - throw ArcadeException("Error writing request", e) - } - } - - override fun contentType(): String = entity.contentType - - override fun contentLength(): Long = -1 - - override fun repeatable(): Boolean = entity.isRepeatable - - override fun close() = entity.close() - } -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/core/ObjectMappers.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/ObjectMappers.kt index f255b25..9fb2ee7 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/core/ObjectMappers.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/ObjectMappers.kt @@ -3,23 +3,176 @@ package dev.arcade.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.cfg.CoercionAction.Fail -import com.fasterxml.jackson.databind.cfg.CoercionInputShape.Integer +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.jacksonMapperBuilder +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.OffsetDateTime +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import java.time.temporal.ChronoField fun jsonMapper(): JsonMapper = - jacksonMapperBuilder() + JsonMapper.builder() + .addModule(kotlinModule()) .addModule(Jdk8Module()) .addModule(JavaTimeModule()) + .addModule( + SimpleModule() + .addSerializer(InputStreamSerializer) + .addDeserializer(OffsetDateTime::class.java, LenientOffsetDateTimeDeserializer()) + ) + .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.Float, 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.DateTime) { + it.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) - .withCoercionConfig(String::class.java) { it.setCoercion(Integer, Fail) } + .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 [OffsetDateTime] from datetimes, dates, and zoned datetimes. + */ +private class LenientOffsetDateTimeDeserializer : + StdDeserializer(OffsetDateTime::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): OffsetDateTime { + 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() + .atZone(ZoneId.of("UTC")) + .toOffsetDateTime() + !temporal.isSupported(ChronoField.OFFSET_SECONDS) -> + LocalDateTime.from(temporal).atZone(ZoneId.of("UTC")).toOffsetDateTime() + else -> OffsetDateTime.from(temporal) + } + } catch (e: DateTimeException) { + exceptions.add(e) + } + } + + throw JsonParseException(p, "Cannot parse `OffsetDateTime` from value: ${p.text}").apply { + exceptions.forEach { addSuppressed(it) } + } + } +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/core/Page.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/Page.kt new file mode 100644 index 0000000..633fa85 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/Page.kt @@ -0,0 +1,33 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.core + +/** + * An interface representing a single page, with items of type [T], from a paginated endpoint + * response. + * + * Implementations of this interface are expected to request additional pages synchronously. For + * asynchronous pagination, see the [PageAsync] interface. + */ +interface Page { + + /** + * Returns whether there's another page after this one. + * + * The method generally doesn't make requests so the result depends entirely on the data in this + * page. If a significant amount of time has passed between requesting this page and calling + * this method, then the result could be stale. + */ + fun hasNextPage(): Boolean + + /** + * Returns the page after this one by making another request. + * + * @throws IllegalStateException if it's impossible to get the next page. This exception is + * avoidable by calling [hasNextPage] first. + */ + fun nextPage(): Page + + /** Returns the items in this page. */ + fun items(): List +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/core/PageAsync.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/PageAsync.kt new file mode 100644 index 0000000..c506a09 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/PageAsync.kt @@ -0,0 +1,35 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.core + +import java.util.concurrent.CompletableFuture + +/** + * An interface representing a single page, with items of type [T], from a paginated endpoint + * response. + * + * Implementations of this interface are expected to request additional pages asynchronously. For + * synchronous pagination, see the [Page] interface. + */ +interface PageAsync { + + /** + * Returns whether there's another page after this one. + * + * The method generally doesn't make requests so the result depends entirely on the data in this + * page. If a significant amount of time has passed between requesting this page and calling + * this method, then the result could be stale. + */ + fun hasNextPage(): Boolean + + /** + * Returns the page after this one by making another request. + * + * @throws IllegalStateException if it's impossible to get the next page. This exception is + * avoidable by calling [hasNextPage] first. + */ + fun nextPage(): CompletableFuture> + + /** Returns the items in this page. */ + fun items(): List +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/core/PhantomReachableExecutorService.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/PhantomReachableExecutorService.kt new file mode 100644 index 0000000..9af39d7 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/PhantomReachableExecutorService.kt @@ -0,0 +1,58 @@ +package dev.arcade.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/arcade-java-core/src/main/kotlin/dev/arcade/core/PhantomReachableSleeper.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/PhantomReachableSleeper.kt new file mode 100644 index 0000000..038b7ae --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/PhantomReachableSleeper.kt @@ -0,0 +1,23 @@ +package dev.arcade.core + +import java.time.Duration +import java.util.concurrent.CompletableFuture + +/** + * A delegating wrapper around a [Sleeper] that closes it once it's only phantom reachable. + * + * This class ensures the [Sleeper] is closed even if the user forgets to do it. + */ +internal class PhantomReachableSleeper(private val sleeper: Sleeper) : Sleeper { + + init { + closeWhenPhantomReachable(this, sleeper) + } + + override fun sleep(duration: Duration) = sleeper.sleep(duration) + + override fun sleepAsync(duration: Duration): CompletableFuture = + sleeper.sleepAsync(duration) + + override fun close() = sleeper.close() +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/core/Properties.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/Properties.kt index ed1e1a9..bd222b4 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/core/Properties.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/Properties.kt @@ -2,7 +2,7 @@ package dev.arcade.core -import java.util.Properties +import dev.arcade.client.ArcadeClient fun getOsArch(): String { val osArch = System.getProperty("os.arch") @@ -16,7 +16,7 @@ fun getOsArch(): String { "x86_64" -> "x64" "arm" -> "arm" "aarch64" -> "arm64" - else -> "other:${osArch}" + else -> "other:$osArch" } } @@ -30,13 +30,13 @@ fun getOsName(): String { osName.startsWith("Linux") -> "Linux" osName.startsWith("Mac OS") -> "MacOS" osName.startsWith("Windows") -> "Windows" - else -> "Other:${osName}" + else -> "Other:$osName" } } -fun getOsVersion(): String = System.getProperty("os.version", "unknown") +fun getOsVersion(): String = System.getProperty("os.version", "unknown") ?: "unknown" fun getPackageVersion(): String = - Properties::class.java.`package`.implementationVersion ?: "unknown" + ArcadeClient::class.java.`package`?.implementationVersion ?: "unknown" -fun getJavaVersion(): String = System.getProperty("java.version", "unknown") +fun getJavaVersion(): String = System.getProperty("java.version", "unknown") ?: "unknown" diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/core/RequestOptions.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/RequestOptions.kt index e6ab322..59a7d7f 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/core/RequestOptions.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/RequestOptions.kt @@ -2,13 +2,7 @@ package dev.arcade.core import java.time.Duration -class RequestOptions private constructor(val responseValidation: Boolean?, val timeout: Duration?) { - fun applyDefaults(options: RequestOptions): RequestOptions { - return RequestOptions( - responseValidation = this.responseValidation ?: options.responseValidation, - timeout = this.timeout ?: options.timeout, - ) - } +class RequestOptions private constructor(val responseValidation: Boolean?, val timeout: Timeout?) { companion object { @@ -16,22 +10,37 @@ class RequestOptions private constructor(val responseValidation: Boolean?, val t @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: Duration? = null + private var timeout: Timeout? = null fun responseValidation(responseValidation: Boolean) = apply { this.responseValidation = responseValidation } - fun timeout(timeout: Duration) = apply { this.timeout = timeout } + fun timeout(timeout: Timeout) = apply { this.timeout = timeout } - fun build(): RequestOptions { - return RequestOptions(responseValidation, timeout) - } + fun timeout(timeout: Duration) = timeout(Timeout.builder().request(timeout).build()) + + fun build(): RequestOptions = RequestOptions(responseValidation, timeout) } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/core/Sleeper.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/Sleeper.kt new file mode 100644 index 0000000..4f86b7b --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/Sleeper.kt @@ -0,0 +1,21 @@ +package dev.arcade.core + +import java.time.Duration +import java.util.concurrent.CompletableFuture + +/** + * An interface for delaying execution for a specified amount of time. + * + * Useful for testing and cleaning up resources. + */ +interface Sleeper : AutoCloseable { + + /** Synchronously pauses execution for the given [duration]. */ + fun sleep(duration: Duration) + + /** Asynchronously pauses execution for the given [duration]. */ + fun sleepAsync(duration: Duration): CompletableFuture + + /** Overridden from [AutoCloseable] to not have a checked exception in its signature. */ + override fun close() +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/core/Timeout.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/Timeout.kt new file mode 100644 index 0000000..e632215 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/Timeout.kt @@ -0,0 +1,171 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.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/arcade-java-core/src/main/kotlin/dev/arcade/core/Utils.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/Utils.kt index 022d964..8c7aa5f 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/core/Utils.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/Utils.kt @@ -5,6 +5,8 @@ package dev.arcade.core import dev.arcade.errors.ArcadeInvalidDataException 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 = @@ -25,4 +27,89 @@ internal fun , V> SortedMap.toImmutable(): SortedMap> 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/arcade-java-core/src/main/kotlin/dev/arcade/core/Values.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/Values.kt index 62438a3..b997cd4 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/core/Values.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/Values.kt @@ -1,8 +1,6 @@ package dev.arcade.core import com.fasterxml.jackson.annotation.JacksonAnnotationsInside -import com.fasterxml.jackson.annotation.JsonAutoDetect -import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.core.JsonGenerator @@ -27,35 +25,55 @@ 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 dev.arcade.errors.ArcadeInvalidDataException -import java.nio.charset.Charset +import java.io.InputStream import java.util.Objects import java.util.Optional -import org.apache.hc.core5.http.ContentType +/** + * 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 - fun asKnown(): Optional = - when (this) { - is KnownValue -> Optional.of(value) - else -> Optional.empty() - } + /** + * 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) /** - * If the "known" value (i.e. matching the type that the SDK expects) is returned by the API - * then this method will return an empty `Optional`, otherwise the returned `Optional` is given - * a `JsonValue`. + * 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 = - when (this) { - is JsonValue -> Optional.of(this) - else -> Optional.empty() - } + 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) @@ -63,6 +81,12 @@ sealed class JsonField { 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) @@ -70,6 +94,12 @@ sealed class JsonField { 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) @@ -80,6 +110,12 @@ sealed class JsonField { fun asStringOrThrow(): String = asString().orElseThrow { ArcadeInvalidDataException("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) @@ -98,6 +134,12 @@ sealed class JsonField { 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) @@ -135,11 +177,17 @@ sealed class JsonField { } @JvmSynthetic - internal fun getNullable(name: String): T? = + internal fun getOptional( + name: String + ): Optional< + // Safe because `Optional` is effectively covariant, but Kotlin doesn't know that. + @UnsafeVariance + T + > = when (this) { - is KnownValue -> value - is JsonMissing -> null - is JsonNull -> null + is KnownValue -> Optional.of(value) + is JsonMissing, + is JsonNull -> Optional.empty() else -> throw ArcadeInvalidDataException("`$name` is invalid, received $this") } @@ -150,21 +198,33 @@ sealed class JsonField { is JsonValue -> this } - @JvmSynthetic fun accept(consume: (T) -> Unit) = asKnown().ifPresent(consume) + @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) { @@ -179,6 +239,7 @@ sealed class JsonField { * annotation. */ class IsMissing { + override fun equals(other: Any?): Boolean = other is JsonMissing override fun hashCode(): Int = Objects.hash() @@ -200,6 +261,12 @@ sealed class JsonField { } } +/** + * 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() { @@ -207,6 +274,43 @@ sealed class JsonValue : JsonField() { fun convert(type: Class): R? = JSON_MAPPER.convertValue(this, type) + // ------------------------------------------------------------------------- + // Start of manually added code + // ------------------------------------------------------------------------- + + /** + * Returns this value's map representation, or an empty map if this value is not a JSON object. + * + * Example usage: + * ```java + * Map map = jsonValue.toMapOrEmpty(); + * ``` + */ + fun toMapOrEmpty(): Map = + when (this) { + is JsonObject -> values + else -> emptyMap() + } + + /** + * Returns this value's list representation, or an empty list if this value is not a JSON array. + * + * Example usage: + * ```java + * List items = jsonValue.toListOrEmpty(); + * ``` + */ + fun toListOrEmpty(): List = + when (this) { + is JsonArray -> values + else -> emptyList() + } + + // ------------------------------------------------------------------------- + // End of manually added code + // ------------------------------------------------------------------------- + + /** 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() @@ -218,7 +322,12 @@ sealed class JsonValue : JsonField() { 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() @@ -233,15 +342,52 @@ sealed class JsonValue : JsonField() { fun visitObject(values: Map): R = visitDefault() - fun visitDefault(): R { - throw RuntimeException("Unexpected value") - } + /** + * 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) { @@ -250,6 +396,11 @@ sealed class JsonValue : JsonField() { 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) { @@ -271,12 +422,19 @@ sealed class JsonValue : JsonField() { } 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 @@ -287,52 +445,67 @@ private constructor( return true } - return other is KnownValue<*> && value == other.value + return other is KnownValue<*> && value contentEquals other.value } - override fun hashCode() = value.hashCode() + override fun hashCode() = contentHash(value) - override fun toString() = value.toString() + 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 RuntimeException("JsonMissing cannot be serialized") + 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 @@ -351,14 +524,18 @@ private constructor( 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 @@ -372,10 +549,13 @@ private constructor( 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 @@ -394,10 +574,13 @@ private constructor( 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 @@ -418,10 +601,13 @@ private constructor( 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 @@ -442,121 +628,132 @@ private constructor( 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 -@JacksonAnnotationsInside -@JsonAutoDetect( - getterVisibility = Visibility.NONE, - isGetterVisibility = Visibility.NONE, - setterVisibility = Visibility.NONE, - creatorVisibility = Visibility.NONE, - fieldVisibility = Visibility.NONE, -) -annotation class NoAutoDetect - -class MultipartFormValue -internal constructor( - val name: String, - val value: T, - val contentType: ContentType, - val filename: String? = null, +/** 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?, ) { - private var hashCode: Int = 0 - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - name, - contentType, - filename, - when (value) { - is ByteArray -> value.contentHashCode() - is String -> value - is Boolean -> value - is Long -> value - is Double -> value - else -> value?.hashCode() - }, - ) - } - return hashCode - } - - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this.javaClass != other.javaClass) return false + companion object { - other as MultipartFormValue<*> + /** + * 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() + } - if (name != other.name || contentType != other.contentType || filename != other.filename) - return false + /** Returns the filename directive that will be included in the serialized field. */ + fun filename(): Optional = Optional.ofNullable(filename) - return when { - value is ByteArray && other.value is ByteArray -> value contentEquals other.value - else -> value?.equals(other.value) ?: (other.value == null) + @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, + ) } } - override fun toString(): String = - "MultipartFormValue{name=$name, contentType=$contentType, filename=$filename, value=${valueToString()}}" + private val hashCode: Int by lazy { contentHash(value, contentType, filename) } + + override fun hashCode(): Int = hashCode - private fun valueToString(): String = - when (value) { - is ByteArray -> "ByteArray of size ${value.size}" - else -> value.toString() + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - companion object { - internal fun fromString( - name: String, - value: String, - contentType: ContentType, - ): MultipartFormValue = MultipartFormValue(name, value, contentType) - - internal fun fromBoolean( - name: String, - value: Boolean, - contentType: ContentType, - ): MultipartFormValue = MultipartFormValue(name, value, contentType) - - internal fun fromLong( - name: String, - value: Long, - contentType: ContentType, - ): MultipartFormValue = MultipartFormValue(name, value, contentType) - - internal fun fromDouble( - name: String, - value: Double, - contentType: ContentType, - ): MultipartFormValue = MultipartFormValue(name, value, contentType) - - internal fun fromEnum( - name: String, - value: T, - contentType: ContentType, - ): MultipartFormValue = MultipartFormValue(name, value, contentType) - - internal fun fromByteArray( - name: String, - value: ByteArray, - contentType: ContentType, - filename: String? = null, - ): MultipartFormValue = MultipartFormValue(name, value, contentType, filename) + return other is MultipartField<*> && + value == other.value && + contentType == other.contentType && + filename == other.filename } -} -internal object ContentTypes { - val DefaultText = ContentType.create(ContentType.TEXT_PLAIN.mimeType, Charset.forName("UTF-8")) - val DefaultBinary = ContentType.DEFAULT_BINARY + override fun toString(): String = + "MultipartField{value=$value, contentType=$contentType, filename=$filename}" } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/core/handlers/ErrorHandler.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/handlers/ErrorHandler.kt index f7cf72a..68e59a3 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/core/handlers/ErrorHandler.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/handlers/ErrorHandler.kt @@ -1,12 +1,14 @@ +// File generated from our OpenAPI spec by Stainless. + @file:JvmName("ErrorHandler") package dev.arcade.core.handlers import com.fasterxml.jackson.databind.json.JsonMapper -import dev.arcade.core.http.Headers +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue import dev.arcade.core.http.HttpResponse import dev.arcade.core.http.HttpResponse.Handler -import dev.arcade.errors.ArcadeError import dev.arcade.errors.BadRequestException import dev.arcade.errors.InternalServerException import dev.arcade.errors.NotFoundException @@ -15,111 +17,68 @@ import dev.arcade.errors.RateLimitException import dev.arcade.errors.UnauthorizedException import dev.arcade.errors.UnexpectedStatusCodeException import dev.arcade.errors.UnprocessableEntityException -import java.io.ByteArrayInputStream -import java.io.InputStream @JvmSynthetic -internal fun errorHandler(jsonMapper: JsonMapper): Handler { - val handler = jsonHandler(jsonMapper) +internal fun errorBodyHandler(jsonMapper: JsonMapper): Handler { + val handler = jsonHandler(jsonMapper) - return object : Handler { - override fun handle(response: HttpResponse): ArcadeError = + return object : Handler { + override fun handle(response: HttpResponse): JsonValue = try { handler.handle(response) } catch (e: Exception) { - ArcadeError.builder().build() + JsonMissing.of() } } } @JvmSynthetic -internal fun Handler.withErrorHandler(errorHandler: Handler): Handler = - object : Handler { - override fun handle(response: HttpResponse): T { +internal fun errorHandler(errorBodyHandler: Handler): Handler = + object : Handler { + override fun handle(response: HttpResponse): HttpResponse = when (val statusCode = response.statusCode()) { - in 200..299 -> { - return this@withErrorHandler.handle(response) - } - 400 -> { - val buffered = response.buffered() - throw BadRequestException( - buffered.headers(), - stringHandler().handle(buffered), - errorHandler.handle(buffered), - ) - } - 401 -> { - val buffered = response.buffered() - throw UnauthorizedException( - buffered.headers(), - stringHandler().handle(buffered), - errorHandler.handle(buffered), - ) - } - 403 -> { - val buffered = response.buffered() - throw PermissionDeniedException( - buffered.headers(), - stringHandler().handle(buffered), - errorHandler.handle(buffered), - ) - } - 404 -> { - val buffered = response.buffered() - throw NotFoundException( - buffered.headers(), - stringHandler().handle(buffered), - errorHandler.handle(buffered), - ) - } - 422 -> { - val buffered = response.buffered() - throw UnprocessableEntityException( - buffered.headers(), - stringHandler().handle(buffered), - errorHandler.handle(buffered), - ) - } - 429 -> { - val buffered = response.buffered() - throw RateLimitException( - buffered.headers(), - stringHandler().handle(buffered), - errorHandler.handle(buffered), - ) - } - in 500..599 -> { - val buffered = response.buffered() - throw InternalServerException( - statusCode, - buffered.headers(), - stringHandler().handle(buffered), - errorHandler.handle(buffered), - ) - } - else -> { - val buffered = response.buffered() - throw UnexpectedStatusCodeException( - statusCode, - buffered.headers(), - stringHandler().handle(buffered), - errorHandler.handle(buffered), - ) - } + 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() } - } - } - -private fun HttpResponse.buffered(): HttpResponse { - val body = body().readBytes() - - return object : HttpResponse { - override fun statusCode(): Int = this@buffered.statusCode() - - override fun headers(): Headers = this@buffered.headers() - - override fun body(): InputStream = ByteArrayInputStream(body) - - override fun close() = this@buffered.close() } -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/core/handlers/JsonHandler.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/handlers/JsonHandler.kt index 782b9df..a1ea0a3 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/core/handlers/JsonHandler.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/handlers/JsonHandler.kt @@ -6,16 +6,15 @@ import com.fasterxml.jackson.databind.json.JsonMapper import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import dev.arcade.core.http.HttpResponse import dev.arcade.core.http.HttpResponse.Handler -import dev.arcade.errors.ArcadeException +import dev.arcade.errors.ArcadeInvalidDataException @JvmSynthetic internal inline fun jsonHandler(jsonMapper: JsonMapper): Handler = object : Handler { - override fun handle(response: HttpResponse): T { + override fun handle(response: HttpResponse): T = try { - return jsonMapper.readValue(response.body(), jacksonTypeRef()) + jsonMapper.readValue(response.body(), jacksonTypeRef()) } catch (e: Exception) { - throw ArcadeException("Error reading response", e) + throw ArcadeInvalidDataException("Error reading response", e) } - } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/core/http/AsyncStreamResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/http/AsyncStreamResponse.kt new file mode 100644 index 0000000..311e4ed --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/http/AsyncStreamResponse.kt @@ -0,0 +1,157 @@ +package dev.arcade.core.http + +import dev.arcade.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/arcade-java-core/src/main/kotlin/dev/arcade/core/http/Headers.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/http/Headers.kt index 8396327..dfdc4cc 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/core/http/Headers.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/http/Headers.kt @@ -1,5 +1,15 @@ +// File generated from our OpenAPI spec by Stainless. + package dev.arcade.core.http +import dev.arcade.core.JsonArray +import dev.arcade.core.JsonBoolean +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonNull +import dev.arcade.core.JsonNumber +import dev.arcade.core.JsonObject +import dev.arcade.core.JsonString +import dev.arcade.core.JsonValue import dev.arcade.core.toImmutable import java.util.TreeMap @@ -28,6 +38,19 @@ private constructor( 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++ @@ -41,15 +64,6 @@ private constructor( headers.names().forEach { put(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 replace(name: String, value: String) = apply { remove(name) put(name, value) @@ -68,6 +82,15 @@ private constructor( 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) -> diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/core/http/HttpClient.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/http/HttpClient.kt index ab82829..66259a2 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/core/http/HttpClient.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/http/HttpClient.kt @@ -1,5 +1,3 @@ -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package dev.arcade.core.http import dev.arcade.core.RequestOptions @@ -8,18 +6,21 @@ import java.util.concurrent.CompletableFuture interface HttpClient : AutoCloseable { - @JvmOverloads fun execute( request: HttpRequest, requestOptions: RequestOptions = RequestOptions.none(), ): HttpResponse - @JvmOverloads + 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/arcade-java-core/src/main/kotlin/dev/arcade/core/http/HttpRequest.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/http/HttpRequest.kt index 548dd46..9e34185 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/core/http/HttpRequest.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/http/HttpRequest.kt @@ -2,21 +2,51 @@ package dev.arcade.core.http import dev.arcade.core.checkRequired import dev.arcade.core.toImmutable +import java.net.URLEncoder class HttpRequest private constructor( @get:JvmName("method") val method: HttpMethod, - @get:JvmName("url") val url: String?, + @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 url(): String = buildString { + append(baseUrl) + + pathSegments.forEach { segment -> + if (!endsWith("/")) { + append("/") + } + append(URLEncoder.encode(segment, "UTF-8")) + } + + if (queryParams.isEmpty()) { + return@buildString + } + + append("?") + var isFirst = true + queryParams.keys().forEach { key -> + queryParams.values(key).forEach { value -> + if (!isFirst) { + append("&") + } + append(URLEncoder.encode(key, "UTF-8")) + append("=") + append(URLEncoder.encode(value, "UTF-8")) + isFirst = false + } + } + } + fun toBuilder(): Builder = Builder().from(this) override fun toString(): String = - "HttpRequest{method=$method, url=$url, pathSegments=$pathSegments, headers=$headers, queryParams=$queryParams, body=$body}" + "HttpRequest{method=$method, baseUrl=$baseUrl, pathSegments=$pathSegments, headers=$headers, queryParams=$queryParams, body=$body}" companion object { @JvmStatic fun builder() = Builder() @@ -25,7 +55,7 @@ private constructor( class Builder internal constructor() { private var method: HttpMethod? = null - private var url: String? = 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() @@ -34,7 +64,7 @@ private constructor( @JvmSynthetic internal fun from(request: HttpRequest) = apply { method = request.method - url = request.url + baseUrl = request.baseUrl pathSegments = request.pathSegments.toMutableList() headers = request.headers.toBuilder() queryParams = request.queryParams.toBuilder() @@ -43,7 +73,7 @@ private constructor( fun method(method: HttpMethod) = apply { this.method = method } - fun url(url: String) = apply { this.url = url } + fun baseUrl(baseUrl: String) = apply { this.baseUrl = baseUrl } fun addPathSegment(pathSegment: String) = apply { pathSegments.add(pathSegment) } @@ -136,7 +166,7 @@ private constructor( fun build(): HttpRequest = HttpRequest( checkRequired("method", method), - url, + checkRequired("baseUrl", baseUrl), pathSegments.toImmutable(), headers.build(), queryParams.build(), diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/core/http/HttpRequestBodies.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/http/HttpRequestBodies.kt new file mode 100644 index 0000000..44a26ed --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/http/HttpRequestBodies.kt @@ -0,0 +1,267 @@ +// File generated from our OpenAPI spec by Stainless. + +@file:JvmName("HttpRequestBodies") + +package dev.arcade.core.http + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.json.JsonMapper +import com.fasterxml.jackson.databind.node.JsonNodeType +import dev.arcade.core.MultipartField +import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import java.io.ByteArrayInputStream +import java.io.InputStream +import java.io.OutputStream +import java.util.UUID +import kotlin.jvm.optionals.getOrNull + +@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 = + MultipartBody.Builder() + .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) -> + val partBody = + if (bytes is ByteArrayInputStream) { + val byteArray = bytes.readBytes() + + object : HttpRequestBody { + + override fun writeTo(outputStream: OutputStream) { + outputStream.write(byteArray) + } + + override fun contentType(): String = field.contentType + + override fun contentLength(): Long = byteArray.size.toLong() + + override fun repeatable(): Boolean = true + + override fun close() {} + } + } else { + object : HttpRequestBody { + + override fun writeTo(outputStream: OutputStream) { + bytes.copyTo(outputStream) + } + + override fun contentType(): String = field.contentType + + override fun contentLength(): Long = -1L + + override fun repeatable(): Boolean = false + + override fun close() = bytes.close() + } + } + + addPart( + MultipartBody.Part.create( + name, + field.filename().getOrNull(), + field.contentType, + partBody, + ) + ) + } + } + } + .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().byteInputStream()) + JsonNodeType.BOOLEAN -> sequenceOf(name to node.booleanValue().toString().byteInputStream()) + JsonNodeType.NUMBER -> sequenceOf(name to node.numberValue().toString().byteInputStream()) + JsonNodeType.ARRAY -> + sequenceOf( + name to + node + .elements() + .asSequence() + .mapNotNull { element -> + when (element.nodeType) { + JsonNodeType.MISSING, + JsonNodeType.NULL -> null + JsonNodeType.STRING -> element.textValue() + JsonNodeType.BOOLEAN -> element.booleanValue().toString() + JsonNodeType.NUMBER -> element.numberValue().toString() + null, + JsonNodeType.BINARY, + JsonNodeType.ARRAY, + JsonNodeType.OBJECT, + JsonNodeType.POJO -> + throw ArcadeInvalidDataException( + "Unexpected JsonNode type in array: ${element.nodeType}" + ) + } + } + .joinToString(",") + .byteInputStream() + ) + JsonNodeType.OBJECT -> + node.fields().asSequence().flatMap { (key, value) -> + serializePart("$name[$key]", value) + } + JsonNodeType.POJO, + null -> throw ArcadeInvalidDataException("Unexpected JsonNode type: ${node.nodeType}") + } + +private class MultipartBody +private constructor(private val boundary: String, private val parts: List) : HttpRequestBody { + private val boundaryBytes: ByteArray = boundary.toByteArray() + private val contentType = "multipart/form-data; boundary=$boundary" + + // This must remain in sync with `contentLength`. + override fun writeTo(outputStream: OutputStream) { + parts.forEach { part -> + outputStream.write(DASHDASH) + outputStream.write(boundaryBytes) + outputStream.write(CRLF) + + outputStream.write(CONTENT_DISPOSITION) + outputStream.write(part.contentDisposition.toByteArray()) + outputStream.write(CRLF) + + outputStream.write(CONTENT_TYPE) + outputStream.write(part.contentType.toByteArray()) + outputStream.write(CRLF) + + outputStream.write(CRLF) + part.body.writeTo(outputStream) + outputStream.write(CRLF) + } + + outputStream.write(DASHDASH) + outputStream.write(boundaryBytes) + outputStream.write(DASHDASH) + outputStream.write(CRLF) + } + + override fun contentType(): String = contentType + + // This must remain in sync with `writeTo`. + override fun contentLength(): Long { + var byteCount = 0L + + parts.forEach { part -> + val contentLength = part.body.contentLength() + if (contentLength == -1L) { + return -1L + } + + byteCount += + DASHDASH.size + + boundaryBytes.size + + CRLF.size + + CONTENT_DISPOSITION.size + + part.contentDisposition.toByteArray().size + + CRLF.size + + CONTENT_TYPE.size + + part.contentType.toByteArray().size + + CRLF.size + + CRLF.size + + contentLength + + CRLF.size + } + + byteCount += DASHDASH.size + boundaryBytes.size + DASHDASH.size + CRLF.size + return byteCount + } + + override fun repeatable(): Boolean = parts.all { it.body.repeatable() } + + override fun close() { + parts.forEach { it.body.close() } + } + + class Builder { + private val boundary = UUID.randomUUID().toString() + private val parts: MutableList = mutableListOf() + + fun addPart(part: Part) = apply { parts.add(part) } + + fun build() = MultipartBody(boundary, parts.toImmutable()) + } + + class Part + private constructor( + val contentDisposition: String, + val contentType: String, + val body: HttpRequestBody, + ) { + companion object { + fun create( + name: String, + filename: String?, + contentType: String, + body: HttpRequestBody, + ): Part { + val disposition = buildString { + append("form-data; name=") + appendQuotedString(name) + if (filename != null) { + append("; filename=") + appendQuotedString(filename) + } + } + return Part(disposition, contentType, body) + } + } + } + + companion object { + private val CRLF = byteArrayOf('\r'.code.toByte(), '\n'.code.toByte()) + private val DASHDASH = byteArrayOf('-'.code.toByte(), '-'.code.toByte()) + private val CONTENT_DISPOSITION = "Content-Disposition: ".toByteArray() + private val CONTENT_TYPE = "Content-Type: ".toByteArray() + + private fun StringBuilder.appendQuotedString(key: String) { + append('"') + for (ch in key) { + when (ch) { + '\n' -> append("%0A") + '\r' -> append("%0D") + '"' -> append("%22") + else -> append(ch) + } + } + append('"') + } + } +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/core/http/HttpResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/http/HttpResponse.kt index b206587..32741ef 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/core/http/HttpResponse.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/http/HttpResponse.kt @@ -1,7 +1,8 @@ +// File generated from our OpenAPI spec by Stainless. + package dev.arcade.core.http import java.io.InputStream -import java.lang.AutoCloseable interface HttpResponse : AutoCloseable { diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/core/http/HttpResponseFor.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/http/HttpResponseFor.kt new file mode 100644 index 0000000..403584d --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/http/HttpResponseFor.kt @@ -0,0 +1,25 @@ +package dev.arcade.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/arcade-java-core/src/main/kotlin/dev/arcade/core/http/PhantomReachableClosingAsyncStreamResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/http/PhantomReachableClosingAsyncStreamResponse.kt new file mode 100644 index 0000000..0f7dc0e --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/http/PhantomReachableClosingAsyncStreamResponse.kt @@ -0,0 +1,56 @@ +package dev.arcade.core.http + +import dev.arcade.core.closeWhenPhantomReachable +import dev.arcade.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/arcade-java-core/src/main/kotlin/dev/arcade/core/http/PhantomReachableClosingStreamResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/http/PhantomReachableClosingStreamResponse.kt new file mode 100644 index 0000000..b19e385 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/http/PhantomReachableClosingStreamResponse.kt @@ -0,0 +1,21 @@ +package dev.arcade.core.http + +import dev.arcade.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/arcade-java-core/src/main/kotlin/dev/arcade/core/http/QueryParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/http/QueryParams.kt index 3aa9828..ff730d3 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/core/http/QueryParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/http/QueryParams.kt @@ -1,5 +1,15 @@ +// File generated from our OpenAPI spec by Stainless. + package dev.arcade.core.http +import dev.arcade.core.JsonArray +import dev.arcade.core.JsonBoolean +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonNull +import dev.arcade.core.JsonNumber +import dev.arcade.core.JsonObject +import dev.arcade.core.JsonString +import dev.arcade.core.JsonValue import dev.arcade.core.toImmutable class QueryParams @@ -26,6 +36,39 @@ private 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++ diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/core/http/RetryingHttpClient.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/http/RetryingHttpClient.kt index d649440..6fe3c03 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/core/http/RetryingHttpClient.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/http/RetryingHttpClient.kt @@ -1,8 +1,13 @@ +// File generated from our OpenAPI spec by Stainless. + package dev.arcade.core.http +import dev.arcade.core.DefaultSleeper import dev.arcade.core.RequestOptions +import dev.arcade.core.Sleeper import dev.arcade.core.checkRequired import dev.arcade.errors.ArcadeIoException +import dev.arcade.errors.ArcadeRetryableException import java.io.IOException import java.time.Clock import java.time.Duration @@ -10,8 +15,6 @@ 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 @@ -23,16 +26,13 @@ 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. @@ -46,6 +46,10 @@ private constructor( modifiedRequest = setRetryCountHeader(modifiedRequest, retries) } + if (!isRetryable(modifiedRequest)) { + return httpClient.execute(modifiedRequest, requestOptions) + } + val response = try { val response = httpClient.execute(modifiedRequest, requestOptions) @@ -62,10 +66,10 @@ private constructor( null } - val backoffMillis = getRetryBackoffMillis(retries, response) + val backoffDuration = getRetryBackoffDuration(retries, response) // All responses must be closed, so close the failed one before retrying. response?.close() - Thread.sleep(backoffMillis.toMillis()) + sleeper.sleep(backoffDuration) } } @@ -73,10 +77,6 @@ private constructor( 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. @@ -92,8 +92,12 @@ private constructor( val requestWithRetryCount = if (shouldSendRetryCount) setRetryCountHeader(request, retries) else request - return httpClient - .executeAsync(requestWithRetryCount, requestOptions) + val responseFuture = httpClient.executeAsync(requestWithRetryCount, requestOptions) + if (!isRetryable(requestWithRetryCount)) { + return responseFuture + } + + return responseFuture .handleAsync( fun( response: HttpResponse?, @@ -111,10 +115,10 @@ private constructor( } } - val backoffMillis = getRetryBackoffMillis(retries, response) + val backoffDuration = getRetryBackoffDuration(retries, response) // All responses must be closed, so close the failed one before retrying. response?.close() - return sleepAsync(backoffMillis.toMillis()).thenCompose { + return sleeper.sleepAsync(backoffDuration).thenCompose { executeWithRetries(requestWithRetryCount, requestOptions) } } @@ -128,7 +132,10 @@ private constructor( return executeWithRetries(modifiedRequest, requestOptions) } - override fun close() = httpClient.close() + override fun close() { + httpClient.close() + sleeper.close() + } private fun isRetryable(request: HttpRequest): Boolean = // Some requests, such as when a request body is being streamed, cannot be retried because @@ -175,11 +182,12 @@ private constructor( } private fun shouldRetry(throwable: Throwable): Boolean = - // Only retry IOException and ArcadeIoException, other exceptions are not intended to be - // retried. - throwable is IOException || throwable is ArcadeIoException + // Only retry known retryable exceptions, other exceptions are not intended to be retried. + throwable is IOException || + throwable is ArcadeIoException || + throwable is ArcadeRetryableException - private fun getRetryBackoffMillis(retries: Int, response: HttpResponse?): Duration { + 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 @@ -226,33 +234,21 @@ private constructor( companion object { - private val TIMER = Timer("RetryingHttpClient", true) - - private fun sleepAsync(millis: Long): CompletableFuture { - val future = CompletableFuture() - TIMER.schedule( - object : TimerTask() { - override fun run() { - future.complete(null) - } - }, - millis, - ) - return future - } - @JvmStatic fun builder() = Builder() } class Builder internal constructor() { private var httpClient: HttpClient? = null + private var sleeper: Sleeper? = null private var clock: Clock = Clock.systemUTC() private var maxRetries: Int = 2 private var idempotencyHeader: String? = null fun httpClient(httpClient: HttpClient) = apply { this.httpClient = httpClient } + fun sleeper(sleeper: Sleeper) = apply { this.sleeper = sleeper } + fun clock(clock: Clock) = apply { this.clock = clock } fun maxRetries(maxRetries: Int) = apply { this.maxRetries = maxRetries } @@ -262,6 +258,7 @@ private constructor( fun build(): HttpClient = RetryingHttpClient( checkRequired("httpClient", httpClient), + sleeper ?: DefaultSleeper(), clock, maxRetries, idempotencyHeader, diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/core/http/StreamResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/core/http/StreamResponse.kt new file mode 100644 index 0000000..fefbeb4 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/core/http/StreamResponse.kt @@ -0,0 +1,19 @@ +package dev.arcade.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/arcade-java-core/src/main/kotlin/dev/arcade/errors/ArcadeError.kt b/arcade-java-core/src/main/kotlin/dev/arcade/errors/ArcadeError.kt deleted file mode 100644 index 8df105f..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/errors/ArcadeError.kt +++ /dev/null @@ -1,76 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.errors - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import java.util.Objects - -@NoAutoDetect -class ArcadeError -@JsonCreator -private constructor( - @JsonAnyGetter - @ExcludeMissing - @JsonAnySetter - @get:JvmName("additionalProperties") - val additionalProperties: Map = immutableEmptyMap() -) { - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ArcadeError]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(arcadeError: ArcadeError) = apply { - additionalProperties = arcadeError.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) - } - - fun build(): ArcadeError = ArcadeError(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ArcadeError && additionalProperties == other.additionalProperties /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(additionalProperties) /* spotless:on */ - - override fun toString() = "ArcadeError{additionalProperties=$additionalProperties}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/errors/ArcadeRetryableException.kt b/arcade-java-core/src/main/kotlin/dev/arcade/errors/ArcadeRetryableException.kt new file mode 100644 index 0000000..e755ee6 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/errors/ArcadeRetryableException.kt @@ -0,0 +1,14 @@ +package dev.arcade.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 ArcadeRetryableException +@JvmOverloads +constructor(message: String? = null, cause: Throwable? = null) : ArcadeException(message, cause) diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/errors/ArcadeServiceException.kt b/arcade-java-core/src/main/kotlin/dev/arcade/errors/ArcadeServiceException.kt index 43498c3..d7bffcc 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/errors/ArcadeServiceException.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/errors/ArcadeServiceException.kt @@ -1,23 +1,16 @@ +// File generated from our OpenAPI spec by Stainless. + package dev.arcade.errors +import dev.arcade.core.JsonValue import dev.arcade.core.http.Headers abstract class ArcadeServiceException -@JvmOverloads -constructor( - private val statusCode: Int, - private val headers: Headers, - private val body: String, - private val error: ArcadeError, - message: String = "$statusCode: $error", - cause: Throwable? = null, -) : ArcadeException(message, cause) { - - fun statusCode(): Int = statusCode +protected constructor(message: String, cause: Throwable? = null) : ArcadeException(message, cause) { - fun headers(): Headers = headers + abstract fun statusCode(): Int - fun body(): String = body + abstract fun headers(): Headers - fun error(): ArcadeError = error + abstract fun body(): JsonValue } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/errors/BadRequestException.kt b/arcade-java-core/src/main/kotlin/dev/arcade/errors/BadRequestException.kt index e95d88e..b5cd72d 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/errors/BadRequestException.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/errors/BadRequestException.kt @@ -1,6 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. + package dev.arcade.errors +import dev.arcade.core.JsonValue +import dev.arcade.core.checkRequired import dev.arcade.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?) : + ArcadeServiceException("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()) -class BadRequestException(headers: Headers, body: String, error: ArcadeError) : - ArcadeServiceException(400, headers, body, error) + /** + * 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/arcade-java-core/src/main/kotlin/dev/arcade/errors/InternalServerException.kt b/arcade-java-core/src/main/kotlin/dev/arcade/errors/InternalServerException.kt index de58ead..faa5ede 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/errors/InternalServerException.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/errors/InternalServerException.kt @@ -1,6 +1,91 @@ +// File generated from our OpenAPI spec by Stainless. + package dev.arcade.errors +import dev.arcade.core.JsonValue +import dev.arcade.core.checkRequired import dev.arcade.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?, +) : ArcadeServiceException("$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()) -class InternalServerException(statusCode: Int, headers: Headers, body: String, error: ArcadeError) : - ArcadeServiceException(statusCode, headers, body, error) + /** + * 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/arcade-java-core/src/main/kotlin/dev/arcade/errors/NotFoundException.kt b/arcade-java-core/src/main/kotlin/dev/arcade/errors/NotFoundException.kt index 7e4bc4c..b156be1 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/errors/NotFoundException.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/errors/NotFoundException.kt @@ -1,6 +1,76 @@ +// File generated from our OpenAPI spec by Stainless. + package dev.arcade.errors +import dev.arcade.core.JsonValue +import dev.arcade.core.checkRequired import dev.arcade.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?) : + ArcadeServiceException("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()) -class NotFoundException(headers: Headers, body: String, error: ArcadeError) : - ArcadeServiceException(404, headers, body, error) + /** + * 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/arcade-java-core/src/main/kotlin/dev/arcade/errors/PermissionDeniedException.kt b/arcade-java-core/src/main/kotlin/dev/arcade/errors/PermissionDeniedException.kt index 5846576..5c77c7a 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/errors/PermissionDeniedException.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/errors/PermissionDeniedException.kt @@ -1,6 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. + package dev.arcade.errors +import dev.arcade.core.JsonValue +import dev.arcade.core.checkRequired import dev.arcade.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?) : + ArcadeServiceException("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()) -class PermissionDeniedException(headers: Headers, body: String, error: ArcadeError) : - ArcadeServiceException(403, headers, body, error) + /** + * 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/arcade-java-core/src/main/kotlin/dev/arcade/errors/RateLimitException.kt b/arcade-java-core/src/main/kotlin/dev/arcade/errors/RateLimitException.kt index 3b5d370..290070c 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/errors/RateLimitException.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/errors/RateLimitException.kt @@ -1,6 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. + package dev.arcade.errors +import dev.arcade.core.JsonValue +import dev.arcade.core.checkRequired import dev.arcade.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?) : + ArcadeServiceException("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()) -class RateLimitException(headers: Headers, body: String, error: ArcadeError) : - ArcadeServiceException(429, headers, body, error) + /** + * 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/arcade-java-core/src/main/kotlin/dev/arcade/errors/UnauthorizedException.kt b/arcade-java-core/src/main/kotlin/dev/arcade/errors/UnauthorizedException.kt index 680b91c..258076a 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/errors/UnauthorizedException.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/errors/UnauthorizedException.kt @@ -1,6 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. + package dev.arcade.errors +import dev.arcade.core.JsonValue +import dev.arcade.core.checkRequired import dev.arcade.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?) : + ArcadeServiceException("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()) -class UnauthorizedException(headers: Headers, body: String, error: ArcadeError) : - ArcadeServiceException(401, headers, body, error) + /** + * 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/arcade-java-core/src/main/kotlin/dev/arcade/errors/UnexpectedStatusCodeException.kt b/arcade-java-core/src/main/kotlin/dev/arcade/errors/UnexpectedStatusCodeException.kt index aefea24..a7a0400 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/errors/UnexpectedStatusCodeException.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/errors/UnexpectedStatusCodeException.kt @@ -1,10 +1,92 @@ +// File generated from our OpenAPI spec by Stainless. + package dev.arcade.errors +import dev.arcade.core.JsonValue +import dev.arcade.core.checkRequired import dev.arcade.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?, +) : ArcadeServiceException("$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()) -class UnexpectedStatusCodeException( - statusCode: Int, - headers: Headers, - body: String, - error: ArcadeError, -) : ArcadeServiceException(statusCode, headers, body, error) + /** + * 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/arcade-java-core/src/main/kotlin/dev/arcade/errors/UnprocessableEntityException.kt b/arcade-java-core/src/main/kotlin/dev/arcade/errors/UnprocessableEntityException.kt index 6616413..b94b126 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/errors/UnprocessableEntityException.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/errors/UnprocessableEntityException.kt @@ -1,6 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. + package dev.arcade.errors +import dev.arcade.core.JsonValue +import dev.arcade.core.checkRequired import dev.arcade.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?) : + ArcadeServiceException("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()) -class UnprocessableEntityException(headers: Headers, body: String, error: ArcadeError) : - ArcadeServiceException(422, headers, body, error) + /** + * 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/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminAuthProviderListResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminAuthProviderListResponse.kt deleted file mode 100644 index b719b25..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminAuthProviderListResponse.kt +++ /dev/null @@ -1,187 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import java.util.Objects -import java.util.Optional - -@NoAutoDetect -class AdminAuthProviderListResponse -@JsonCreator -private constructor( - @JsonProperty("items") - @ExcludeMissing - private val items: JsonField> = JsonMissing.of(), - @JsonProperty("limit") @ExcludeMissing private val limit: JsonField = JsonMissing.of(), - @JsonProperty("offset") @ExcludeMissing private val offset: JsonField = JsonMissing.of(), - @JsonProperty("page_count") - @ExcludeMissing - private val pageCount: JsonField = JsonMissing.of(), - @JsonProperty("total_count") - @ExcludeMissing - private val totalCount: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), -) { - - fun items(): Optional> = - Optional.ofNullable(items.getNullable("items")) - - fun limit(): Optional = Optional.ofNullable(limit.getNullable("limit")) - - fun offset(): Optional = Optional.ofNullable(offset.getNullable("offset")) - - fun pageCount(): Optional = Optional.ofNullable(pageCount.getNullable("page_count")) - - fun totalCount(): Optional = Optional.ofNullable(totalCount.getNullable("total_count")) - - @JsonProperty("items") - @ExcludeMissing - fun _items(): JsonField> = items - - @JsonProperty("limit") @ExcludeMissing fun _limit(): JsonField = limit - - @JsonProperty("offset") @ExcludeMissing fun _offset(): JsonField = offset - - @JsonProperty("page_count") @ExcludeMissing fun _pageCount(): JsonField = pageCount - - @JsonProperty("total_count") @ExcludeMissing fun _totalCount(): JsonField = totalCount - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): AdminAuthProviderListResponse = apply { - if (validated) { - return@apply - } - - items().ifPresent { it.forEach { it.validate() } } - limit() - offset() - pageCount() - totalCount() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [AdminAuthProviderListResponse]. */ - class Builder internal constructor() { - - private var items: JsonField>? = null - private var limit: JsonField = JsonMissing.of() - private var offset: JsonField = JsonMissing.of() - private var pageCount: JsonField = JsonMissing.of() - private var totalCount: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(adminAuthProviderListResponse: AdminAuthProviderListResponse) = apply { - items = adminAuthProviderListResponse.items.map { it.toMutableList() } - limit = adminAuthProviderListResponse.limit - offset = adminAuthProviderListResponse.offset - pageCount = adminAuthProviderListResponse.pageCount - totalCount = adminAuthProviderListResponse.totalCount - additionalProperties = adminAuthProviderListResponse.additionalProperties.toMutableMap() - } - - fun items(items: List) = items(JsonField.of(items)) - - fun items(items: JsonField>) = apply { - this.items = items.map { it.toMutableList() } - } - - fun addItem(item: AuthProviderResponse) = apply { - items = - (items ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(item) - } - } - - fun limit(limit: Long) = limit(JsonField.of(limit)) - - fun limit(limit: JsonField) = apply { this.limit = limit } - - fun offset(offset: Long) = offset(JsonField.of(offset)) - - fun offset(offset: JsonField) = apply { this.offset = offset } - - fun pageCount(pageCount: Long) = pageCount(JsonField.of(pageCount)) - - fun pageCount(pageCount: JsonField) = apply { this.pageCount = pageCount } - - fun totalCount(totalCount: Long) = totalCount(JsonField.of(totalCount)) - - fun totalCount(totalCount: JsonField) = apply { this.totalCount = totalCount } - - 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) - } - - fun build(): AdminAuthProviderListResponse = - AdminAuthProviderListResponse( - (items ?: JsonMissing.of()).map { it.toImmutable() }, - limit, - offset, - pageCount, - totalCount, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is AdminAuthProviderListResponse && items == other.items && limit == other.limit && offset == other.offset && pageCount == other.pageCount && totalCount == other.totalCount && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(items, limit, offset, pageCount, totalCount, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "AdminAuthProviderListResponse{items=$items, limit=$limit, offset=$offset, pageCount=$pageCount, totalCount=$totalCount, additionalProperties=$additionalProperties}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminSecretListResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminSecretListResponse.kt deleted file mode 100644 index ed4deb3..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminSecretListResponse.kt +++ /dev/null @@ -1,184 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import java.util.Objects -import java.util.Optional - -@NoAutoDetect -class AdminSecretListResponse -@JsonCreator -private constructor( - @JsonProperty("items") - @ExcludeMissing - private val items: JsonField> = JsonMissing.of(), - @JsonProperty("limit") @ExcludeMissing private val limit: JsonField = JsonMissing.of(), - @JsonProperty("offset") @ExcludeMissing private val offset: JsonField = JsonMissing.of(), - @JsonProperty("page_count") - @ExcludeMissing - private val pageCount: JsonField = JsonMissing.of(), - @JsonProperty("total_count") - @ExcludeMissing - private val totalCount: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), -) { - - fun items(): Optional> = Optional.ofNullable(items.getNullable("items")) - - fun limit(): Optional = Optional.ofNullable(limit.getNullable("limit")) - - fun offset(): Optional = Optional.ofNullable(offset.getNullable("offset")) - - fun pageCount(): Optional = Optional.ofNullable(pageCount.getNullable("page_count")) - - fun totalCount(): Optional = Optional.ofNullable(totalCount.getNullable("total_count")) - - @JsonProperty("items") @ExcludeMissing fun _items(): JsonField> = items - - @JsonProperty("limit") @ExcludeMissing fun _limit(): JsonField = limit - - @JsonProperty("offset") @ExcludeMissing fun _offset(): JsonField = offset - - @JsonProperty("page_count") @ExcludeMissing fun _pageCount(): JsonField = pageCount - - @JsonProperty("total_count") @ExcludeMissing fun _totalCount(): JsonField = totalCount - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): AdminSecretListResponse = apply { - if (validated) { - return@apply - } - - items().ifPresent { it.forEach { it.validate() } } - limit() - offset() - pageCount() - totalCount() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [AdminSecretListResponse]. */ - class Builder internal constructor() { - - private var items: JsonField>? = null - private var limit: JsonField = JsonMissing.of() - private var offset: JsonField = JsonMissing.of() - private var pageCount: JsonField = JsonMissing.of() - private var totalCount: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(adminSecretListResponse: AdminSecretListResponse) = apply { - items = adminSecretListResponse.items.map { it.toMutableList() } - limit = adminSecretListResponse.limit - offset = adminSecretListResponse.offset - pageCount = adminSecretListResponse.pageCount - totalCount = adminSecretListResponse.totalCount - additionalProperties = adminSecretListResponse.additionalProperties.toMutableMap() - } - - fun items(items: List) = items(JsonField.of(items)) - - fun items(items: JsonField>) = apply { - this.items = items.map { it.toMutableList() } - } - - fun addItem(item: SecretResponse) = apply { - items = - (items ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(item) - } - } - - fun limit(limit: Long) = limit(JsonField.of(limit)) - - fun limit(limit: JsonField) = apply { this.limit = limit } - - fun offset(offset: Long) = offset(JsonField.of(offset)) - - fun offset(offset: JsonField) = apply { this.offset = offset } - - fun pageCount(pageCount: Long) = pageCount(JsonField.of(pageCount)) - - fun pageCount(pageCount: JsonField) = apply { this.pageCount = pageCount } - - fun totalCount(totalCount: Long) = totalCount(JsonField.of(totalCount)) - - fun totalCount(totalCount: JsonField) = apply { this.totalCount = totalCount } - - 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) - } - - fun build(): AdminSecretListResponse = - AdminSecretListResponse( - (items ?: JsonMissing.of()).map { it.toImmutable() }, - limit, - offset, - pageCount, - totalCount, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is AdminSecretListResponse && items == other.items && limit == other.limit && offset == other.offset && pageCount == other.pageCount && totalCount == other.totalCount && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(items, limit, offset, pageCount, totalCount, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "AdminSecretListResponse{items=$items, limit=$limit, offset=$offset, pageCount=$pageCount, totalCount=$totalCount, additionalProperties=$additionalProperties}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminUserConnectionListPage.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminUserConnectionListPage.kt deleted file mode 100644 index 21e3150..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminUserConnectionListPage.kt +++ /dev/null @@ -1,207 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import dev.arcade.services.blocking.admin.UserConnectionService -import java.util.Objects -import java.util.Optional -import java.util.stream.Stream -import java.util.stream.StreamSupport - -/** List all auth connections */ -class AdminUserConnectionListPage -private constructor( - private val userConnectionsService: UserConnectionService, - private val params: AdminUserConnectionListParams, - private val response: Response, -) { - - fun response(): Response = response - - fun items(): List = response().items() - - fun totalCount(): Optional = response().totalCount() - - fun offset(): Optional = response().offset() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is AdminUserConnectionListPage && userConnectionsService == other.userConnectionsService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(userConnectionsService, params, response) /* spotless:on */ - - override fun toString() = - "AdminUserConnectionListPage{userConnectionsService=$userConnectionsService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - if (items().isEmpty()) { - return false - } - - return offset().orElse(0) + items().count() < totalCount().orElse(Long.MAX_VALUE) - } - - fun getNextPageParams(): Optional { - if (!hasNextPage()) { - return Optional.empty() - } - - return Optional.of( - AdminUserConnectionListParams.builder() - .from(params) - .offset(offset().orElse(0) + items().count()) - .build() - ) - } - - fun getNextPage(): Optional { - return getNextPageParams().map { userConnectionsService.list(it) } - } - - fun autoPager(): AutoPager = AutoPager(this) - - companion object { - - @JvmStatic - fun of( - userConnectionsService: UserConnectionService, - params: AdminUserConnectionListParams, - response: Response, - ) = AdminUserConnectionListPage(userConnectionsService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("items") - private val items: JsonField> = JsonMissing.of(), - @JsonProperty("total_count") private val totalCount: JsonField = JsonMissing.of(), - @JsonProperty("offset") private val offset: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun items(): List = items.getNullable("items") ?: listOf() - - fun totalCount(): Optional = - Optional.ofNullable(totalCount.getNullable("total_count")) - - fun offset(): Optional = Optional.ofNullable(offset.getNullable("offset")) - - @JsonProperty("items") - fun _items(): Optional>> = Optional.ofNullable(items) - - @JsonProperty("total_count") - fun _totalCount(): Optional> = Optional.ofNullable(totalCount) - - @JsonProperty("offset") - fun _offset(): Optional> = Optional.ofNullable(offset) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - items().map { it.validate() } - totalCount() - offset() - validated = true - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && items == other.items && totalCount == other.totalCount && offset == other.offset && additionalProperties == other.additionalProperties /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(items, totalCount, offset, additionalProperties) /* spotless:on */ - - override fun toString() = - "Response{items=$items, totalCount=$totalCount, offset=$offset, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var items: JsonField> = JsonMissing.of() - private var totalCount: JsonField = JsonMissing.of() - private var offset: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.items = page.items - this.totalCount = page.totalCount - this.offset = page.offset - this.additionalProperties.putAll(page.additionalProperties) - } - - fun items(items: List) = items(JsonField.of(items)) - - fun items(items: JsonField>) = apply { this.items = items } - - fun totalCount(totalCount: Long) = totalCount(JsonField.of(totalCount)) - - fun totalCount(totalCount: JsonField) = apply { this.totalCount = totalCount } - - fun offset(offset: Long) = offset(JsonField.of(offset)) - - fun offset(offset: JsonField) = apply { this.offset = offset } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun build() = Response(items, totalCount, offset, additionalProperties.toImmutable()) - } - } - - class AutoPager(private val firstPage: AdminUserConnectionListPage) : - Iterable { - - override fun iterator(): Iterator = iterator { - var page = firstPage - var index = 0 - while (true) { - while (index < page.items().size) { - yield(page.items()[index++]) - } - page = page.getNextPage().orElse(null) ?: break - index = 0 - } - } - - fun stream(): Stream { - return StreamSupport.stream(spliterator(), false) - } - } -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminUserConnectionListPageAsync.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminUserConnectionListPageAsync.kt deleted file mode 100644 index b9e3680..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminUserConnectionListPageAsync.kt +++ /dev/null @@ -1,219 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import dev.arcade.services.async.admin.UserConnectionServiceAsync -import java.util.Objects -import java.util.Optional -import java.util.concurrent.CompletableFuture -import java.util.concurrent.Executor -import java.util.function.Predicate - -/** List all auth connections */ -class AdminUserConnectionListPageAsync -private constructor( - private val userConnectionsService: UserConnectionServiceAsync, - private val params: AdminUserConnectionListParams, - private val response: Response, -) { - - fun response(): Response = response - - fun items(): List = response().items() - - fun totalCount(): Optional = response().totalCount() - - fun offset(): Optional = response().offset() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is AdminUserConnectionListPageAsync && userConnectionsService == other.userConnectionsService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(userConnectionsService, params, response) /* spotless:on */ - - override fun toString() = - "AdminUserConnectionListPageAsync{userConnectionsService=$userConnectionsService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - if (items().isEmpty()) { - return false - } - - return offset().orElse(0) + items().count() < totalCount().orElse(Long.MAX_VALUE) - } - - fun getNextPageParams(): Optional { - if (!hasNextPage()) { - return Optional.empty() - } - - return Optional.of( - AdminUserConnectionListParams.builder() - .from(params) - .offset(offset().orElse(0) + items().count()) - .build() - ) - } - - fun getNextPage(): CompletableFuture> { - return getNextPageParams() - .map { userConnectionsService.list(it).thenApply { Optional.of(it) } } - .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } - } - - fun autoPager(): AutoPager = AutoPager(this) - - companion object { - - @JvmStatic - fun of( - userConnectionsService: UserConnectionServiceAsync, - params: AdminUserConnectionListParams, - response: Response, - ) = AdminUserConnectionListPageAsync(userConnectionsService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("items") - private val items: JsonField> = JsonMissing.of(), - @JsonProperty("total_count") private val totalCount: JsonField = JsonMissing.of(), - @JsonProperty("offset") private val offset: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun items(): List = items.getNullable("items") ?: listOf() - - fun totalCount(): Optional = - Optional.ofNullable(totalCount.getNullable("total_count")) - - fun offset(): Optional = Optional.ofNullable(offset.getNullable("offset")) - - @JsonProperty("items") - fun _items(): Optional>> = Optional.ofNullable(items) - - @JsonProperty("total_count") - fun _totalCount(): Optional> = Optional.ofNullable(totalCount) - - @JsonProperty("offset") - fun _offset(): Optional> = Optional.ofNullable(offset) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - items().map { it.validate() } - totalCount() - offset() - validated = true - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && items == other.items && totalCount == other.totalCount && offset == other.offset && additionalProperties == other.additionalProperties /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(items, totalCount, offset, additionalProperties) /* spotless:on */ - - override fun toString() = - "Response{items=$items, totalCount=$totalCount, offset=$offset, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var items: JsonField> = JsonMissing.of() - private var totalCount: JsonField = JsonMissing.of() - private var offset: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.items = page.items - this.totalCount = page.totalCount - this.offset = page.offset - this.additionalProperties.putAll(page.additionalProperties) - } - - fun items(items: List) = items(JsonField.of(items)) - - fun items(items: JsonField>) = apply { this.items = items } - - fun totalCount(totalCount: Long) = totalCount(JsonField.of(totalCount)) - - fun totalCount(totalCount: JsonField) = apply { this.totalCount = totalCount } - - fun offset(offset: Long) = offset(JsonField.of(offset)) - - fun offset(offset: JsonField) = apply { this.offset = offset } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun build() = Response(items, totalCount, offset, additionalProperties.toImmutable()) - } - } - - class AutoPager(private val firstPage: AdminUserConnectionListPageAsync) { - - fun forEach( - action: Predicate, - executor: Executor, - ): CompletableFuture { - fun CompletableFuture>.forEach( - action: (UserConnectionResponse) -> Boolean, - executor: Executor, - ): CompletableFuture = - thenComposeAsync( - { page -> - page - .filter { it.items().all(action) } - .map { it.getNextPage().forEach(action, executor) } - .orElseGet { CompletableFuture.completedFuture(null) } - }, - executor, - ) - return CompletableFuture.completedFuture(Optional.of(firstPage)) - .forEach(action::test, executor) - } - - fun toList(executor: Executor): CompletableFuture> { - val values = mutableListOf() - return forEach(values::add, executor).thenApply { values } - } - } -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminUserConnectionListParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminUserConnectionListParams.kt deleted file mode 100644 index cdcb4c9..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminUserConnectionListParams.kt +++ /dev/null @@ -1,444 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.models - -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.Params -import dev.arcade.core.http.Headers -import dev.arcade.core.http.QueryParams -import java.util.Objects -import java.util.Optional - -/** List all auth connections */ -class AdminUserConnectionListParams -private constructor( - private val limit: Long?, - private val offset: Long?, - private val provider: Provider?, - private val user: User?, - private val additionalHeaders: Headers, - private val additionalQueryParams: QueryParams, -) : Params { - - /** Page size */ - fun limit(): Optional = Optional.ofNullable(limit) - - /** Page offset */ - fun offset(): Optional = Optional.ofNullable(offset) - - fun provider(): Optional = Optional.ofNullable(provider) - - fun user(): Optional = Optional.ofNullable(user) - - fun _additionalHeaders(): Headers = additionalHeaders - - fun _additionalQueryParams(): QueryParams = additionalQueryParams - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams { - val queryParams = QueryParams.builder() - this.limit?.let { queryParams.put("limit", listOf(it.toString())) } - this.offset?.let { queryParams.put("offset", listOf(it.toString())) } - this.provider?.forEachQueryParam { key, values -> - queryParams.put("provider[$key]", values) - } - this.user?.forEachQueryParam { key, values -> queryParams.put("user[$key]", values) } - queryParams.putAll(additionalQueryParams) - return queryParams.build() - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [AdminUserConnectionListParams]. */ - @NoAutoDetect - class Builder internal constructor() { - - private var limit: Long? = null - private var offset: Long? = null - private var provider: Provider? = null - private var user: User? = null - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() - - @JvmSynthetic - internal fun from(adminUserConnectionListParams: AdminUserConnectionListParams) = apply { - limit = adminUserConnectionListParams.limit - offset = adminUserConnectionListParams.offset - provider = adminUserConnectionListParams.provider - user = adminUserConnectionListParams.user - additionalHeaders = adminUserConnectionListParams.additionalHeaders.toBuilder() - additionalQueryParams = adminUserConnectionListParams.additionalQueryParams.toBuilder() - } - - /** Page size */ - fun limit(limit: Long?) = apply { this.limit = limit } - - /** Page size */ - fun limit(limit: Long) = limit(limit as Long?) - - /** Page size */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun limit(limit: Optional) = limit(limit.orElse(null) as Long?) - - /** Page offset */ - fun offset(offset: Long?) = apply { this.offset = offset } - - /** Page offset */ - fun offset(offset: Long) = offset(offset as Long?) - - /** Page offset */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun offset(offset: Optional) = offset(offset.orElse(null) as Long?) - - fun provider(provider: Provider?) = apply { this.provider = provider } - - fun provider(provider: Optional) = provider(provider.orElse(null)) - - fun user(user: User?) = apply { this.user = user } - - fun user(user: Optional) = user(user.orElse(null)) - - 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 build(): AdminUserConnectionListParams = - AdminUserConnectionListParams( - limit, - offset, - provider, - user, - additionalHeaders.build(), - additionalQueryParams.build(), - ) - } - - class Provider - private constructor(private val id: String?, private val additionalProperties: QueryParams) { - - /** Provider ID */ - fun id(): Optional = Optional.ofNullable(id) - - fun _additionalProperties(): QueryParams = additionalProperties - - @JvmSynthetic - internal fun forEachQueryParam(putParam: (String, List) -> Unit) { - this.id?.let { putParam("id", listOf(it.toString())) } - additionalProperties.keys().forEach { putParam(it, additionalProperties.values(it)) } - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Provider]. */ - class Builder internal constructor() { - - private var id: String? = null - private var additionalProperties: QueryParams.Builder = QueryParams.builder() - - @JvmSynthetic - internal fun from(provider: Provider) = apply { - id = provider.id - additionalProperties = provider.additionalProperties.toBuilder() - } - - /** Provider ID */ - fun id(id: String?) = apply { this.id = id } - - /** Provider ID */ - fun id(id: Optional) = id(id.orElse(null)) - - fun additionalProperties(additionalProperties: QueryParams) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun additionalProperties(additionalProperties: Map>) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: String) = apply { - additionalProperties.put(key, value) - } - - fun putAdditionalProperties(key: String, values: Iterable) = apply { - additionalProperties.put(key, values) - } - - fun putAllAdditionalProperties(additionalProperties: QueryParams) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun putAllAdditionalProperties(additionalProperties: Map>) = - apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun replaceAdditionalProperties(key: String, value: String) = apply { - additionalProperties.replace(key, value) - } - - fun replaceAdditionalProperties(key: String, values: Iterable) = apply { - additionalProperties.replace(key, values) - } - - fun replaceAllAdditionalProperties(additionalProperties: QueryParams) = apply { - this.additionalProperties.replaceAll(additionalProperties) - } - - fun replaceAllAdditionalProperties( - additionalProperties: Map> - ) = apply { this.additionalProperties.replaceAll(additionalProperties) } - - fun removeAdditionalProperties(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - additionalProperties.removeAll(keys) - } - - fun build(): Provider = Provider(id, additionalProperties.build()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Provider && id == other.id && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(id, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "Provider{id=$id, additionalProperties=$additionalProperties}" - } - - class User - private constructor(private val id: String?, private val additionalProperties: QueryParams) { - - /** User ID */ - fun id(): Optional = Optional.ofNullable(id) - - fun _additionalProperties(): QueryParams = additionalProperties - - @JvmSynthetic - internal fun forEachQueryParam(putParam: (String, List) -> Unit) { - this.id?.let { putParam("id", listOf(it.toString())) } - additionalProperties.keys().forEach { putParam(it, additionalProperties.values(it)) } - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [User]. */ - class Builder internal constructor() { - - private var id: String? = null - private var additionalProperties: QueryParams.Builder = QueryParams.builder() - - @JvmSynthetic - internal fun from(user: User) = apply { - id = user.id - additionalProperties = user.additionalProperties.toBuilder() - } - - /** User ID */ - fun id(id: String?) = apply { this.id = id } - - /** User ID */ - fun id(id: Optional) = id(id.orElse(null)) - - fun additionalProperties(additionalProperties: QueryParams) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun additionalProperties(additionalProperties: Map>) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: String) = apply { - additionalProperties.put(key, value) - } - - fun putAdditionalProperties(key: String, values: Iterable) = apply { - additionalProperties.put(key, values) - } - - fun putAllAdditionalProperties(additionalProperties: QueryParams) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun putAllAdditionalProperties(additionalProperties: Map>) = - apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun replaceAdditionalProperties(key: String, value: String) = apply { - additionalProperties.replace(key, value) - } - - fun replaceAdditionalProperties(key: String, values: Iterable) = apply { - additionalProperties.replace(key, values) - } - - fun replaceAllAdditionalProperties(additionalProperties: QueryParams) = apply { - this.additionalProperties.replaceAll(additionalProperties) - } - - fun replaceAllAdditionalProperties( - additionalProperties: Map> - ) = apply { this.additionalProperties.replaceAll(additionalProperties) } - - fun removeAdditionalProperties(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - additionalProperties.removeAll(keys) - } - - fun build(): User = User(id, additionalProperties.build()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is User && id == other.id && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(id, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "User{id=$id, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is AdminUserConnectionListParams && limit == other.limit && offset == other.offset && provider == other.provider && user == other.user && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(limit, offset, provider, user, additionalHeaders, additionalQueryParams) /* spotless:on */ - - override fun toString() = - "AdminUserConnectionListParams{limit=$limit, offset=$offset, provider=$provider, user=$user, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthProviderResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthProviderResponse.kt deleted file mode 100644 index 1f7b9d6..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthProviderResponse.kt +++ /dev/null @@ -1,3503 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.Enum -import dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import dev.arcade.errors.ArcadeInvalidDataException -import java.util.Objects -import java.util.Optional - -@NoAutoDetect -class AuthProviderResponse -@JsonCreator -private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("binding") - @ExcludeMissing - private val binding: JsonField = JsonMissing.of(), - @JsonProperty("created_at") - @ExcludeMissing - private val createdAt: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("oauth2") - @ExcludeMissing - private val oauth2: JsonField = JsonMissing.of(), - @JsonProperty("provider_id") - @ExcludeMissing - private val providerId: JsonField = JsonMissing.of(), - @JsonProperty("status") - @ExcludeMissing - private val status: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonProperty("updated_at") - @ExcludeMissing - private val updatedAt: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), -) { - - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - fun binding(): Optional = Optional.ofNullable(binding.getNullable("binding")) - - fun createdAt(): Optional = Optional.ofNullable(createdAt.getNullable("created_at")) - - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) - - fun oauth2(): Optional = Optional.ofNullable(oauth2.getNullable("oauth2")) - - fun providerId(): Optional = Optional.ofNullable(providerId.getNullable("provider_id")) - - fun status(): Optional = Optional.ofNullable(status.getNullable("status")) - - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - - fun updatedAt(): Optional = Optional.ofNullable(updatedAt.getNullable("updated_at")) - - @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - - @JsonProperty("binding") @ExcludeMissing fun _binding(): JsonField = binding - - @JsonProperty("created_at") @ExcludeMissing fun _createdAt(): JsonField = createdAt - - @JsonProperty("description") @ExcludeMissing fun _description(): JsonField = description - - @JsonProperty("oauth2") @ExcludeMissing fun _oauth2(): JsonField = oauth2 - - @JsonProperty("provider_id") @ExcludeMissing fun _providerId(): JsonField = providerId - - @JsonProperty("status") @ExcludeMissing fun _status(): JsonField = status - - @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type - - @JsonProperty("updated_at") @ExcludeMissing fun _updatedAt(): JsonField = updatedAt - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): AuthProviderResponse = apply { - if (validated) { - return@apply - } - - id() - binding().ifPresent { it.validate() } - createdAt() - description() - oauth2().ifPresent { it.validate() } - providerId() - status() - type() - updatedAt() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [AuthProviderResponse]. */ - class Builder internal constructor() { - - private var id: JsonField = JsonMissing.of() - private var binding: JsonField = JsonMissing.of() - private var createdAt: JsonField = JsonMissing.of() - private var description: JsonField = JsonMissing.of() - private var oauth2: JsonField = JsonMissing.of() - private var providerId: JsonField = JsonMissing.of() - private var status: JsonField = JsonMissing.of() - private var type: JsonField = JsonMissing.of() - private var updatedAt: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(authProviderResponse: AuthProviderResponse) = apply { - id = authProviderResponse.id - binding = authProviderResponse.binding - createdAt = authProviderResponse.createdAt - description = authProviderResponse.description - oauth2 = authProviderResponse.oauth2 - providerId = authProviderResponse.providerId - status = authProviderResponse.status - type = authProviderResponse.type - updatedAt = authProviderResponse.updatedAt - additionalProperties = authProviderResponse.additionalProperties.toMutableMap() - } - - fun id(id: String) = id(JsonField.of(id)) - - fun id(id: JsonField) = apply { this.id = id } - - fun binding(binding: Binding) = binding(JsonField.of(binding)) - - fun binding(binding: JsonField) = apply { this.binding = binding } - - fun createdAt(createdAt: String) = createdAt(JsonField.of(createdAt)) - - fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } - - fun description(description: String) = description(JsonField.of(description)) - - fun description(description: JsonField) = apply { this.description = description } - - fun oauth2(oauth2: Oauth2) = oauth2(JsonField.of(oauth2)) - - fun oauth2(oauth2: JsonField) = apply { this.oauth2 = oauth2 } - - fun providerId(providerId: String) = providerId(JsonField.of(providerId)) - - fun providerId(providerId: JsonField) = apply { this.providerId = providerId } - - fun status(status: String) = status(JsonField.of(status)) - - fun status(status: JsonField) = apply { this.status = status } - - fun type(type: String) = type(JsonField.of(type)) - - fun type(type: JsonField) = apply { this.type = type } - - fun updatedAt(updatedAt: String) = updatedAt(JsonField.of(updatedAt)) - - 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) - } - - fun build(): AuthProviderResponse = - AuthProviderResponse( - id, - binding, - createdAt, - description, - oauth2, - providerId, - status, - type, - updatedAt, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class Binding - @JsonCreator - private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - - @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - - @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Binding = apply { - if (validated) { - return@apply - } - - id() - type() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Binding]. */ - class Builder internal constructor() { - - private var id: JsonField = JsonMissing.of() - private var type: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(binding: Binding) = apply { - id = binding.id - type = binding.type - additionalProperties = binding.additionalProperties.toMutableMap() - } - - fun id(id: String) = id(JsonField.of(id)) - - fun id(id: JsonField) = apply { this.id = id } - - fun type(type: Type) = type(JsonField.of(type)) - - 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) - } - - fun build(): Binding = Binding(id, type, additionalProperties.toImmutable()) - } - - 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 STATIC = of("static") - - @JvmField val TENANT = of("tenant") - - @JvmField val PROJECT = of("project") - - @JvmField val ACCOUNT = of("account") - - @JvmStatic fun of(value: String) = Type(JsonField.of(value)) - } - - /** An enum containing [Type]'s known values. */ - enum class Known { - STATIC, - TENANT, - PROJECT, - ACCOUNT, - } - - /** - * 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 { - STATIC, - TENANT, - PROJECT, - ACCOUNT, - /** 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) { - STATIC -> Value.STATIC - TENANT -> Value.TENANT - PROJECT -> Value.PROJECT - ACCOUNT -> Value.ACCOUNT - 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 ArcadeInvalidDataException if this class instance's value is a not a known - * member. - */ - fun known(): Known = - when (this) { - STATIC -> Known.STATIC - TENANT -> Known.TENANT - PROJECT -> Known.PROJECT - ACCOUNT -> Known.ACCOUNT - else -> throw ArcadeInvalidDataException("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 ArcadeInvalidDataException if this class instance's value does not have the - * expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - ArcadeInvalidDataException("Value is not a String") - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Type && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Binding && id == other.id && type == other.type && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(id, type, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Binding{id=$id, type=$type, additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class Oauth2 - @JsonCreator - private constructor( - @JsonProperty("authorize_request") - @ExcludeMissing - private val authorizeRequest: JsonField = JsonMissing.of(), - @JsonProperty("client_id") - @ExcludeMissing - private val clientId: JsonField = JsonMissing.of(), - @JsonProperty("client_secret") - @ExcludeMissing - private val clientSecret: JsonField = JsonMissing.of(), - @JsonProperty("pkce") @ExcludeMissing private val pkce: JsonField = JsonMissing.of(), - @JsonProperty("redirect_uri") - @ExcludeMissing - private val redirectUri: JsonField = JsonMissing.of(), - @JsonProperty("refresh_request") - @ExcludeMissing - private val refreshRequest: JsonField = JsonMissing.of(), - @JsonProperty("scope_delimiter") - @ExcludeMissing - private val scopeDelimiter: JsonField = JsonMissing.of(), - @JsonProperty("token_introspection_request") - @ExcludeMissing - private val tokenIntrospectionRequest: JsonField = - JsonMissing.of(), - @JsonProperty("token_request") - @ExcludeMissing - private val tokenRequest: JsonField = JsonMissing.of(), - @JsonProperty("user_info_request") - @ExcludeMissing - private val userInfoRequest: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun authorizeRequest(): Optional = - Optional.ofNullable(authorizeRequest.getNullable("authorize_request")) - - fun clientId(): Optional = Optional.ofNullable(clientId.getNullable("client_id")) - - fun clientSecret(): Optional = - Optional.ofNullable(clientSecret.getNullable("client_secret")) - - fun pkce(): Optional = Optional.ofNullable(pkce.getNullable("pkce")) - - /** The redirect URI required for this provider. */ - fun redirectUri(): Optional = - Optional.ofNullable(redirectUri.getNullable("redirect_uri")) - - fun refreshRequest(): Optional = - Optional.ofNullable(refreshRequest.getNullable("refresh_request")) - - fun scopeDelimiter(): Optional = - Optional.ofNullable(scopeDelimiter.getNullable("scope_delimiter")) - - fun tokenIntrospectionRequest(): Optional = - Optional.ofNullable( - tokenIntrospectionRequest.getNullable("token_introspection_request") - ) - - fun tokenRequest(): Optional = - Optional.ofNullable(tokenRequest.getNullable("token_request")) - - fun userInfoRequest(): Optional = - Optional.ofNullable(userInfoRequest.getNullable("user_info_request")) - - @JsonProperty("authorize_request") - @ExcludeMissing - fun _authorizeRequest(): JsonField = authorizeRequest - - @JsonProperty("client_id") @ExcludeMissing fun _clientId(): JsonField = clientId - - @JsonProperty("client_secret") - @ExcludeMissing - fun _clientSecret(): JsonField = clientSecret - - @JsonProperty("pkce") @ExcludeMissing fun _pkce(): JsonField = pkce - - /** The redirect URI required for this provider. */ - @JsonProperty("redirect_uri") - @ExcludeMissing - fun _redirectUri(): JsonField = redirectUri - - @JsonProperty("refresh_request") - @ExcludeMissing - fun _refreshRequest(): JsonField = refreshRequest - - @JsonProperty("scope_delimiter") - @ExcludeMissing - fun _scopeDelimiter(): JsonField = scopeDelimiter - - @JsonProperty("token_introspection_request") - @ExcludeMissing - fun _tokenIntrospectionRequest(): JsonField = - tokenIntrospectionRequest - - @JsonProperty("token_request") - @ExcludeMissing - fun _tokenRequest(): JsonField = tokenRequest - - @JsonProperty("user_info_request") - @ExcludeMissing - fun _userInfoRequest(): JsonField = userInfoRequest - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Oauth2 = apply { - if (validated) { - return@apply - } - - authorizeRequest().ifPresent { it.validate() } - clientId() - clientSecret().ifPresent { it.validate() } - pkce().ifPresent { it.validate() } - redirectUri() - refreshRequest().ifPresent { it.validate() } - scopeDelimiter() - tokenIntrospectionRequest().ifPresent { it.validate() } - tokenRequest().ifPresent { it.validate() } - userInfoRequest().ifPresent { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Oauth2]. */ - class Builder internal constructor() { - - private var authorizeRequest: JsonField = JsonMissing.of() - private var clientId: JsonField = JsonMissing.of() - private var clientSecret: JsonField = JsonMissing.of() - private var pkce: JsonField = JsonMissing.of() - private var redirectUri: JsonField = JsonMissing.of() - private var refreshRequest: JsonField = JsonMissing.of() - private var scopeDelimiter: JsonField = JsonMissing.of() - private var tokenIntrospectionRequest: JsonField = - JsonMissing.of() - private var tokenRequest: JsonField = JsonMissing.of() - private var userInfoRequest: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(oauth2: Oauth2) = apply { - authorizeRequest = oauth2.authorizeRequest - clientId = oauth2.clientId - clientSecret = oauth2.clientSecret - pkce = oauth2.pkce - redirectUri = oauth2.redirectUri - refreshRequest = oauth2.refreshRequest - scopeDelimiter = oauth2.scopeDelimiter - tokenIntrospectionRequest = oauth2.tokenIntrospectionRequest - tokenRequest = oauth2.tokenRequest - userInfoRequest = oauth2.userInfoRequest - additionalProperties = oauth2.additionalProperties.toMutableMap() - } - - fun authorizeRequest(authorizeRequest: AuthorizeRequest) = - authorizeRequest(JsonField.of(authorizeRequest)) - - fun authorizeRequest(authorizeRequest: JsonField) = apply { - this.authorizeRequest = authorizeRequest - } - - fun clientId(clientId: String) = clientId(JsonField.of(clientId)) - - fun clientId(clientId: JsonField) = apply { this.clientId = clientId } - - fun clientSecret(clientSecret: ClientSecret) = clientSecret(JsonField.of(clientSecret)) - - fun clientSecret(clientSecret: JsonField) = apply { - this.clientSecret = clientSecret - } - - fun pkce(pkce: Pkce) = pkce(JsonField.of(pkce)) - - fun pkce(pkce: JsonField) = apply { this.pkce = pkce } - - /** The redirect URI required for this provider. */ - fun redirectUri(redirectUri: String) = redirectUri(JsonField.of(redirectUri)) - - /** The redirect URI required for this provider. */ - fun redirectUri(redirectUri: JsonField) = apply { - this.redirectUri = redirectUri - } - - fun refreshRequest(refreshRequest: RefreshRequest) = - refreshRequest(JsonField.of(refreshRequest)) - - fun refreshRequest(refreshRequest: JsonField) = apply { - this.refreshRequest = refreshRequest - } - - fun scopeDelimiter(scopeDelimiter: String) = - scopeDelimiter(JsonField.of(scopeDelimiter)) - - fun scopeDelimiter(scopeDelimiter: JsonField) = apply { - this.scopeDelimiter = scopeDelimiter - } - - fun tokenIntrospectionRequest(tokenIntrospectionRequest: TokenIntrospectionRequest) = - tokenIntrospectionRequest(JsonField.of(tokenIntrospectionRequest)) - - fun tokenIntrospectionRequest( - tokenIntrospectionRequest: JsonField - ) = apply { this.tokenIntrospectionRequest = tokenIntrospectionRequest } - - fun tokenRequest(tokenRequest: TokenRequest) = tokenRequest(JsonField.of(tokenRequest)) - - fun tokenRequest(tokenRequest: JsonField) = apply { - this.tokenRequest = tokenRequest - } - - fun userInfoRequest(userInfoRequest: UserInfoRequest) = - userInfoRequest(JsonField.of(userInfoRequest)) - - fun userInfoRequest(userInfoRequest: JsonField) = apply { - this.userInfoRequest = userInfoRequest - } - - 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) - } - - fun build(): Oauth2 = - Oauth2( - authorizeRequest, - clientId, - clientSecret, - pkce, - redirectUri, - refreshRequest, - scopeDelimiter, - tokenIntrospectionRequest, - tokenRequest, - userInfoRequest, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class AuthorizeRequest - @JsonCreator - private constructor( - @JsonProperty("auth_header_value_format") - @ExcludeMissing - private val authHeaderValueFormat: JsonField = JsonMissing.of(), - @JsonProperty("auth_method") - @ExcludeMissing - private val authMethod: JsonField = JsonMissing.of(), - @JsonProperty("endpoint") - @ExcludeMissing - private val endpoint: JsonField = JsonMissing.of(), - @JsonProperty("expiration_format") - @ExcludeMissing - private val expirationFormat: JsonField = JsonMissing.of(), - @JsonProperty("method") - @ExcludeMissing - private val method: JsonField = JsonMissing.of(), - @JsonProperty("params") - @ExcludeMissing - private val params: JsonField = JsonMissing.of(), - @JsonProperty("request_content_type") - @ExcludeMissing - private val requestContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_content_type") - @ExcludeMissing - private val responseContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_map") - @ExcludeMissing - private val responseMap: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun authHeaderValueFormat(): Optional = - Optional.ofNullable(authHeaderValueFormat.getNullable("auth_header_value_format")) - - fun authMethod(): Optional = - Optional.ofNullable(authMethod.getNullable("auth_method")) - - fun endpoint(): Optional = Optional.ofNullable(endpoint.getNullable("endpoint")) - - fun expirationFormat(): Optional = - Optional.ofNullable(expirationFormat.getNullable("expiration_format")) - - fun method(): Optional = Optional.ofNullable(method.getNullable("method")) - - fun params(): Optional = Optional.ofNullable(params.getNullable("params")) - - fun requestContentType(): Optional = - Optional.ofNullable(requestContentType.getNullable("request_content_type")) - - fun responseContentType(): Optional = - Optional.ofNullable(responseContentType.getNullable("response_content_type")) - - fun responseMap(): Optional = - Optional.ofNullable(responseMap.getNullable("response_map")) - - @JsonProperty("auth_header_value_format") - @ExcludeMissing - fun _authHeaderValueFormat(): JsonField = authHeaderValueFormat - - @JsonProperty("auth_method") - @ExcludeMissing - fun _authMethod(): JsonField = authMethod - - @JsonProperty("endpoint") @ExcludeMissing fun _endpoint(): JsonField = endpoint - - @JsonProperty("expiration_format") - @ExcludeMissing - fun _expirationFormat(): JsonField = expirationFormat - - @JsonProperty("method") @ExcludeMissing fun _method(): JsonField = method - - @JsonProperty("params") @ExcludeMissing fun _params(): JsonField = params - - @JsonProperty("request_content_type") - @ExcludeMissing - fun _requestContentType(): JsonField = requestContentType - - @JsonProperty("response_content_type") - @ExcludeMissing - fun _responseContentType(): JsonField = responseContentType - - @JsonProperty("response_map") - @ExcludeMissing - fun _responseMap(): JsonField = responseMap - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): AuthorizeRequest = apply { - if (validated) { - return@apply - } - - authHeaderValueFormat() - authMethod() - endpoint() - expirationFormat() - method() - params().ifPresent { it.validate() } - requestContentType() - responseContentType() - responseMap().ifPresent { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [AuthorizeRequest]. */ - class Builder internal constructor() { - - private var authHeaderValueFormat: JsonField = JsonMissing.of() - private var authMethod: JsonField = JsonMissing.of() - private var endpoint: JsonField = JsonMissing.of() - private var expirationFormat: JsonField = JsonMissing.of() - private var method: JsonField = JsonMissing.of() - private var params: JsonField = JsonMissing.of() - private var requestContentType: JsonField = JsonMissing.of() - private var responseContentType: JsonField = JsonMissing.of() - private var responseMap: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(authorizeRequest: AuthorizeRequest) = apply { - authHeaderValueFormat = authorizeRequest.authHeaderValueFormat - authMethod = authorizeRequest.authMethod - endpoint = authorizeRequest.endpoint - expirationFormat = authorizeRequest.expirationFormat - method = authorizeRequest.method - params = authorizeRequest.params - requestContentType = authorizeRequest.requestContentType - responseContentType = authorizeRequest.responseContentType - responseMap = authorizeRequest.responseMap - additionalProperties = authorizeRequest.additionalProperties.toMutableMap() - } - - fun authHeaderValueFormat(authHeaderValueFormat: String) = - authHeaderValueFormat(JsonField.of(authHeaderValueFormat)) - - fun authHeaderValueFormat(authHeaderValueFormat: JsonField) = apply { - this.authHeaderValueFormat = authHeaderValueFormat - } - - fun authMethod(authMethod: String) = authMethod(JsonField.of(authMethod)) - - fun authMethod(authMethod: JsonField) = apply { - this.authMethod = authMethod - } - - fun endpoint(endpoint: String) = endpoint(JsonField.of(endpoint)) - - fun endpoint(endpoint: JsonField) = apply { this.endpoint = endpoint } - - fun expirationFormat(expirationFormat: String) = - expirationFormat(JsonField.of(expirationFormat)) - - fun expirationFormat(expirationFormat: JsonField) = apply { - this.expirationFormat = expirationFormat - } - - fun method(method: String) = method(JsonField.of(method)) - - fun method(method: JsonField) = apply { this.method = method } - - fun params(params: Params) = params(JsonField.of(params)) - - fun params(params: JsonField) = apply { this.params = params } - - fun requestContentType(requestContentType: String) = - requestContentType(JsonField.of(requestContentType)) - - fun requestContentType(requestContentType: JsonField) = apply { - this.requestContentType = requestContentType - } - - fun responseContentType(responseContentType: String) = - responseContentType(JsonField.of(responseContentType)) - - fun responseContentType(responseContentType: JsonField) = apply { - this.responseContentType = responseContentType - } - - fun responseMap(responseMap: ResponseMap) = responseMap(JsonField.of(responseMap)) - - fun responseMap(responseMap: JsonField) = apply { - this.responseMap = responseMap - } - - 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) - } - - fun build(): AuthorizeRequest = - AuthorizeRequest( - authHeaderValueFormat, - authMethod, - endpoint, - expirationFormat, - method, - params, - requestContentType, - responseContentType, - responseMap, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class Params - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Params = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Params]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(params: Params) = apply { - additionalProperties = params.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) - } - - fun build(): Params = Params(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Params && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "Params{additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class ResponseMap - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ResponseMap = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ResponseMap]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(responseMap: ResponseMap) = apply { - additionalProperties = responseMap.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) - } - - fun build(): ResponseMap = ResponseMap(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ResponseMap && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "ResponseMap{additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is AuthorizeRequest && authHeaderValueFormat == other.authHeaderValueFormat && authMethod == other.authMethod && endpoint == other.endpoint && expirationFormat == other.expirationFormat && method == other.method && params == other.params && requestContentType == other.requestContentType && responseContentType == other.responseContentType && responseMap == other.responseMap && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(authHeaderValueFormat, authMethod, endpoint, expirationFormat, method, params, requestContentType, responseContentType, responseMap, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "AuthorizeRequest{authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, endpoint=$endpoint, expirationFormat=$expirationFormat, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class ClientSecret - @JsonCreator - private constructor( - @JsonProperty("binding") - @ExcludeMissing - private val binding: JsonField = JsonMissing.of(), - @JsonProperty("editable") - @ExcludeMissing - private val editable: JsonField = JsonMissing.of(), - @JsonProperty("exists") - @ExcludeMissing - private val exists: JsonField = JsonMissing.of(), - @JsonProperty("hint") - @ExcludeMissing - private val hint: JsonField = JsonMissing.of(), - @JsonProperty("value") - @ExcludeMissing - private val value: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun binding(): Optional = Optional.ofNullable(binding.getNullable("binding")) - - fun editable(): Optional = - Optional.ofNullable(editable.getNullable("editable")) - - fun exists(): Optional = Optional.ofNullable(exists.getNullable("exists")) - - fun hint(): Optional = Optional.ofNullable(hint.getNullable("hint")) - - fun value(): Optional = Optional.ofNullable(value.getNullable("value")) - - @JsonProperty("binding") @ExcludeMissing fun _binding(): JsonField = binding - - @JsonProperty("editable") @ExcludeMissing fun _editable(): JsonField = editable - - @JsonProperty("exists") @ExcludeMissing fun _exists(): JsonField = exists - - @JsonProperty("hint") @ExcludeMissing fun _hint(): JsonField = hint - - @JsonProperty("value") @ExcludeMissing fun _value(): JsonField = value - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ClientSecret = apply { - if (validated) { - return@apply - } - - binding() - editable() - exists() - hint() - value() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ClientSecret]. */ - class Builder internal constructor() { - - private var binding: JsonField = JsonMissing.of() - private var editable: JsonField = JsonMissing.of() - private var exists: JsonField = JsonMissing.of() - private var hint: JsonField = JsonMissing.of() - private var value: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(clientSecret: ClientSecret) = apply { - binding = clientSecret.binding - editable = clientSecret.editable - exists = clientSecret.exists - hint = clientSecret.hint - value = clientSecret.value - additionalProperties = clientSecret.additionalProperties.toMutableMap() - } - - fun binding(binding: Binding) = binding(JsonField.of(binding)) - - fun binding(binding: JsonField) = apply { this.binding = binding } - - fun editable(editable: Boolean) = editable(JsonField.of(editable)) - - fun editable(editable: JsonField) = apply { this.editable = editable } - - fun exists(exists: Boolean) = exists(JsonField.of(exists)) - - fun exists(exists: JsonField) = apply { this.exists = exists } - - fun hint(hint: String) = hint(JsonField.of(hint)) - - fun hint(hint: JsonField) = apply { this.hint = hint } - - fun value(value: String) = value(JsonField.of(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) - } - - fun build(): ClientSecret = - ClientSecret( - binding, - editable, - exists, - hint, - value, - additionalProperties.toImmutable(), - ) - } - - class Binding @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 STATIC = of("static") - - @JvmField val TENANT = of("tenant") - - @JvmField val PROJECT = of("project") - - @JvmField val ACCOUNT = of("account") - - @JvmStatic fun of(value: String) = Binding(JsonField.of(value)) - } - - /** An enum containing [Binding]'s known values. */ - enum class Known { - STATIC, - TENANT, - PROJECT, - ACCOUNT, - } - - /** - * An enum containing [Binding]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [Binding] 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 { - STATIC, - TENANT, - PROJECT, - ACCOUNT, - /** - * An enum member indicating that [Binding] 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) { - STATIC -> Value.STATIC - TENANT -> Value.TENANT - PROJECT -> Value.PROJECT - ACCOUNT -> Value.ACCOUNT - 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 ArcadeInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - STATIC -> Known.STATIC - TENANT -> Known.TENANT - PROJECT -> Known.PROJECT - ACCOUNT -> Known.ACCOUNT - else -> throw ArcadeInvalidDataException("Unknown Binding: $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 ArcadeInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - ArcadeInvalidDataException("Value is not a String") - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Binding && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ClientSecret && binding == other.binding && editable == other.editable && exists == other.exists && hint == other.hint && value == other.value && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(binding, editable, exists, hint, value, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ClientSecret{binding=$binding, editable=$editable, exists=$exists, hint=$hint, value=$value, additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class Pkce - @JsonCreator - private constructor( - @JsonProperty("code_challenge_method") - @ExcludeMissing - private val codeChallengeMethod: JsonField = JsonMissing.of(), - @JsonProperty("enabled") - @ExcludeMissing - private val enabled: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun codeChallengeMethod(): Optional = - Optional.ofNullable(codeChallengeMethod.getNullable("code_challenge_method")) - - fun enabled(): Optional = Optional.ofNullable(enabled.getNullable("enabled")) - - @JsonProperty("code_challenge_method") - @ExcludeMissing - fun _codeChallengeMethod(): JsonField = codeChallengeMethod - - @JsonProperty("enabled") @ExcludeMissing fun _enabled(): JsonField = enabled - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Pkce = apply { - if (validated) { - return@apply - } - - codeChallengeMethod() - enabled() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Pkce]. */ - class Builder internal constructor() { - - private var codeChallengeMethod: JsonField = JsonMissing.of() - private var enabled: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(pkce: Pkce) = apply { - codeChallengeMethod = pkce.codeChallengeMethod - enabled = pkce.enabled - additionalProperties = pkce.additionalProperties.toMutableMap() - } - - fun codeChallengeMethod(codeChallengeMethod: String) = - codeChallengeMethod(JsonField.of(codeChallengeMethod)) - - fun codeChallengeMethod(codeChallengeMethod: JsonField) = apply { - this.codeChallengeMethod = codeChallengeMethod - } - - fun enabled(enabled: Boolean) = enabled(JsonField.of(enabled)) - - fun enabled(enabled: JsonField) = apply { this.enabled = enabled } - - 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) - } - - fun build(): Pkce = - Pkce(codeChallengeMethod, enabled, additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Pkce && codeChallengeMethod == other.codeChallengeMethod && enabled == other.enabled && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(codeChallengeMethod, enabled, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Pkce{codeChallengeMethod=$codeChallengeMethod, enabled=$enabled, additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class RefreshRequest - @JsonCreator - private constructor( - @JsonProperty("auth_header_value_format") - @ExcludeMissing - private val authHeaderValueFormat: JsonField = JsonMissing.of(), - @JsonProperty("auth_method") - @ExcludeMissing - private val authMethod: JsonField = JsonMissing.of(), - @JsonProperty("endpoint") - @ExcludeMissing - private val endpoint: JsonField = JsonMissing.of(), - @JsonProperty("expiration_format") - @ExcludeMissing - private val expirationFormat: JsonField = JsonMissing.of(), - @JsonProperty("method") - @ExcludeMissing - private val method: JsonField = JsonMissing.of(), - @JsonProperty("params") - @ExcludeMissing - private val params: JsonField = JsonMissing.of(), - @JsonProperty("request_content_type") - @ExcludeMissing - private val requestContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_content_type") - @ExcludeMissing - private val responseContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_map") - @ExcludeMissing - private val responseMap: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun authHeaderValueFormat(): Optional = - Optional.ofNullable(authHeaderValueFormat.getNullable("auth_header_value_format")) - - fun authMethod(): Optional = - Optional.ofNullable(authMethod.getNullable("auth_method")) - - fun endpoint(): Optional = Optional.ofNullable(endpoint.getNullable("endpoint")) - - fun expirationFormat(): Optional = - Optional.ofNullable(expirationFormat.getNullable("expiration_format")) - - fun method(): Optional = Optional.ofNullable(method.getNullable("method")) - - fun params(): Optional = Optional.ofNullable(params.getNullable("params")) - - fun requestContentType(): Optional = - Optional.ofNullable(requestContentType.getNullable("request_content_type")) - - fun responseContentType(): Optional = - Optional.ofNullable(responseContentType.getNullable("response_content_type")) - - fun responseMap(): Optional = - Optional.ofNullable(responseMap.getNullable("response_map")) - - @JsonProperty("auth_header_value_format") - @ExcludeMissing - fun _authHeaderValueFormat(): JsonField = authHeaderValueFormat - - @JsonProperty("auth_method") - @ExcludeMissing - fun _authMethod(): JsonField = authMethod - - @JsonProperty("endpoint") @ExcludeMissing fun _endpoint(): JsonField = endpoint - - @JsonProperty("expiration_format") - @ExcludeMissing - fun _expirationFormat(): JsonField = expirationFormat - - @JsonProperty("method") @ExcludeMissing fun _method(): JsonField = method - - @JsonProperty("params") @ExcludeMissing fun _params(): JsonField = params - - @JsonProperty("request_content_type") - @ExcludeMissing - fun _requestContentType(): JsonField = requestContentType - - @JsonProperty("response_content_type") - @ExcludeMissing - fun _responseContentType(): JsonField = responseContentType - - @JsonProperty("response_map") - @ExcludeMissing - fun _responseMap(): JsonField = responseMap - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): RefreshRequest = apply { - if (validated) { - return@apply - } - - authHeaderValueFormat() - authMethod() - endpoint() - expirationFormat() - method() - params().ifPresent { it.validate() } - requestContentType() - responseContentType() - responseMap().ifPresent { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [RefreshRequest]. */ - class Builder internal constructor() { - - private var authHeaderValueFormat: JsonField = JsonMissing.of() - private var authMethod: JsonField = JsonMissing.of() - private var endpoint: JsonField = JsonMissing.of() - private var expirationFormat: JsonField = JsonMissing.of() - private var method: JsonField = JsonMissing.of() - private var params: JsonField = JsonMissing.of() - private var requestContentType: JsonField = JsonMissing.of() - private var responseContentType: JsonField = JsonMissing.of() - private var responseMap: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(refreshRequest: RefreshRequest) = apply { - authHeaderValueFormat = refreshRequest.authHeaderValueFormat - authMethod = refreshRequest.authMethod - endpoint = refreshRequest.endpoint - expirationFormat = refreshRequest.expirationFormat - method = refreshRequest.method - params = refreshRequest.params - requestContentType = refreshRequest.requestContentType - responseContentType = refreshRequest.responseContentType - responseMap = refreshRequest.responseMap - additionalProperties = refreshRequest.additionalProperties.toMutableMap() - } - - fun authHeaderValueFormat(authHeaderValueFormat: String) = - authHeaderValueFormat(JsonField.of(authHeaderValueFormat)) - - fun authHeaderValueFormat(authHeaderValueFormat: JsonField) = apply { - this.authHeaderValueFormat = authHeaderValueFormat - } - - fun authMethod(authMethod: String) = authMethod(JsonField.of(authMethod)) - - fun authMethod(authMethod: JsonField) = apply { - this.authMethod = authMethod - } - - fun endpoint(endpoint: String) = endpoint(JsonField.of(endpoint)) - - fun endpoint(endpoint: JsonField) = apply { this.endpoint = endpoint } - - fun expirationFormat(expirationFormat: String) = - expirationFormat(JsonField.of(expirationFormat)) - - fun expirationFormat(expirationFormat: JsonField) = apply { - this.expirationFormat = expirationFormat - } - - fun method(method: String) = method(JsonField.of(method)) - - fun method(method: JsonField) = apply { this.method = method } - - fun params(params: Params) = params(JsonField.of(params)) - - fun params(params: JsonField) = apply { this.params = params } - - fun requestContentType(requestContentType: String) = - requestContentType(JsonField.of(requestContentType)) - - fun requestContentType(requestContentType: JsonField) = apply { - this.requestContentType = requestContentType - } - - fun responseContentType(responseContentType: String) = - responseContentType(JsonField.of(responseContentType)) - - fun responseContentType(responseContentType: JsonField) = apply { - this.responseContentType = responseContentType - } - - fun responseMap(responseMap: ResponseMap) = responseMap(JsonField.of(responseMap)) - - fun responseMap(responseMap: JsonField) = apply { - this.responseMap = responseMap - } - - 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) - } - - fun build(): RefreshRequest = - RefreshRequest( - authHeaderValueFormat, - authMethod, - endpoint, - expirationFormat, - method, - params, - requestContentType, - responseContentType, - responseMap, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class Params - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Params = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Params]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(params: Params) = apply { - additionalProperties = params.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) - } - - fun build(): Params = Params(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Params && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "Params{additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class ResponseMap - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ResponseMap = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ResponseMap]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(responseMap: ResponseMap) = apply { - additionalProperties = responseMap.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) - } - - fun build(): ResponseMap = ResponseMap(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ResponseMap && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "ResponseMap{additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is RefreshRequest && authHeaderValueFormat == other.authHeaderValueFormat && authMethod == other.authMethod && endpoint == other.endpoint && expirationFormat == other.expirationFormat && method == other.method && params == other.params && requestContentType == other.requestContentType && responseContentType == other.responseContentType && responseMap == other.responseMap && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(authHeaderValueFormat, authMethod, endpoint, expirationFormat, method, params, requestContentType, responseContentType, responseMap, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "RefreshRequest{authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, endpoint=$endpoint, expirationFormat=$expirationFormat, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class TokenIntrospectionRequest - @JsonCreator - private constructor( - @JsonProperty("auth_header_value_format") - @ExcludeMissing - private val authHeaderValueFormat: JsonField = JsonMissing.of(), - @JsonProperty("auth_method") - @ExcludeMissing - private val authMethod: JsonField = JsonMissing.of(), - @JsonProperty("enabled") - @ExcludeMissing - private val enabled: JsonField = JsonMissing.of(), - @JsonProperty("endpoint") - @ExcludeMissing - private val endpoint: JsonField = JsonMissing.of(), - @JsonProperty("expiration_format") - @ExcludeMissing - private val expirationFormat: JsonField = JsonMissing.of(), - @JsonProperty("method") - @ExcludeMissing - private val method: JsonField = JsonMissing.of(), - @JsonProperty("params") - @ExcludeMissing - private val params: JsonField = JsonMissing.of(), - @JsonProperty("request_content_type") - @ExcludeMissing - private val requestContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_content_type") - @ExcludeMissing - private val responseContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_map") - @ExcludeMissing - private val responseMap: JsonField = JsonMissing.of(), - @JsonProperty("triggers") - @ExcludeMissing - private val triggers: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun authHeaderValueFormat(): Optional = - Optional.ofNullable(authHeaderValueFormat.getNullable("auth_header_value_format")) - - fun authMethod(): Optional = - Optional.ofNullable(authMethod.getNullable("auth_method")) - - fun enabled(): Optional = Optional.ofNullable(enabled.getNullable("enabled")) - - fun endpoint(): Optional = Optional.ofNullable(endpoint.getNullable("endpoint")) - - fun expirationFormat(): Optional = - Optional.ofNullable(expirationFormat.getNullable("expiration_format")) - - fun method(): Optional = Optional.ofNullable(method.getNullable("method")) - - fun params(): Optional = Optional.ofNullable(params.getNullable("params")) - - fun requestContentType(): Optional = - Optional.ofNullable(requestContentType.getNullable("request_content_type")) - - fun responseContentType(): Optional = - Optional.ofNullable(responseContentType.getNullable("response_content_type")) - - fun responseMap(): Optional = - Optional.ofNullable(responseMap.getNullable("response_map")) - - fun triggers(): Optional = - Optional.ofNullable(triggers.getNullable("triggers")) - - @JsonProperty("auth_header_value_format") - @ExcludeMissing - fun _authHeaderValueFormat(): JsonField = authHeaderValueFormat - - @JsonProperty("auth_method") - @ExcludeMissing - fun _authMethod(): JsonField = authMethod - - @JsonProperty("enabled") @ExcludeMissing fun _enabled(): JsonField = enabled - - @JsonProperty("endpoint") @ExcludeMissing fun _endpoint(): JsonField = endpoint - - @JsonProperty("expiration_format") - @ExcludeMissing - fun _expirationFormat(): JsonField = expirationFormat - - @JsonProperty("method") @ExcludeMissing fun _method(): JsonField = method - - @JsonProperty("params") @ExcludeMissing fun _params(): JsonField = params - - @JsonProperty("request_content_type") - @ExcludeMissing - fun _requestContentType(): JsonField = requestContentType - - @JsonProperty("response_content_type") - @ExcludeMissing - fun _responseContentType(): JsonField = responseContentType - - @JsonProperty("response_map") - @ExcludeMissing - fun _responseMap(): JsonField = responseMap - - @JsonProperty("triggers") - @ExcludeMissing - fun _triggers(): JsonField = triggers - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): TokenIntrospectionRequest = apply { - if (validated) { - return@apply - } - - authHeaderValueFormat() - authMethod() - enabled() - endpoint() - expirationFormat() - method() - params().ifPresent { it.validate() } - requestContentType() - responseContentType() - responseMap().ifPresent { it.validate() } - triggers().ifPresent { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [TokenIntrospectionRequest]. */ - class Builder internal constructor() { - - private var authHeaderValueFormat: JsonField = JsonMissing.of() - private var authMethod: JsonField = JsonMissing.of() - private var enabled: JsonField = JsonMissing.of() - private var endpoint: JsonField = JsonMissing.of() - private var expirationFormat: JsonField = JsonMissing.of() - private var method: JsonField = JsonMissing.of() - private var params: JsonField = JsonMissing.of() - private var requestContentType: JsonField = JsonMissing.of() - private var responseContentType: JsonField = JsonMissing.of() - private var responseMap: JsonField = JsonMissing.of() - private var triggers: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(tokenIntrospectionRequest: TokenIntrospectionRequest) = apply { - authHeaderValueFormat = tokenIntrospectionRequest.authHeaderValueFormat - authMethod = tokenIntrospectionRequest.authMethod - enabled = tokenIntrospectionRequest.enabled - endpoint = tokenIntrospectionRequest.endpoint - expirationFormat = tokenIntrospectionRequest.expirationFormat - method = tokenIntrospectionRequest.method - params = tokenIntrospectionRequest.params - requestContentType = tokenIntrospectionRequest.requestContentType - responseContentType = tokenIntrospectionRequest.responseContentType - responseMap = tokenIntrospectionRequest.responseMap - triggers = tokenIntrospectionRequest.triggers - additionalProperties = - tokenIntrospectionRequest.additionalProperties.toMutableMap() - } - - fun authHeaderValueFormat(authHeaderValueFormat: String) = - authHeaderValueFormat(JsonField.of(authHeaderValueFormat)) - - fun authHeaderValueFormat(authHeaderValueFormat: JsonField) = apply { - this.authHeaderValueFormat = authHeaderValueFormat - } - - fun authMethod(authMethod: String) = authMethod(JsonField.of(authMethod)) - - fun authMethod(authMethod: JsonField) = apply { - this.authMethod = authMethod - } - - fun enabled(enabled: Boolean) = enabled(JsonField.of(enabled)) - - fun enabled(enabled: JsonField) = apply { this.enabled = enabled } - - fun endpoint(endpoint: String) = endpoint(JsonField.of(endpoint)) - - fun endpoint(endpoint: JsonField) = apply { this.endpoint = endpoint } - - fun expirationFormat(expirationFormat: String) = - expirationFormat(JsonField.of(expirationFormat)) - - fun expirationFormat(expirationFormat: JsonField) = apply { - this.expirationFormat = expirationFormat - } - - fun method(method: String) = method(JsonField.of(method)) - - fun method(method: JsonField) = apply { this.method = method } - - fun params(params: Params) = params(JsonField.of(params)) - - fun params(params: JsonField) = apply { this.params = params } - - fun requestContentType(requestContentType: String) = - requestContentType(JsonField.of(requestContentType)) - - fun requestContentType(requestContentType: JsonField) = apply { - this.requestContentType = requestContentType - } - - fun responseContentType(responseContentType: String) = - responseContentType(JsonField.of(responseContentType)) - - fun responseContentType(responseContentType: JsonField) = apply { - this.responseContentType = responseContentType - } - - fun responseMap(responseMap: ResponseMap) = responseMap(JsonField.of(responseMap)) - - fun responseMap(responseMap: JsonField) = apply { - this.responseMap = responseMap - } - - fun triggers(triggers: Triggers) = triggers(JsonField.of(triggers)) - - fun triggers(triggers: JsonField) = apply { this.triggers = triggers } - - 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) - } - - fun build(): TokenIntrospectionRequest = - TokenIntrospectionRequest( - authHeaderValueFormat, - authMethod, - enabled, - endpoint, - expirationFormat, - method, - params, - requestContentType, - responseContentType, - responseMap, - triggers, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class Params - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Params = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Params]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(params: Params) = apply { - additionalProperties = params.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) - } - - fun build(): Params = Params(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Params && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "Params{additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class ResponseMap - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ResponseMap = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ResponseMap]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(responseMap: ResponseMap) = apply { - additionalProperties = responseMap.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) - } - - fun build(): ResponseMap = ResponseMap(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ResponseMap && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "ResponseMap{additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class Triggers - @JsonCreator - private constructor( - @JsonProperty("on_token_grant") - @ExcludeMissing - private val onTokenGrant: JsonField = JsonMissing.of(), - @JsonProperty("on_token_refresh") - @ExcludeMissing - private val onTokenRefresh: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun onTokenGrant(): Optional = - Optional.ofNullable(onTokenGrant.getNullable("on_token_grant")) - - fun onTokenRefresh(): Optional = - Optional.ofNullable(onTokenRefresh.getNullable("on_token_refresh")) - - @JsonProperty("on_token_grant") - @ExcludeMissing - fun _onTokenGrant(): JsonField = onTokenGrant - - @JsonProperty("on_token_refresh") - @ExcludeMissing - fun _onTokenRefresh(): JsonField = onTokenRefresh - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Triggers = apply { - if (validated) { - return@apply - } - - onTokenGrant() - onTokenRefresh() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Triggers]. */ - class Builder internal constructor() { - - private var onTokenGrant: JsonField = JsonMissing.of() - private var onTokenRefresh: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(triggers: Triggers) = apply { - onTokenGrant = triggers.onTokenGrant - onTokenRefresh = triggers.onTokenRefresh - additionalProperties = triggers.additionalProperties.toMutableMap() - } - - fun onTokenGrant(onTokenGrant: Boolean) = - onTokenGrant(JsonField.of(onTokenGrant)) - - fun onTokenGrant(onTokenGrant: JsonField) = apply { - this.onTokenGrant = onTokenGrant - } - - fun onTokenRefresh(onTokenRefresh: Boolean) = - onTokenRefresh(JsonField.of(onTokenRefresh)) - - fun onTokenRefresh(onTokenRefresh: JsonField) = apply { - this.onTokenRefresh = onTokenRefresh - } - - 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) - } - - fun build(): Triggers = - Triggers(onTokenGrant, onTokenRefresh, additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Triggers && onTokenGrant == other.onTokenGrant && onTokenRefresh == other.onTokenRefresh && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(onTokenGrant, onTokenRefresh, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Triggers{onTokenGrant=$onTokenGrant, onTokenRefresh=$onTokenRefresh, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is TokenIntrospectionRequest && authHeaderValueFormat == other.authHeaderValueFormat && authMethod == other.authMethod && enabled == other.enabled && endpoint == other.endpoint && expirationFormat == other.expirationFormat && method == other.method && params == other.params && requestContentType == other.requestContentType && responseContentType == other.responseContentType && responseMap == other.responseMap && triggers == other.triggers && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(authHeaderValueFormat, authMethod, enabled, endpoint, expirationFormat, method, params, requestContentType, responseContentType, responseMap, triggers, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "TokenIntrospectionRequest{authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, enabled=$enabled, endpoint=$endpoint, expirationFormat=$expirationFormat, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, triggers=$triggers, additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class TokenRequest - @JsonCreator - private constructor( - @JsonProperty("auth_header_value_format") - @ExcludeMissing - private val authHeaderValueFormat: JsonField = JsonMissing.of(), - @JsonProperty("auth_method") - @ExcludeMissing - private val authMethod: JsonField = JsonMissing.of(), - @JsonProperty("endpoint") - @ExcludeMissing - private val endpoint: JsonField = JsonMissing.of(), - @JsonProperty("expiration_format") - @ExcludeMissing - private val expirationFormat: JsonField = JsonMissing.of(), - @JsonProperty("method") - @ExcludeMissing - private val method: JsonField = JsonMissing.of(), - @JsonProperty("params") - @ExcludeMissing - private val params: JsonField = JsonMissing.of(), - @JsonProperty("request_content_type") - @ExcludeMissing - private val requestContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_content_type") - @ExcludeMissing - private val responseContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_map") - @ExcludeMissing - private val responseMap: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun authHeaderValueFormat(): Optional = - Optional.ofNullable(authHeaderValueFormat.getNullable("auth_header_value_format")) - - fun authMethod(): Optional = - Optional.ofNullable(authMethod.getNullable("auth_method")) - - fun endpoint(): Optional = Optional.ofNullable(endpoint.getNullable("endpoint")) - - fun expirationFormat(): Optional = - Optional.ofNullable(expirationFormat.getNullable("expiration_format")) - - fun method(): Optional = Optional.ofNullable(method.getNullable("method")) - - fun params(): Optional = Optional.ofNullable(params.getNullable("params")) - - fun requestContentType(): Optional = - Optional.ofNullable(requestContentType.getNullable("request_content_type")) - - fun responseContentType(): Optional = - Optional.ofNullable(responseContentType.getNullable("response_content_type")) - - fun responseMap(): Optional = - Optional.ofNullable(responseMap.getNullable("response_map")) - - @JsonProperty("auth_header_value_format") - @ExcludeMissing - fun _authHeaderValueFormat(): JsonField = authHeaderValueFormat - - @JsonProperty("auth_method") - @ExcludeMissing - fun _authMethod(): JsonField = authMethod - - @JsonProperty("endpoint") @ExcludeMissing fun _endpoint(): JsonField = endpoint - - @JsonProperty("expiration_format") - @ExcludeMissing - fun _expirationFormat(): JsonField = expirationFormat - - @JsonProperty("method") @ExcludeMissing fun _method(): JsonField = method - - @JsonProperty("params") @ExcludeMissing fun _params(): JsonField = params - - @JsonProperty("request_content_type") - @ExcludeMissing - fun _requestContentType(): JsonField = requestContentType - - @JsonProperty("response_content_type") - @ExcludeMissing - fun _responseContentType(): JsonField = responseContentType - - @JsonProperty("response_map") - @ExcludeMissing - fun _responseMap(): JsonField = responseMap - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): TokenRequest = apply { - if (validated) { - return@apply - } - - authHeaderValueFormat() - authMethod() - endpoint() - expirationFormat() - method() - params().ifPresent { it.validate() } - requestContentType() - responseContentType() - responseMap().ifPresent { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [TokenRequest]. */ - class Builder internal constructor() { - - private var authHeaderValueFormat: JsonField = JsonMissing.of() - private var authMethod: JsonField = JsonMissing.of() - private var endpoint: JsonField = JsonMissing.of() - private var expirationFormat: JsonField = JsonMissing.of() - private var method: JsonField = JsonMissing.of() - private var params: JsonField = JsonMissing.of() - private var requestContentType: JsonField = JsonMissing.of() - private var responseContentType: JsonField = JsonMissing.of() - private var responseMap: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(tokenRequest: TokenRequest) = apply { - authHeaderValueFormat = tokenRequest.authHeaderValueFormat - authMethod = tokenRequest.authMethod - endpoint = tokenRequest.endpoint - expirationFormat = tokenRequest.expirationFormat - method = tokenRequest.method - params = tokenRequest.params - requestContentType = tokenRequest.requestContentType - responseContentType = tokenRequest.responseContentType - responseMap = tokenRequest.responseMap - additionalProperties = tokenRequest.additionalProperties.toMutableMap() - } - - fun authHeaderValueFormat(authHeaderValueFormat: String) = - authHeaderValueFormat(JsonField.of(authHeaderValueFormat)) - - fun authHeaderValueFormat(authHeaderValueFormat: JsonField) = apply { - this.authHeaderValueFormat = authHeaderValueFormat - } - - fun authMethod(authMethod: String) = authMethod(JsonField.of(authMethod)) - - fun authMethod(authMethod: JsonField) = apply { - this.authMethod = authMethod - } - - fun endpoint(endpoint: String) = endpoint(JsonField.of(endpoint)) - - fun endpoint(endpoint: JsonField) = apply { this.endpoint = endpoint } - - fun expirationFormat(expirationFormat: String) = - expirationFormat(JsonField.of(expirationFormat)) - - fun expirationFormat(expirationFormat: JsonField) = apply { - this.expirationFormat = expirationFormat - } - - fun method(method: String) = method(JsonField.of(method)) - - fun method(method: JsonField) = apply { this.method = method } - - fun params(params: Params) = params(JsonField.of(params)) - - fun params(params: JsonField) = apply { this.params = params } - - fun requestContentType(requestContentType: String) = - requestContentType(JsonField.of(requestContentType)) - - fun requestContentType(requestContentType: JsonField) = apply { - this.requestContentType = requestContentType - } - - fun responseContentType(responseContentType: String) = - responseContentType(JsonField.of(responseContentType)) - - fun responseContentType(responseContentType: JsonField) = apply { - this.responseContentType = responseContentType - } - - fun responseMap(responseMap: ResponseMap) = responseMap(JsonField.of(responseMap)) - - fun responseMap(responseMap: JsonField) = apply { - this.responseMap = responseMap - } - - 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) - } - - fun build(): TokenRequest = - TokenRequest( - authHeaderValueFormat, - authMethod, - endpoint, - expirationFormat, - method, - params, - requestContentType, - responseContentType, - responseMap, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class Params - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Params = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Params]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(params: Params) = apply { - additionalProperties = params.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) - } - - fun build(): Params = Params(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Params && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "Params{additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class ResponseMap - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ResponseMap = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ResponseMap]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(responseMap: ResponseMap) = apply { - additionalProperties = responseMap.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) - } - - fun build(): ResponseMap = ResponseMap(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ResponseMap && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "ResponseMap{additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is TokenRequest && authHeaderValueFormat == other.authHeaderValueFormat && authMethod == other.authMethod && endpoint == other.endpoint && expirationFormat == other.expirationFormat && method == other.method && params == other.params && requestContentType == other.requestContentType && responseContentType == other.responseContentType && responseMap == other.responseMap && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(authHeaderValueFormat, authMethod, endpoint, expirationFormat, method, params, requestContentType, responseContentType, responseMap, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "TokenRequest{authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, endpoint=$endpoint, expirationFormat=$expirationFormat, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class UserInfoRequest - @JsonCreator - private constructor( - @JsonProperty("auth_header_value_format") - @ExcludeMissing - private val authHeaderValueFormat: JsonField = JsonMissing.of(), - @JsonProperty("auth_method") - @ExcludeMissing - private val authMethod: JsonField = JsonMissing.of(), - @JsonProperty("endpoint") - @ExcludeMissing - private val endpoint: JsonField = JsonMissing.of(), - @JsonProperty("expiration_format") - @ExcludeMissing - private val expirationFormat: JsonField = JsonMissing.of(), - @JsonProperty("method") - @ExcludeMissing - private val method: JsonField = JsonMissing.of(), - @JsonProperty("params") - @ExcludeMissing - private val params: JsonField = JsonMissing.of(), - @JsonProperty("request_content_type") - @ExcludeMissing - private val requestContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_content_type") - @ExcludeMissing - private val responseContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_map") - @ExcludeMissing - private val responseMap: JsonField = JsonMissing.of(), - @JsonProperty("triggers") - @ExcludeMissing - private val triggers: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun authHeaderValueFormat(): Optional = - Optional.ofNullable(authHeaderValueFormat.getNullable("auth_header_value_format")) - - fun authMethod(): Optional = - Optional.ofNullable(authMethod.getNullable("auth_method")) - - fun endpoint(): Optional = Optional.ofNullable(endpoint.getNullable("endpoint")) - - fun expirationFormat(): Optional = - Optional.ofNullable(expirationFormat.getNullable("expiration_format")) - - fun method(): Optional = Optional.ofNullable(method.getNullable("method")) - - fun params(): Optional = Optional.ofNullable(params.getNullable("params")) - - fun requestContentType(): Optional = - Optional.ofNullable(requestContentType.getNullable("request_content_type")) - - fun responseContentType(): Optional = - Optional.ofNullable(responseContentType.getNullable("response_content_type")) - - fun responseMap(): Optional = - Optional.ofNullable(responseMap.getNullable("response_map")) - - fun triggers(): Optional = - Optional.ofNullable(triggers.getNullable("triggers")) - - @JsonProperty("auth_header_value_format") - @ExcludeMissing - fun _authHeaderValueFormat(): JsonField = authHeaderValueFormat - - @JsonProperty("auth_method") - @ExcludeMissing - fun _authMethod(): JsonField = authMethod - - @JsonProperty("endpoint") @ExcludeMissing fun _endpoint(): JsonField = endpoint - - @JsonProperty("expiration_format") - @ExcludeMissing - fun _expirationFormat(): JsonField = expirationFormat - - @JsonProperty("method") @ExcludeMissing fun _method(): JsonField = method - - @JsonProperty("params") @ExcludeMissing fun _params(): JsonField = params - - @JsonProperty("request_content_type") - @ExcludeMissing - fun _requestContentType(): JsonField = requestContentType - - @JsonProperty("response_content_type") - @ExcludeMissing - fun _responseContentType(): JsonField = responseContentType - - @JsonProperty("response_map") - @ExcludeMissing - fun _responseMap(): JsonField = responseMap - - @JsonProperty("triggers") - @ExcludeMissing - fun _triggers(): JsonField = triggers - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): UserInfoRequest = apply { - if (validated) { - return@apply - } - - authHeaderValueFormat() - authMethod() - endpoint() - expirationFormat() - method() - params().ifPresent { it.validate() } - requestContentType() - responseContentType() - responseMap().ifPresent { it.validate() } - triggers().ifPresent { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [UserInfoRequest]. */ - class Builder internal constructor() { - - private var authHeaderValueFormat: JsonField = JsonMissing.of() - private var authMethod: JsonField = JsonMissing.of() - private var endpoint: JsonField = JsonMissing.of() - private var expirationFormat: JsonField = JsonMissing.of() - private var method: JsonField = JsonMissing.of() - private var params: JsonField = JsonMissing.of() - private var requestContentType: JsonField = JsonMissing.of() - private var responseContentType: JsonField = JsonMissing.of() - private var responseMap: JsonField = JsonMissing.of() - private var triggers: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(userInfoRequest: UserInfoRequest) = apply { - authHeaderValueFormat = userInfoRequest.authHeaderValueFormat - authMethod = userInfoRequest.authMethod - endpoint = userInfoRequest.endpoint - expirationFormat = userInfoRequest.expirationFormat - method = userInfoRequest.method - params = userInfoRequest.params - requestContentType = userInfoRequest.requestContentType - responseContentType = userInfoRequest.responseContentType - responseMap = userInfoRequest.responseMap - triggers = userInfoRequest.triggers - additionalProperties = userInfoRequest.additionalProperties.toMutableMap() - } - - fun authHeaderValueFormat(authHeaderValueFormat: String) = - authHeaderValueFormat(JsonField.of(authHeaderValueFormat)) - - fun authHeaderValueFormat(authHeaderValueFormat: JsonField) = apply { - this.authHeaderValueFormat = authHeaderValueFormat - } - - fun authMethod(authMethod: String) = authMethod(JsonField.of(authMethod)) - - fun authMethod(authMethod: JsonField) = apply { - this.authMethod = authMethod - } - - fun endpoint(endpoint: String) = endpoint(JsonField.of(endpoint)) - - fun endpoint(endpoint: JsonField) = apply { this.endpoint = endpoint } - - fun expirationFormat(expirationFormat: String) = - expirationFormat(JsonField.of(expirationFormat)) - - fun expirationFormat(expirationFormat: JsonField) = apply { - this.expirationFormat = expirationFormat - } - - fun method(method: String) = method(JsonField.of(method)) - - fun method(method: JsonField) = apply { this.method = method } - - fun params(params: Params) = params(JsonField.of(params)) - - fun params(params: JsonField) = apply { this.params = params } - - fun requestContentType(requestContentType: String) = - requestContentType(JsonField.of(requestContentType)) - - fun requestContentType(requestContentType: JsonField) = apply { - this.requestContentType = requestContentType - } - - fun responseContentType(responseContentType: String) = - responseContentType(JsonField.of(responseContentType)) - - fun responseContentType(responseContentType: JsonField) = apply { - this.responseContentType = responseContentType - } - - fun responseMap(responseMap: ResponseMap) = responseMap(JsonField.of(responseMap)) - - fun responseMap(responseMap: JsonField) = apply { - this.responseMap = responseMap - } - - fun triggers(triggers: Triggers) = triggers(JsonField.of(triggers)) - - fun triggers(triggers: JsonField) = apply { this.triggers = triggers } - - 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) - } - - fun build(): UserInfoRequest = - UserInfoRequest( - authHeaderValueFormat, - authMethod, - endpoint, - expirationFormat, - method, - params, - requestContentType, - responseContentType, - responseMap, - triggers, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class Params - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Params = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Params]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(params: Params) = apply { - additionalProperties = params.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) - } - - fun build(): Params = Params(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Params && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "Params{additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class ResponseMap - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ResponseMap = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ResponseMap]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(responseMap: ResponseMap) = apply { - additionalProperties = responseMap.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) - } - - fun build(): ResponseMap = ResponseMap(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ResponseMap && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "ResponseMap{additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class Triggers - @JsonCreator - private constructor( - @JsonProperty("on_token_grant") - @ExcludeMissing - private val onTokenGrant: JsonField = JsonMissing.of(), - @JsonProperty("on_token_refresh") - @ExcludeMissing - private val onTokenRefresh: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun onTokenGrant(): Optional = - Optional.ofNullable(onTokenGrant.getNullable("on_token_grant")) - - fun onTokenRefresh(): Optional = - Optional.ofNullable(onTokenRefresh.getNullable("on_token_refresh")) - - @JsonProperty("on_token_grant") - @ExcludeMissing - fun _onTokenGrant(): JsonField = onTokenGrant - - @JsonProperty("on_token_refresh") - @ExcludeMissing - fun _onTokenRefresh(): JsonField = onTokenRefresh - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Triggers = apply { - if (validated) { - return@apply - } - - onTokenGrant() - onTokenRefresh() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Triggers]. */ - class Builder internal constructor() { - - private var onTokenGrant: JsonField = JsonMissing.of() - private var onTokenRefresh: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(triggers: Triggers) = apply { - onTokenGrant = triggers.onTokenGrant - onTokenRefresh = triggers.onTokenRefresh - additionalProperties = triggers.additionalProperties.toMutableMap() - } - - fun onTokenGrant(onTokenGrant: Boolean) = - onTokenGrant(JsonField.of(onTokenGrant)) - - fun onTokenGrant(onTokenGrant: JsonField) = apply { - this.onTokenGrant = onTokenGrant - } - - fun onTokenRefresh(onTokenRefresh: Boolean) = - onTokenRefresh(JsonField.of(onTokenRefresh)) - - fun onTokenRefresh(onTokenRefresh: JsonField) = apply { - this.onTokenRefresh = onTokenRefresh - } - - 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) - } - - fun build(): Triggers = - Triggers(onTokenGrant, onTokenRefresh, additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Triggers && onTokenGrant == other.onTokenGrant && onTokenRefresh == other.onTokenRefresh && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(onTokenGrant, onTokenRefresh, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Triggers{onTokenGrant=$onTokenGrant, onTokenRefresh=$onTokenRefresh, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is UserInfoRequest && authHeaderValueFormat == other.authHeaderValueFormat && authMethod == other.authMethod && endpoint == other.endpoint && expirationFormat == other.expirationFormat && method == other.method && params == other.params && requestContentType == other.requestContentType && responseContentType == other.responseContentType && responseMap == other.responseMap && triggers == other.triggers && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(authHeaderValueFormat, authMethod, endpoint, expirationFormat, method, params, requestContentType, responseContentType, responseMap, triggers, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "UserInfoRequest{authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, endpoint=$endpoint, expirationFormat=$expirationFormat, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, triggers=$triggers, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Oauth2 && authorizeRequest == other.authorizeRequest && clientId == other.clientId && clientSecret == other.clientSecret && pkce == other.pkce && redirectUri == other.redirectUri && refreshRequest == other.refreshRequest && scopeDelimiter == other.scopeDelimiter && tokenIntrospectionRequest == other.tokenIntrospectionRequest && tokenRequest == other.tokenRequest && userInfoRequest == other.userInfoRequest && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(authorizeRequest, clientId, clientSecret, pkce, redirectUri, refreshRequest, scopeDelimiter, tokenIntrospectionRequest, tokenRequest, userInfoRequest, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Oauth2{authorizeRequest=$authorizeRequest, clientId=$clientId, clientSecret=$clientSecret, pkce=$pkce, redirectUri=$redirectUri, refreshRequest=$refreshRequest, scopeDelimiter=$scopeDelimiter, tokenIntrospectionRequest=$tokenIntrospectionRequest, tokenRequest=$tokenRequest, userInfoRequest=$userInfoRequest, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is AuthProviderResponse && id == other.id && binding == other.binding && createdAt == other.createdAt && description == other.description && oauth2 == other.oauth2 && providerId == other.providerId && status == other.status && type == other.type && updatedAt == other.updatedAt && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(id, binding, createdAt, description, oauth2, providerId, status, type, updatedAt, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "AuthProviderResponse{id=$id, binding=$binding, createdAt=$createdAt, description=$description, oauth2=$oauth2, providerId=$providerId, status=$status, type=$type, updatedAt=$updatedAt, additionalProperties=$additionalProperties}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthProviderUpdateRequest.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthProviderUpdateRequest.kt deleted file mode 100644 index ad2c258..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthProviderUpdateRequest.kt +++ /dev/null @@ -1,3240 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.Enum -import dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import dev.arcade.errors.ArcadeInvalidDataException -import java.util.Objects -import java.util.Optional - -@NoAutoDetect -class AuthProviderUpdateRequest -@JsonCreator -private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("oauth2") - @ExcludeMissing - private val oauth2: JsonField = JsonMissing.of(), - @JsonProperty("provider_id") - @ExcludeMissing - private val providerId: JsonField = JsonMissing.of(), - @JsonProperty("status") - @ExcludeMissing - private val status: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), -) { - - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) - - fun oauth2(): Optional = Optional.ofNullable(oauth2.getNullable("oauth2")) - - fun providerId(): Optional = Optional.ofNullable(providerId.getNullable("provider_id")) - - fun status(): Optional = Optional.ofNullable(status.getNullable("status")) - - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - - @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - - @JsonProperty("description") @ExcludeMissing fun _description(): JsonField = description - - @JsonProperty("oauth2") @ExcludeMissing fun _oauth2(): JsonField = oauth2 - - @JsonProperty("provider_id") @ExcludeMissing fun _providerId(): JsonField = providerId - - @JsonProperty("status") @ExcludeMissing fun _status(): JsonField = status - - @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): AuthProviderUpdateRequest = apply { - if (validated) { - return@apply - } - - id() - description() - oauth2().ifPresent { it.validate() } - providerId() - status() - type() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [AuthProviderUpdateRequest]. */ - class Builder internal constructor() { - - private var id: JsonField = JsonMissing.of() - private var description: JsonField = JsonMissing.of() - private var oauth2: JsonField = JsonMissing.of() - private var providerId: JsonField = JsonMissing.of() - private var status: JsonField = JsonMissing.of() - private var type: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(authProviderUpdateRequest: AuthProviderUpdateRequest) = apply { - id = authProviderUpdateRequest.id - description = authProviderUpdateRequest.description - oauth2 = authProviderUpdateRequest.oauth2 - providerId = authProviderUpdateRequest.providerId - status = authProviderUpdateRequest.status - type = authProviderUpdateRequest.type - additionalProperties = authProviderUpdateRequest.additionalProperties.toMutableMap() - } - - fun id(id: String) = id(JsonField.of(id)) - - fun id(id: JsonField) = apply { this.id = id } - - fun description(description: String) = description(JsonField.of(description)) - - fun description(description: JsonField) = apply { this.description = description } - - fun oauth2(oauth2: Oauth2) = oauth2(JsonField.of(oauth2)) - - fun oauth2(oauth2: JsonField) = apply { this.oauth2 = oauth2 } - - fun providerId(providerId: String) = providerId(JsonField.of(providerId)) - - fun providerId(providerId: JsonField) = apply { this.providerId = providerId } - - fun status(status: String) = status(JsonField.of(status)) - - fun status(status: JsonField) = apply { this.status = status } - - fun type(type: String) = type(JsonField.of(type)) - - 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) - } - - fun build(): AuthProviderUpdateRequest = - AuthProviderUpdateRequest( - id, - description, - oauth2, - providerId, - status, - type, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class Oauth2 - @JsonCreator - private constructor( - @JsonProperty("authorize_request") - @ExcludeMissing - private val authorizeRequest: JsonField = JsonMissing.of(), - @JsonProperty("client_id") - @ExcludeMissing - private val clientId: JsonField = JsonMissing.of(), - @JsonProperty("client_secret") - @ExcludeMissing - private val clientSecret: JsonField = JsonMissing.of(), - @JsonProperty("pkce") @ExcludeMissing private val pkce: JsonField = JsonMissing.of(), - @JsonProperty("refresh_request") - @ExcludeMissing - private val refreshRequest: JsonField = JsonMissing.of(), - @JsonProperty("scope_delimiter") - @ExcludeMissing - private val scopeDelimiter: JsonField = JsonMissing.of(), - @JsonProperty("token_request") - @ExcludeMissing - private val tokenRequest: JsonField = JsonMissing.of(), - @JsonProperty("user_info_request") - @ExcludeMissing - private val userInfoRequest: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun authorizeRequest(): Optional = - Optional.ofNullable(authorizeRequest.getNullable("authorize_request")) - - fun clientId(): Optional = Optional.ofNullable(clientId.getNullable("client_id")) - - fun clientSecret(): Optional = - Optional.ofNullable(clientSecret.getNullable("client_secret")) - - fun pkce(): Optional = Optional.ofNullable(pkce.getNullable("pkce")) - - fun refreshRequest(): Optional = - Optional.ofNullable(refreshRequest.getNullable("refresh_request")) - - fun scopeDelimiter(): Optional = - Optional.ofNullable(scopeDelimiter.getNullable("scope_delimiter")) - - fun tokenRequest(): Optional = - Optional.ofNullable(tokenRequest.getNullable("token_request")) - - fun userInfoRequest(): Optional = - Optional.ofNullable(userInfoRequest.getNullable("user_info_request")) - - @JsonProperty("authorize_request") - @ExcludeMissing - fun _authorizeRequest(): JsonField = authorizeRequest - - @JsonProperty("client_id") @ExcludeMissing fun _clientId(): JsonField = clientId - - @JsonProperty("client_secret") - @ExcludeMissing - fun _clientSecret(): JsonField = clientSecret - - @JsonProperty("pkce") @ExcludeMissing fun _pkce(): JsonField = pkce - - @JsonProperty("refresh_request") - @ExcludeMissing - fun _refreshRequest(): JsonField = refreshRequest - - @JsonProperty("scope_delimiter") - @ExcludeMissing - fun _scopeDelimiter(): JsonField = scopeDelimiter - - @JsonProperty("token_request") - @ExcludeMissing - fun _tokenRequest(): JsonField = tokenRequest - - @JsonProperty("user_info_request") - @ExcludeMissing - fun _userInfoRequest(): JsonField = userInfoRequest - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Oauth2 = apply { - if (validated) { - return@apply - } - - authorizeRequest().ifPresent { it.validate() } - clientId() - clientSecret() - pkce().ifPresent { it.validate() } - refreshRequest().ifPresent { it.validate() } - scopeDelimiter() - tokenRequest().ifPresent { it.validate() } - userInfoRequest().ifPresent { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Oauth2]. */ - class Builder internal constructor() { - - private var authorizeRequest: JsonField = JsonMissing.of() - private var clientId: JsonField = JsonMissing.of() - private var clientSecret: JsonField = JsonMissing.of() - private var pkce: JsonField = JsonMissing.of() - private var refreshRequest: JsonField = JsonMissing.of() - private var scopeDelimiter: JsonField = JsonMissing.of() - private var tokenRequest: JsonField = JsonMissing.of() - private var userInfoRequest: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(oauth2: Oauth2) = apply { - authorizeRequest = oauth2.authorizeRequest - clientId = oauth2.clientId - clientSecret = oauth2.clientSecret - pkce = oauth2.pkce - refreshRequest = oauth2.refreshRequest - scopeDelimiter = oauth2.scopeDelimiter - tokenRequest = oauth2.tokenRequest - userInfoRequest = oauth2.userInfoRequest - additionalProperties = oauth2.additionalProperties.toMutableMap() - } - - fun authorizeRequest(authorizeRequest: AuthorizeRequest) = - authorizeRequest(JsonField.of(authorizeRequest)) - - fun authorizeRequest(authorizeRequest: JsonField) = apply { - this.authorizeRequest = authorizeRequest - } - - fun clientId(clientId: String) = clientId(JsonField.of(clientId)) - - fun clientId(clientId: JsonField) = apply { this.clientId = clientId } - - fun clientSecret(clientSecret: String) = clientSecret(JsonField.of(clientSecret)) - - fun clientSecret(clientSecret: JsonField) = apply { - this.clientSecret = clientSecret - } - - fun pkce(pkce: Pkce) = pkce(JsonField.of(pkce)) - - fun pkce(pkce: JsonField) = apply { this.pkce = pkce } - - fun refreshRequest(refreshRequest: RefreshRequest) = - refreshRequest(JsonField.of(refreshRequest)) - - fun refreshRequest(refreshRequest: JsonField) = apply { - this.refreshRequest = refreshRequest - } - - fun scopeDelimiter(scopeDelimiter: ScopeDelimiter) = - scopeDelimiter(JsonField.of(scopeDelimiter)) - - fun scopeDelimiter(scopeDelimiter: JsonField) = apply { - this.scopeDelimiter = scopeDelimiter - } - - fun tokenRequest(tokenRequest: TokenRequest) = tokenRequest(JsonField.of(tokenRequest)) - - fun tokenRequest(tokenRequest: JsonField) = apply { - this.tokenRequest = tokenRequest - } - - fun userInfoRequest(userInfoRequest: UserInfoRequest) = - userInfoRequest(JsonField.of(userInfoRequest)) - - fun userInfoRequest(userInfoRequest: JsonField) = apply { - this.userInfoRequest = userInfoRequest - } - - 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) - } - - fun build(): Oauth2 = - Oauth2( - authorizeRequest, - clientId, - clientSecret, - pkce, - refreshRequest, - scopeDelimiter, - tokenRequest, - userInfoRequest, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class AuthorizeRequest - @JsonCreator - private constructor( - @JsonProperty("auth_header_value_format") - @ExcludeMissing - private val authHeaderValueFormat: JsonField = JsonMissing.of(), - @JsonProperty("auth_method") - @ExcludeMissing - private val authMethod: JsonField = JsonMissing.of(), - @JsonProperty("endpoint") - @ExcludeMissing - private val endpoint: JsonField = JsonMissing.of(), - @JsonProperty("method") - @ExcludeMissing - private val method: JsonField = JsonMissing.of(), - @JsonProperty("params") - @ExcludeMissing - private val params: JsonField = JsonMissing.of(), - @JsonProperty("request_content_type") - @ExcludeMissing - private val requestContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_content_type") - @ExcludeMissing - private val responseContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_map") - @ExcludeMissing - private val responseMap: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun authHeaderValueFormat(): Optional = - Optional.ofNullable(authHeaderValueFormat.getNullable("auth_header_value_format")) - - fun authMethod(): Optional = - Optional.ofNullable(authMethod.getNullable("auth_method")) - - fun endpoint(): Optional = Optional.ofNullable(endpoint.getNullable("endpoint")) - - fun method(): Optional = Optional.ofNullable(method.getNullable("method")) - - fun params(): Optional = Optional.ofNullable(params.getNullable("params")) - - fun requestContentType(): Optional = - Optional.ofNullable(requestContentType.getNullable("request_content_type")) - - fun responseContentType(): Optional = - Optional.ofNullable(responseContentType.getNullable("response_content_type")) - - fun responseMap(): Optional = - Optional.ofNullable(responseMap.getNullable("response_map")) - - @JsonProperty("auth_header_value_format") - @ExcludeMissing - fun _authHeaderValueFormat(): JsonField = authHeaderValueFormat - - @JsonProperty("auth_method") - @ExcludeMissing - fun _authMethod(): JsonField = authMethod - - @JsonProperty("endpoint") @ExcludeMissing fun _endpoint(): JsonField = endpoint - - @JsonProperty("method") @ExcludeMissing fun _method(): JsonField = method - - @JsonProperty("params") @ExcludeMissing fun _params(): JsonField = params - - @JsonProperty("request_content_type") - @ExcludeMissing - fun _requestContentType(): JsonField = requestContentType - - @JsonProperty("response_content_type") - @ExcludeMissing - fun _responseContentType(): JsonField = responseContentType - - @JsonProperty("response_map") - @ExcludeMissing - fun _responseMap(): JsonField = responseMap - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): AuthorizeRequest = apply { - if (validated) { - return@apply - } - - authHeaderValueFormat() - authMethod() - endpoint() - method() - params().ifPresent { it.validate() } - requestContentType() - responseContentType() - responseMap().ifPresent { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [AuthorizeRequest]. */ - class Builder internal constructor() { - - private var authHeaderValueFormat: JsonField = JsonMissing.of() - private var authMethod: JsonField = JsonMissing.of() - private var endpoint: JsonField = JsonMissing.of() - private var method: JsonField = JsonMissing.of() - private var params: JsonField = JsonMissing.of() - private var requestContentType: JsonField = JsonMissing.of() - private var responseContentType: JsonField = JsonMissing.of() - private var responseMap: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(authorizeRequest: AuthorizeRequest) = apply { - authHeaderValueFormat = authorizeRequest.authHeaderValueFormat - authMethod = authorizeRequest.authMethod - endpoint = authorizeRequest.endpoint - method = authorizeRequest.method - params = authorizeRequest.params - requestContentType = authorizeRequest.requestContentType - responseContentType = authorizeRequest.responseContentType - responseMap = authorizeRequest.responseMap - additionalProperties = authorizeRequest.additionalProperties.toMutableMap() - } - - fun authHeaderValueFormat(authHeaderValueFormat: String) = - authHeaderValueFormat(JsonField.of(authHeaderValueFormat)) - - fun authHeaderValueFormat(authHeaderValueFormat: JsonField) = apply { - this.authHeaderValueFormat = authHeaderValueFormat - } - - fun authMethod(authMethod: String) = authMethod(JsonField.of(authMethod)) - - fun authMethod(authMethod: JsonField) = apply { - this.authMethod = authMethod - } - - fun endpoint(endpoint: String) = endpoint(JsonField.of(endpoint)) - - fun endpoint(endpoint: JsonField) = apply { this.endpoint = endpoint } - - fun method(method: String) = method(JsonField.of(method)) - - fun method(method: JsonField) = apply { this.method = method } - - fun params(params: Params) = params(JsonField.of(params)) - - fun params(params: JsonField) = apply { this.params = params } - - fun requestContentType(requestContentType: RequestContentType) = - requestContentType(JsonField.of(requestContentType)) - - fun requestContentType(requestContentType: JsonField) = apply { - this.requestContentType = requestContentType - } - - fun responseContentType(responseContentType: ResponseContentType) = - responseContentType(JsonField.of(responseContentType)) - - fun responseContentType(responseContentType: JsonField) = - apply { - this.responseContentType = responseContentType - } - - fun responseMap(responseMap: ResponseMap) = responseMap(JsonField.of(responseMap)) - - fun responseMap(responseMap: JsonField) = apply { - this.responseMap = responseMap - } - - 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) - } - - fun build(): AuthorizeRequest = - AuthorizeRequest( - authHeaderValueFormat, - authMethod, - endpoint, - method, - params, - requestContentType, - responseContentType, - responseMap, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class Params - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Params = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Params]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(params: Params) = apply { - additionalProperties = params.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) - } - - fun build(): Params = Params(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Params && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "Params{additionalProperties=$additionalProperties}" - } - - class RequestContentType - @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 APPLICATION_X_WWW_FORM_URLENCODED = of("application/x-www-form-urlencoded") - - @JvmField val APPLICATION_JSON = of("application/json") - - @JvmStatic fun of(value: String) = RequestContentType(JsonField.of(value)) - } - - /** An enum containing [RequestContentType]'s known values. */ - enum class Known { - APPLICATION_X_WWW_FORM_URLENCODED, - APPLICATION_JSON, - } - - /** - * An enum containing [RequestContentType]'s known values, as well as an [_UNKNOWN] - * member. - * - * An instance of [RequestContentType] 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 { - APPLICATION_X_WWW_FORM_URLENCODED, - APPLICATION_JSON, - /** - * An enum member indicating that [RequestContentType] 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) { - APPLICATION_X_WWW_FORM_URLENCODED -> Value.APPLICATION_X_WWW_FORM_URLENCODED - APPLICATION_JSON -> Value.APPLICATION_JSON - 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 ArcadeInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - APPLICATION_X_WWW_FORM_URLENCODED -> Known.APPLICATION_X_WWW_FORM_URLENCODED - APPLICATION_JSON -> Known.APPLICATION_JSON - else -> - throw ArcadeInvalidDataException("Unknown RequestContentType: $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 ArcadeInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - ArcadeInvalidDataException("Value is not a String") - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is RequestContentType && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - class ResponseContentType - @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 APPLICATION_X_WWW_FORM_URLENCODED = of("application/x-www-form-urlencoded") - - @JvmField val APPLICATION_JSON = of("application/json") - - @JvmStatic fun of(value: String) = ResponseContentType(JsonField.of(value)) - } - - /** An enum containing [ResponseContentType]'s known values. */ - enum class Known { - APPLICATION_X_WWW_FORM_URLENCODED, - APPLICATION_JSON, - } - - /** - * An enum containing [ResponseContentType]'s known values, as well as an [_UNKNOWN] - * member. - * - * An instance of [ResponseContentType] 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 { - APPLICATION_X_WWW_FORM_URLENCODED, - APPLICATION_JSON, - /** - * An enum member indicating that [ResponseContentType] 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) { - APPLICATION_X_WWW_FORM_URLENCODED -> Value.APPLICATION_X_WWW_FORM_URLENCODED - APPLICATION_JSON -> Value.APPLICATION_JSON - 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 ArcadeInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - APPLICATION_X_WWW_FORM_URLENCODED -> Known.APPLICATION_X_WWW_FORM_URLENCODED - APPLICATION_JSON -> Known.APPLICATION_JSON - else -> - throw ArcadeInvalidDataException("Unknown ResponseContentType: $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 ArcadeInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - ArcadeInvalidDataException("Value is not a String") - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ResponseContentType && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - @NoAutoDetect - class ResponseMap - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ResponseMap = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ResponseMap]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(responseMap: ResponseMap) = apply { - additionalProperties = responseMap.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) - } - - fun build(): ResponseMap = ResponseMap(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ResponseMap && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "ResponseMap{additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is AuthorizeRequest && authHeaderValueFormat == other.authHeaderValueFormat && authMethod == other.authMethod && endpoint == other.endpoint && method == other.method && params == other.params && requestContentType == other.requestContentType && responseContentType == other.responseContentType && responseMap == other.responseMap && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(authHeaderValueFormat, authMethod, endpoint, method, params, requestContentType, responseContentType, responseMap, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "AuthorizeRequest{authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, endpoint=$endpoint, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class Pkce - @JsonCreator - private constructor( - @JsonProperty("code_challenge_method") - @ExcludeMissing - private val codeChallengeMethod: JsonField = JsonMissing.of(), - @JsonProperty("enabled") - @ExcludeMissing - private val enabled: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun codeChallengeMethod(): Optional = - Optional.ofNullable(codeChallengeMethod.getNullable("code_challenge_method")) - - fun enabled(): Optional = Optional.ofNullable(enabled.getNullable("enabled")) - - @JsonProperty("code_challenge_method") - @ExcludeMissing - fun _codeChallengeMethod(): JsonField = codeChallengeMethod - - @JsonProperty("enabled") @ExcludeMissing fun _enabled(): JsonField = enabled - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Pkce = apply { - if (validated) { - return@apply - } - - codeChallengeMethod() - enabled() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Pkce]. */ - class Builder internal constructor() { - - private var codeChallengeMethod: JsonField = JsonMissing.of() - private var enabled: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(pkce: Pkce) = apply { - codeChallengeMethod = pkce.codeChallengeMethod - enabled = pkce.enabled - additionalProperties = pkce.additionalProperties.toMutableMap() - } - - fun codeChallengeMethod(codeChallengeMethod: String) = - codeChallengeMethod(JsonField.of(codeChallengeMethod)) - - fun codeChallengeMethod(codeChallengeMethod: JsonField) = apply { - this.codeChallengeMethod = codeChallengeMethod - } - - fun enabled(enabled: Boolean) = enabled(JsonField.of(enabled)) - - fun enabled(enabled: JsonField) = apply { this.enabled = enabled } - - 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) - } - - fun build(): Pkce = - Pkce(codeChallengeMethod, enabled, additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Pkce && codeChallengeMethod == other.codeChallengeMethod && enabled == other.enabled && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(codeChallengeMethod, enabled, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Pkce{codeChallengeMethod=$codeChallengeMethod, enabled=$enabled, additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class RefreshRequest - @JsonCreator - private constructor( - @JsonProperty("auth_header_value_format") - @ExcludeMissing - private val authHeaderValueFormat: JsonField = JsonMissing.of(), - @JsonProperty("auth_method") - @ExcludeMissing - private val authMethod: JsonField = JsonMissing.of(), - @JsonProperty("endpoint") - @ExcludeMissing - private val endpoint: JsonField = JsonMissing.of(), - @JsonProperty("method") - @ExcludeMissing - private val method: JsonField = JsonMissing.of(), - @JsonProperty("params") - @ExcludeMissing - private val params: JsonField = JsonMissing.of(), - @JsonProperty("request_content_type") - @ExcludeMissing - private val requestContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_content_type") - @ExcludeMissing - private val responseContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_map") - @ExcludeMissing - private val responseMap: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun authHeaderValueFormat(): Optional = - Optional.ofNullable(authHeaderValueFormat.getNullable("auth_header_value_format")) - - fun authMethod(): Optional = - Optional.ofNullable(authMethod.getNullable("auth_method")) - - fun endpoint(): Optional = Optional.ofNullable(endpoint.getNullable("endpoint")) - - fun method(): Optional = Optional.ofNullable(method.getNullable("method")) - - fun params(): Optional = Optional.ofNullable(params.getNullable("params")) - - fun requestContentType(): Optional = - Optional.ofNullable(requestContentType.getNullable("request_content_type")) - - fun responseContentType(): Optional = - Optional.ofNullable(responseContentType.getNullable("response_content_type")) - - fun responseMap(): Optional = - Optional.ofNullable(responseMap.getNullable("response_map")) - - @JsonProperty("auth_header_value_format") - @ExcludeMissing - fun _authHeaderValueFormat(): JsonField = authHeaderValueFormat - - @JsonProperty("auth_method") - @ExcludeMissing - fun _authMethod(): JsonField = authMethod - - @JsonProperty("endpoint") @ExcludeMissing fun _endpoint(): JsonField = endpoint - - @JsonProperty("method") @ExcludeMissing fun _method(): JsonField = method - - @JsonProperty("params") @ExcludeMissing fun _params(): JsonField = params - - @JsonProperty("request_content_type") - @ExcludeMissing - fun _requestContentType(): JsonField = requestContentType - - @JsonProperty("response_content_type") - @ExcludeMissing - fun _responseContentType(): JsonField = responseContentType - - @JsonProperty("response_map") - @ExcludeMissing - fun _responseMap(): JsonField = responseMap - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): RefreshRequest = apply { - if (validated) { - return@apply - } - - authHeaderValueFormat() - authMethod() - endpoint() - method() - params().ifPresent { it.validate() } - requestContentType() - responseContentType() - responseMap().ifPresent { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [RefreshRequest]. */ - class Builder internal constructor() { - - private var authHeaderValueFormat: JsonField = JsonMissing.of() - private var authMethod: JsonField = JsonMissing.of() - private var endpoint: JsonField = JsonMissing.of() - private var method: JsonField = JsonMissing.of() - private var params: JsonField = JsonMissing.of() - private var requestContentType: JsonField = JsonMissing.of() - private var responseContentType: JsonField = JsonMissing.of() - private var responseMap: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(refreshRequest: RefreshRequest) = apply { - authHeaderValueFormat = refreshRequest.authHeaderValueFormat - authMethod = refreshRequest.authMethod - endpoint = refreshRequest.endpoint - method = refreshRequest.method - params = refreshRequest.params - requestContentType = refreshRequest.requestContentType - responseContentType = refreshRequest.responseContentType - responseMap = refreshRequest.responseMap - additionalProperties = refreshRequest.additionalProperties.toMutableMap() - } - - fun authHeaderValueFormat(authHeaderValueFormat: String) = - authHeaderValueFormat(JsonField.of(authHeaderValueFormat)) - - fun authHeaderValueFormat(authHeaderValueFormat: JsonField) = apply { - this.authHeaderValueFormat = authHeaderValueFormat - } - - fun authMethod(authMethod: String) = authMethod(JsonField.of(authMethod)) - - fun authMethod(authMethod: JsonField) = apply { - this.authMethod = authMethod - } - - fun endpoint(endpoint: String) = endpoint(JsonField.of(endpoint)) - - fun endpoint(endpoint: JsonField) = apply { this.endpoint = endpoint } - - fun method(method: String) = method(JsonField.of(method)) - - fun method(method: JsonField) = apply { this.method = method } - - fun params(params: Params) = params(JsonField.of(params)) - - fun params(params: JsonField) = apply { this.params = params } - - fun requestContentType(requestContentType: RequestContentType) = - requestContentType(JsonField.of(requestContentType)) - - fun requestContentType(requestContentType: JsonField) = apply { - this.requestContentType = requestContentType - } - - fun responseContentType(responseContentType: ResponseContentType) = - responseContentType(JsonField.of(responseContentType)) - - fun responseContentType(responseContentType: JsonField) = - apply { - this.responseContentType = responseContentType - } - - fun responseMap(responseMap: ResponseMap) = responseMap(JsonField.of(responseMap)) - - fun responseMap(responseMap: JsonField) = apply { - this.responseMap = responseMap - } - - 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) - } - - fun build(): RefreshRequest = - RefreshRequest( - authHeaderValueFormat, - authMethod, - endpoint, - method, - params, - requestContentType, - responseContentType, - responseMap, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class Params - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Params = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Params]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(params: Params) = apply { - additionalProperties = params.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) - } - - fun build(): Params = Params(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Params && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "Params{additionalProperties=$additionalProperties}" - } - - class RequestContentType - @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 APPLICATION_X_WWW_FORM_URLENCODED = of("application/x-www-form-urlencoded") - - @JvmField val APPLICATION_JSON = of("application/json") - - @JvmStatic fun of(value: String) = RequestContentType(JsonField.of(value)) - } - - /** An enum containing [RequestContentType]'s known values. */ - enum class Known { - APPLICATION_X_WWW_FORM_URLENCODED, - APPLICATION_JSON, - } - - /** - * An enum containing [RequestContentType]'s known values, as well as an [_UNKNOWN] - * member. - * - * An instance of [RequestContentType] 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 { - APPLICATION_X_WWW_FORM_URLENCODED, - APPLICATION_JSON, - /** - * An enum member indicating that [RequestContentType] 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) { - APPLICATION_X_WWW_FORM_URLENCODED -> Value.APPLICATION_X_WWW_FORM_URLENCODED - APPLICATION_JSON -> Value.APPLICATION_JSON - 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 ArcadeInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - APPLICATION_X_WWW_FORM_URLENCODED -> Known.APPLICATION_X_WWW_FORM_URLENCODED - APPLICATION_JSON -> Known.APPLICATION_JSON - else -> - throw ArcadeInvalidDataException("Unknown RequestContentType: $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 ArcadeInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - ArcadeInvalidDataException("Value is not a String") - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is RequestContentType && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - class ResponseContentType - @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 APPLICATION_X_WWW_FORM_URLENCODED = of("application/x-www-form-urlencoded") - - @JvmField val APPLICATION_JSON = of("application/json") - - @JvmStatic fun of(value: String) = ResponseContentType(JsonField.of(value)) - } - - /** An enum containing [ResponseContentType]'s known values. */ - enum class Known { - APPLICATION_X_WWW_FORM_URLENCODED, - APPLICATION_JSON, - } - - /** - * An enum containing [ResponseContentType]'s known values, as well as an [_UNKNOWN] - * member. - * - * An instance of [ResponseContentType] 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 { - APPLICATION_X_WWW_FORM_URLENCODED, - APPLICATION_JSON, - /** - * An enum member indicating that [ResponseContentType] 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) { - APPLICATION_X_WWW_FORM_URLENCODED -> Value.APPLICATION_X_WWW_FORM_URLENCODED - APPLICATION_JSON -> Value.APPLICATION_JSON - 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 ArcadeInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - APPLICATION_X_WWW_FORM_URLENCODED -> Known.APPLICATION_X_WWW_FORM_URLENCODED - APPLICATION_JSON -> Known.APPLICATION_JSON - else -> - throw ArcadeInvalidDataException("Unknown ResponseContentType: $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 ArcadeInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - ArcadeInvalidDataException("Value is not a String") - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ResponseContentType && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - @NoAutoDetect - class ResponseMap - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ResponseMap = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ResponseMap]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(responseMap: ResponseMap) = apply { - additionalProperties = responseMap.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) - } - - fun build(): ResponseMap = ResponseMap(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ResponseMap && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "ResponseMap{additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is RefreshRequest && authHeaderValueFormat == other.authHeaderValueFormat && authMethod == other.authMethod && endpoint == other.endpoint && method == other.method && params == other.params && requestContentType == other.requestContentType && responseContentType == other.responseContentType && responseMap == other.responseMap && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(authHeaderValueFormat, authMethod, endpoint, method, params, requestContentType, responseContentType, responseMap, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "RefreshRequest{authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, endpoint=$endpoint, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, additionalProperties=$additionalProperties}" - } - - class ScopeDelimiter - @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 Unknown1 = of(",") - - @JvmField val Unknown3 = of(" ") - - @JvmStatic fun of(value: String) = ScopeDelimiter(JsonField.of(value)) - } - - /** An enum containing [ScopeDelimiter]'s known values. */ - enum class Known { - Unknown1, - Unknown3, - } - - /** - * An enum containing [ScopeDelimiter]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [ScopeDelimiter] 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 { - Unknown1, - Unknown3, - /** - * An enum member indicating that [ScopeDelimiter] 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) { - Unknown1 -> Value.Unknown1 - Unknown3 -> Value.Unknown3 - 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 ArcadeInvalidDataException if this class instance's value is a not a known - * member. - */ - fun known(): Known = - when (this) { - Unknown1 -> Known.Unknown1 - Unknown3 -> Known.Unknown3 - else -> throw ArcadeInvalidDataException("Unknown ScopeDelimiter: $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 ArcadeInvalidDataException if this class instance's value does not have the - * expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - ArcadeInvalidDataException("Value is not a String") - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ScopeDelimiter && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - @NoAutoDetect - class TokenRequest - @JsonCreator - private constructor( - @JsonProperty("auth_header_value_format") - @ExcludeMissing - private val authHeaderValueFormat: JsonField = JsonMissing.of(), - @JsonProperty("auth_method") - @ExcludeMissing - private val authMethod: JsonField = JsonMissing.of(), - @JsonProperty("endpoint") - @ExcludeMissing - private val endpoint: JsonField = JsonMissing.of(), - @JsonProperty("method") - @ExcludeMissing - private val method: JsonField = JsonMissing.of(), - @JsonProperty("params") - @ExcludeMissing - private val params: JsonField = JsonMissing.of(), - @JsonProperty("request_content_type") - @ExcludeMissing - private val requestContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_content_type") - @ExcludeMissing - private val responseContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_map") - @ExcludeMissing - private val responseMap: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun authHeaderValueFormat(): Optional = - Optional.ofNullable(authHeaderValueFormat.getNullable("auth_header_value_format")) - - fun authMethod(): Optional = - Optional.ofNullable(authMethod.getNullable("auth_method")) - - fun endpoint(): Optional = Optional.ofNullable(endpoint.getNullable("endpoint")) - - fun method(): Optional = Optional.ofNullable(method.getNullable("method")) - - fun params(): Optional = Optional.ofNullable(params.getNullable("params")) - - fun requestContentType(): Optional = - Optional.ofNullable(requestContentType.getNullable("request_content_type")) - - fun responseContentType(): Optional = - Optional.ofNullable(responseContentType.getNullable("response_content_type")) - - fun responseMap(): Optional = - Optional.ofNullable(responseMap.getNullable("response_map")) - - @JsonProperty("auth_header_value_format") - @ExcludeMissing - fun _authHeaderValueFormat(): JsonField = authHeaderValueFormat - - @JsonProperty("auth_method") - @ExcludeMissing - fun _authMethod(): JsonField = authMethod - - @JsonProperty("endpoint") @ExcludeMissing fun _endpoint(): JsonField = endpoint - - @JsonProperty("method") @ExcludeMissing fun _method(): JsonField = method - - @JsonProperty("params") @ExcludeMissing fun _params(): JsonField = params - - @JsonProperty("request_content_type") - @ExcludeMissing - fun _requestContentType(): JsonField = requestContentType - - @JsonProperty("response_content_type") - @ExcludeMissing - fun _responseContentType(): JsonField = responseContentType - - @JsonProperty("response_map") - @ExcludeMissing - fun _responseMap(): JsonField = responseMap - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): TokenRequest = apply { - if (validated) { - return@apply - } - - authHeaderValueFormat() - authMethod() - endpoint() - method() - params().ifPresent { it.validate() } - requestContentType() - responseContentType() - responseMap().ifPresent { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [TokenRequest]. */ - class Builder internal constructor() { - - private var authHeaderValueFormat: JsonField = JsonMissing.of() - private var authMethod: JsonField = JsonMissing.of() - private var endpoint: JsonField = JsonMissing.of() - private var method: JsonField = JsonMissing.of() - private var params: JsonField = JsonMissing.of() - private var requestContentType: JsonField = JsonMissing.of() - private var responseContentType: JsonField = JsonMissing.of() - private var responseMap: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(tokenRequest: TokenRequest) = apply { - authHeaderValueFormat = tokenRequest.authHeaderValueFormat - authMethod = tokenRequest.authMethod - endpoint = tokenRequest.endpoint - method = tokenRequest.method - params = tokenRequest.params - requestContentType = tokenRequest.requestContentType - responseContentType = tokenRequest.responseContentType - responseMap = tokenRequest.responseMap - additionalProperties = tokenRequest.additionalProperties.toMutableMap() - } - - fun authHeaderValueFormat(authHeaderValueFormat: String) = - authHeaderValueFormat(JsonField.of(authHeaderValueFormat)) - - fun authHeaderValueFormat(authHeaderValueFormat: JsonField) = apply { - this.authHeaderValueFormat = authHeaderValueFormat - } - - fun authMethod(authMethod: String) = authMethod(JsonField.of(authMethod)) - - fun authMethod(authMethod: JsonField) = apply { - this.authMethod = authMethod - } - - fun endpoint(endpoint: String) = endpoint(JsonField.of(endpoint)) - - fun endpoint(endpoint: JsonField) = apply { this.endpoint = endpoint } - - fun method(method: String) = method(JsonField.of(method)) - - fun method(method: JsonField) = apply { this.method = method } - - fun params(params: Params) = params(JsonField.of(params)) - - fun params(params: JsonField) = apply { this.params = params } - - fun requestContentType(requestContentType: RequestContentType) = - requestContentType(JsonField.of(requestContentType)) - - fun requestContentType(requestContentType: JsonField) = apply { - this.requestContentType = requestContentType - } - - fun responseContentType(responseContentType: ResponseContentType) = - responseContentType(JsonField.of(responseContentType)) - - fun responseContentType(responseContentType: JsonField) = - apply { - this.responseContentType = responseContentType - } - - fun responseMap(responseMap: ResponseMap) = responseMap(JsonField.of(responseMap)) - - fun responseMap(responseMap: JsonField) = apply { - this.responseMap = responseMap - } - - 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) - } - - fun build(): TokenRequest = - TokenRequest( - authHeaderValueFormat, - authMethod, - endpoint, - method, - params, - requestContentType, - responseContentType, - responseMap, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class Params - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Params = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Params]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(params: Params) = apply { - additionalProperties = params.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) - } - - fun build(): Params = Params(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Params && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "Params{additionalProperties=$additionalProperties}" - } - - class RequestContentType - @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 APPLICATION_X_WWW_FORM_URLENCODED = of("application/x-www-form-urlencoded") - - @JvmField val APPLICATION_JSON = of("application/json") - - @JvmStatic fun of(value: String) = RequestContentType(JsonField.of(value)) - } - - /** An enum containing [RequestContentType]'s known values. */ - enum class Known { - APPLICATION_X_WWW_FORM_URLENCODED, - APPLICATION_JSON, - } - - /** - * An enum containing [RequestContentType]'s known values, as well as an [_UNKNOWN] - * member. - * - * An instance of [RequestContentType] 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 { - APPLICATION_X_WWW_FORM_URLENCODED, - APPLICATION_JSON, - /** - * An enum member indicating that [RequestContentType] 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) { - APPLICATION_X_WWW_FORM_URLENCODED -> Value.APPLICATION_X_WWW_FORM_URLENCODED - APPLICATION_JSON -> Value.APPLICATION_JSON - 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 ArcadeInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - APPLICATION_X_WWW_FORM_URLENCODED -> Known.APPLICATION_X_WWW_FORM_URLENCODED - APPLICATION_JSON -> Known.APPLICATION_JSON - else -> - throw ArcadeInvalidDataException("Unknown RequestContentType: $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 ArcadeInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - ArcadeInvalidDataException("Value is not a String") - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is RequestContentType && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - class ResponseContentType - @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 APPLICATION_X_WWW_FORM_URLENCODED = of("application/x-www-form-urlencoded") - - @JvmField val APPLICATION_JSON = of("application/json") - - @JvmStatic fun of(value: String) = ResponseContentType(JsonField.of(value)) - } - - /** An enum containing [ResponseContentType]'s known values. */ - enum class Known { - APPLICATION_X_WWW_FORM_URLENCODED, - APPLICATION_JSON, - } - - /** - * An enum containing [ResponseContentType]'s known values, as well as an [_UNKNOWN] - * member. - * - * An instance of [ResponseContentType] 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 { - APPLICATION_X_WWW_FORM_URLENCODED, - APPLICATION_JSON, - /** - * An enum member indicating that [ResponseContentType] 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) { - APPLICATION_X_WWW_FORM_URLENCODED -> Value.APPLICATION_X_WWW_FORM_URLENCODED - APPLICATION_JSON -> Value.APPLICATION_JSON - 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 ArcadeInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - APPLICATION_X_WWW_FORM_URLENCODED -> Known.APPLICATION_X_WWW_FORM_URLENCODED - APPLICATION_JSON -> Known.APPLICATION_JSON - else -> - throw ArcadeInvalidDataException("Unknown ResponseContentType: $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 ArcadeInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - ArcadeInvalidDataException("Value is not a String") - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ResponseContentType && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - @NoAutoDetect - class ResponseMap - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ResponseMap = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ResponseMap]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(responseMap: ResponseMap) = apply { - additionalProperties = responseMap.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) - } - - fun build(): ResponseMap = ResponseMap(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ResponseMap && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "ResponseMap{additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is TokenRequest && authHeaderValueFormat == other.authHeaderValueFormat && authMethod == other.authMethod && endpoint == other.endpoint && method == other.method && params == other.params && requestContentType == other.requestContentType && responseContentType == other.responseContentType && responseMap == other.responseMap && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(authHeaderValueFormat, authMethod, endpoint, method, params, requestContentType, responseContentType, responseMap, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "TokenRequest{authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, endpoint=$endpoint, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class UserInfoRequest - @JsonCreator - private constructor( - @JsonProperty("auth_header_value_format") - @ExcludeMissing - private val authHeaderValueFormat: JsonField = JsonMissing.of(), - @JsonProperty("auth_method") - @ExcludeMissing - private val authMethod: JsonField = JsonMissing.of(), - @JsonProperty("endpoint") - @ExcludeMissing - private val endpoint: JsonField = JsonMissing.of(), - @JsonProperty("method") - @ExcludeMissing - private val method: JsonField = JsonMissing.of(), - @JsonProperty("params") - @ExcludeMissing - private val params: JsonField = JsonMissing.of(), - @JsonProperty("request_content_type") - @ExcludeMissing - private val requestContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_content_type") - @ExcludeMissing - private val responseContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_map") - @ExcludeMissing - private val responseMap: JsonField = JsonMissing.of(), - @JsonProperty("triggers") - @ExcludeMissing - private val triggers: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun authHeaderValueFormat(): Optional = - Optional.ofNullable(authHeaderValueFormat.getNullable("auth_header_value_format")) - - fun authMethod(): Optional = - Optional.ofNullable(authMethod.getNullable("auth_method")) - - fun endpoint(): Optional = Optional.ofNullable(endpoint.getNullable("endpoint")) - - fun method(): Optional = Optional.ofNullable(method.getNullable("method")) - - fun params(): Optional = Optional.ofNullable(params.getNullable("params")) - - fun requestContentType(): Optional = - Optional.ofNullable(requestContentType.getNullable("request_content_type")) - - fun responseContentType(): Optional = - Optional.ofNullable(responseContentType.getNullable("response_content_type")) - - fun responseMap(): Optional = - Optional.ofNullable(responseMap.getNullable("response_map")) - - fun triggers(): Optional = - Optional.ofNullable(triggers.getNullable("triggers")) - - @JsonProperty("auth_header_value_format") - @ExcludeMissing - fun _authHeaderValueFormat(): JsonField = authHeaderValueFormat - - @JsonProperty("auth_method") - @ExcludeMissing - fun _authMethod(): JsonField = authMethod - - @JsonProperty("endpoint") @ExcludeMissing fun _endpoint(): JsonField = endpoint - - @JsonProperty("method") @ExcludeMissing fun _method(): JsonField = method - - @JsonProperty("params") @ExcludeMissing fun _params(): JsonField = params - - @JsonProperty("request_content_type") - @ExcludeMissing - fun _requestContentType(): JsonField = requestContentType - - @JsonProperty("response_content_type") - @ExcludeMissing - fun _responseContentType(): JsonField = responseContentType - - @JsonProperty("response_map") - @ExcludeMissing - fun _responseMap(): JsonField = responseMap - - @JsonProperty("triggers") - @ExcludeMissing - fun _triggers(): JsonField = triggers - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): UserInfoRequest = apply { - if (validated) { - return@apply - } - - authHeaderValueFormat() - authMethod() - endpoint() - method() - params().ifPresent { it.validate() } - requestContentType() - responseContentType() - responseMap().ifPresent { it.validate() } - triggers().ifPresent { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [UserInfoRequest]. */ - class Builder internal constructor() { - - private var authHeaderValueFormat: JsonField = JsonMissing.of() - private var authMethod: JsonField = JsonMissing.of() - private var endpoint: JsonField = JsonMissing.of() - private var method: JsonField = JsonMissing.of() - private var params: JsonField = JsonMissing.of() - private var requestContentType: JsonField = JsonMissing.of() - private var responseContentType: JsonField = JsonMissing.of() - private var responseMap: JsonField = JsonMissing.of() - private var triggers: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(userInfoRequest: UserInfoRequest) = apply { - authHeaderValueFormat = userInfoRequest.authHeaderValueFormat - authMethod = userInfoRequest.authMethod - endpoint = userInfoRequest.endpoint - method = userInfoRequest.method - params = userInfoRequest.params - requestContentType = userInfoRequest.requestContentType - responseContentType = userInfoRequest.responseContentType - responseMap = userInfoRequest.responseMap - triggers = userInfoRequest.triggers - additionalProperties = userInfoRequest.additionalProperties.toMutableMap() - } - - fun authHeaderValueFormat(authHeaderValueFormat: String) = - authHeaderValueFormat(JsonField.of(authHeaderValueFormat)) - - fun authHeaderValueFormat(authHeaderValueFormat: JsonField) = apply { - this.authHeaderValueFormat = authHeaderValueFormat - } - - fun authMethod(authMethod: String) = authMethod(JsonField.of(authMethod)) - - fun authMethod(authMethod: JsonField) = apply { - this.authMethod = authMethod - } - - fun endpoint(endpoint: String) = endpoint(JsonField.of(endpoint)) - - fun endpoint(endpoint: JsonField) = apply { this.endpoint = endpoint } - - fun method(method: String) = method(JsonField.of(method)) - - fun method(method: JsonField) = apply { this.method = method } - - fun params(params: Params) = params(JsonField.of(params)) - - fun params(params: JsonField) = apply { this.params = params } - - fun requestContentType(requestContentType: RequestContentType) = - requestContentType(JsonField.of(requestContentType)) - - fun requestContentType(requestContentType: JsonField) = apply { - this.requestContentType = requestContentType - } - - fun responseContentType(responseContentType: ResponseContentType) = - responseContentType(JsonField.of(responseContentType)) - - fun responseContentType(responseContentType: JsonField) = - apply { - this.responseContentType = responseContentType - } - - fun responseMap(responseMap: ResponseMap) = responseMap(JsonField.of(responseMap)) - - fun responseMap(responseMap: JsonField) = apply { - this.responseMap = responseMap - } - - fun triggers(triggers: Triggers) = triggers(JsonField.of(triggers)) - - fun triggers(triggers: JsonField) = apply { this.triggers = triggers } - - 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) - } - - fun build(): UserInfoRequest = - UserInfoRequest( - authHeaderValueFormat, - authMethod, - endpoint, - method, - params, - requestContentType, - responseContentType, - responseMap, - triggers, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class Params - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Params = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Params]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(params: Params) = apply { - additionalProperties = params.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) - } - - fun build(): Params = Params(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Params && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "Params{additionalProperties=$additionalProperties}" - } - - class RequestContentType - @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 APPLICATION_X_WWW_FORM_URLENCODED = of("application/x-www-form-urlencoded") - - @JvmField val APPLICATION_JSON = of("application/json") - - @JvmStatic fun of(value: String) = RequestContentType(JsonField.of(value)) - } - - /** An enum containing [RequestContentType]'s known values. */ - enum class Known { - APPLICATION_X_WWW_FORM_URLENCODED, - APPLICATION_JSON, - } - - /** - * An enum containing [RequestContentType]'s known values, as well as an [_UNKNOWN] - * member. - * - * An instance of [RequestContentType] 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 { - APPLICATION_X_WWW_FORM_URLENCODED, - APPLICATION_JSON, - /** - * An enum member indicating that [RequestContentType] 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) { - APPLICATION_X_WWW_FORM_URLENCODED -> Value.APPLICATION_X_WWW_FORM_URLENCODED - APPLICATION_JSON -> Value.APPLICATION_JSON - 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 ArcadeInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - APPLICATION_X_WWW_FORM_URLENCODED -> Known.APPLICATION_X_WWW_FORM_URLENCODED - APPLICATION_JSON -> Known.APPLICATION_JSON - else -> - throw ArcadeInvalidDataException("Unknown RequestContentType: $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 ArcadeInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - ArcadeInvalidDataException("Value is not a String") - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is RequestContentType && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - class ResponseContentType - @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 APPLICATION_X_WWW_FORM_URLENCODED = of("application/x-www-form-urlencoded") - - @JvmField val APPLICATION_JSON = of("application/json") - - @JvmStatic fun of(value: String) = ResponseContentType(JsonField.of(value)) - } - - /** An enum containing [ResponseContentType]'s known values. */ - enum class Known { - APPLICATION_X_WWW_FORM_URLENCODED, - APPLICATION_JSON, - } - - /** - * An enum containing [ResponseContentType]'s known values, as well as an [_UNKNOWN] - * member. - * - * An instance of [ResponseContentType] 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 { - APPLICATION_X_WWW_FORM_URLENCODED, - APPLICATION_JSON, - /** - * An enum member indicating that [ResponseContentType] 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) { - APPLICATION_X_WWW_FORM_URLENCODED -> Value.APPLICATION_X_WWW_FORM_URLENCODED - APPLICATION_JSON -> Value.APPLICATION_JSON - 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 ArcadeInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - APPLICATION_X_WWW_FORM_URLENCODED -> Known.APPLICATION_X_WWW_FORM_URLENCODED - APPLICATION_JSON -> Known.APPLICATION_JSON - else -> - throw ArcadeInvalidDataException("Unknown ResponseContentType: $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 ArcadeInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - ArcadeInvalidDataException("Value is not a String") - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ResponseContentType && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - @NoAutoDetect - class ResponseMap - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ResponseMap = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ResponseMap]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(responseMap: ResponseMap) = apply { - additionalProperties = responseMap.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) - } - - fun build(): ResponseMap = ResponseMap(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ResponseMap && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "ResponseMap{additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class Triggers - @JsonCreator - private constructor( - @JsonProperty("on_token_grant") - @ExcludeMissing - private val onTokenGrant: JsonField = JsonMissing.of(), - @JsonProperty("on_token_refresh") - @ExcludeMissing - private val onTokenRefresh: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun onTokenGrant(): Optional = - Optional.ofNullable(onTokenGrant.getNullable("on_token_grant")) - - fun onTokenRefresh(): Optional = - Optional.ofNullable(onTokenRefresh.getNullable("on_token_refresh")) - - @JsonProperty("on_token_grant") - @ExcludeMissing - fun _onTokenGrant(): JsonField = onTokenGrant - - @JsonProperty("on_token_refresh") - @ExcludeMissing - fun _onTokenRefresh(): JsonField = onTokenRefresh - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Triggers = apply { - if (validated) { - return@apply - } - - onTokenGrant() - onTokenRefresh() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Triggers]. */ - class Builder internal constructor() { - - private var onTokenGrant: JsonField = JsonMissing.of() - private var onTokenRefresh: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(triggers: Triggers) = apply { - onTokenGrant = triggers.onTokenGrant - onTokenRefresh = triggers.onTokenRefresh - additionalProperties = triggers.additionalProperties.toMutableMap() - } - - fun onTokenGrant(onTokenGrant: Boolean) = - onTokenGrant(JsonField.of(onTokenGrant)) - - fun onTokenGrant(onTokenGrant: JsonField) = apply { - this.onTokenGrant = onTokenGrant - } - - fun onTokenRefresh(onTokenRefresh: Boolean) = - onTokenRefresh(JsonField.of(onTokenRefresh)) - - fun onTokenRefresh(onTokenRefresh: JsonField) = apply { - this.onTokenRefresh = onTokenRefresh - } - - 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) - } - - fun build(): Triggers = - Triggers(onTokenGrant, onTokenRefresh, additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Triggers && onTokenGrant == other.onTokenGrant && onTokenRefresh == other.onTokenRefresh && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(onTokenGrant, onTokenRefresh, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Triggers{onTokenGrant=$onTokenGrant, onTokenRefresh=$onTokenRefresh, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is UserInfoRequest && authHeaderValueFormat == other.authHeaderValueFormat && authMethod == other.authMethod && endpoint == other.endpoint && method == other.method && params == other.params && requestContentType == other.requestContentType && responseContentType == other.responseContentType && responseMap == other.responseMap && triggers == other.triggers && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(authHeaderValueFormat, authMethod, endpoint, method, params, requestContentType, responseContentType, responseMap, triggers, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "UserInfoRequest{authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, endpoint=$endpoint, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, triggers=$triggers, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Oauth2 && authorizeRequest == other.authorizeRequest && clientId == other.clientId && clientSecret == other.clientSecret && pkce == other.pkce && refreshRequest == other.refreshRequest && scopeDelimiter == other.scopeDelimiter && tokenRequest == other.tokenRequest && userInfoRequest == other.userInfoRequest && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(authorizeRequest, clientId, clientSecret, pkce, refreshRequest, scopeDelimiter, tokenRequest, userInfoRequest, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Oauth2{authorizeRequest=$authorizeRequest, clientId=$clientId, clientSecret=$clientSecret, pkce=$pkce, refreshRequest=$refreshRequest, scopeDelimiter=$scopeDelimiter, tokenRequest=$tokenRequest, userInfoRequest=$userInfoRequest, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is AuthProviderUpdateRequest && id == other.id && description == other.description && oauth2 == other.oauth2 && providerId == other.providerId && status == other.status && type == other.type && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(id, description, oauth2, providerId, status, type, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "AuthProviderUpdateRequest{id=$id, description=$description, oauth2=$oauth2, providerId=$providerId, status=$status, type=$type, additionalProperties=$additionalProperties}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthRequest.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthRequest.kt deleted file mode 100644 index 6a78abf..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthRequest.kt +++ /dev/null @@ -1,424 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.checkRequired -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import java.util.Objects -import java.util.Optional - -@NoAutoDetect -class AuthRequest -@JsonCreator -private constructor( - @JsonProperty("auth_requirement") - @ExcludeMissing - private val authRequirement: JsonField = JsonMissing.of(), - @JsonProperty("user_id") - @ExcludeMissing - private val userId: JsonField = JsonMissing.of(), - @JsonProperty("next_uri") - @ExcludeMissing - private val nextUri: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), -) { - - fun authRequirement(): AuthRequirement = authRequirement.getRequired("auth_requirement") - - fun userId(): String = userId.getRequired("user_id") - - /** Optional: if provided, the user will be redirected to this URI after authorization */ - fun nextUri(): Optional = Optional.ofNullable(nextUri.getNullable("next_uri")) - - @JsonProperty("auth_requirement") - @ExcludeMissing - fun _authRequirement(): JsonField = authRequirement - - @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId - - /** Optional: if provided, the user will be redirected to this URI after authorization */ - @JsonProperty("next_uri") @ExcludeMissing fun _nextUri(): JsonField = nextUri - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): AuthRequest = apply { - if (validated) { - return@apply - } - - authRequirement().validate() - userId() - nextUri() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [AuthRequest]. */ - class Builder internal constructor() { - - private var authRequirement: JsonField? = null - private var userId: JsonField? = null - private var nextUri: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(authRequest: AuthRequest) = apply { - authRequirement = authRequest.authRequirement - userId = authRequest.userId - nextUri = authRequest.nextUri - additionalProperties = authRequest.additionalProperties.toMutableMap() - } - - fun authRequirement(authRequirement: AuthRequirement) = - authRequirement(JsonField.of(authRequirement)) - - fun authRequirement(authRequirement: JsonField) = apply { - this.authRequirement = authRequirement - } - - fun userId(userId: String) = userId(JsonField.of(userId)) - - fun userId(userId: JsonField) = apply { this.userId = userId } - - /** Optional: if provided, the user will be redirected to this URI after authorization */ - fun nextUri(nextUri: String) = nextUri(JsonField.of(nextUri)) - - /** Optional: if provided, the user will be redirected to this URI after authorization */ - fun nextUri(nextUri: JsonField) = apply { this.nextUri = nextUri } - - 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) - } - - fun build(): AuthRequest = - AuthRequest( - checkRequired("authRequirement", authRequirement), - checkRequired("userId", userId), - nextUri, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class AuthRequirement - @JsonCreator - private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("oauth2") - @ExcludeMissing - private val oauth2: JsonField = JsonMissing.of(), - @JsonProperty("provider_id") - @ExcludeMissing - private val providerId: JsonField = JsonMissing.of(), - @JsonProperty("provider_type") - @ExcludeMissing - private val providerType: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** one of ID or ProviderID must be set */ - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - fun oauth2(): Optional = Optional.ofNullable(oauth2.getNullable("oauth2")) - - /** one of ID or ProviderID must be set */ - fun providerId(): Optional = - Optional.ofNullable(providerId.getNullable("provider_id")) - - fun providerType(): Optional = - Optional.ofNullable(providerType.getNullable("provider_type")) - - /** one of ID or ProviderID must be set */ - @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - - @JsonProperty("oauth2") @ExcludeMissing fun _oauth2(): JsonField = oauth2 - - /** one of ID or ProviderID must be set */ - @JsonProperty("provider_id") - @ExcludeMissing - fun _providerId(): JsonField = providerId - - @JsonProperty("provider_type") - @ExcludeMissing - fun _providerType(): JsonField = providerType - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): AuthRequirement = apply { - if (validated) { - return@apply - } - - id() - oauth2().ifPresent { it.validate() } - providerId() - providerType() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [AuthRequirement]. */ - class Builder internal constructor() { - - private var id: JsonField = JsonMissing.of() - private var oauth2: JsonField = JsonMissing.of() - private var providerId: JsonField = JsonMissing.of() - private var providerType: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(authRequirement: AuthRequirement) = apply { - id = authRequirement.id - oauth2 = authRequirement.oauth2 - providerId = authRequirement.providerId - providerType = authRequirement.providerType - additionalProperties = authRequirement.additionalProperties.toMutableMap() - } - - /** one of ID or ProviderID must be set */ - fun id(id: String) = id(JsonField.of(id)) - - /** one of ID or ProviderID must be set */ - fun id(id: JsonField) = apply { this.id = id } - - fun oauth2(oauth2: Oauth2) = oauth2(JsonField.of(oauth2)) - - fun oauth2(oauth2: JsonField) = apply { this.oauth2 = oauth2 } - - /** one of ID or ProviderID must be set */ - fun providerId(providerId: String) = providerId(JsonField.of(providerId)) - - /** one of ID or ProviderID must be set */ - fun providerId(providerId: JsonField) = apply { this.providerId = providerId } - - fun providerType(providerType: String) = providerType(JsonField.of(providerType)) - - fun providerType(providerType: JsonField) = apply { - this.providerType = providerType - } - - 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) - } - - fun build(): AuthRequirement = - AuthRequirement( - id, - oauth2, - providerId, - providerType, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class Oauth2 - @JsonCreator - private constructor( - @JsonProperty("scopes") - @ExcludeMissing - private val scopes: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun scopes(): Optional> = Optional.ofNullable(scopes.getNullable("scopes")) - - @JsonProperty("scopes") @ExcludeMissing fun _scopes(): JsonField> = scopes - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Oauth2 = apply { - if (validated) { - return@apply - } - - scopes() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Oauth2]. */ - class Builder internal constructor() { - - private var scopes: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(oauth2: Oauth2) = apply { - scopes = oauth2.scopes.map { it.toMutableList() } - additionalProperties = oauth2.additionalProperties.toMutableMap() - } - - fun scopes(scopes: List) = scopes(JsonField.of(scopes)) - - fun scopes(scopes: JsonField>) = apply { - this.scopes = scopes.map { it.toMutableList() } - } - - fun addScope(scope: String) = apply { - scopes = - (scopes ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(scope) - } - } - - 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) - } - - fun build(): Oauth2 = - Oauth2( - (scopes ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Oauth2 && scopes == other.scopes && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(scopes, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Oauth2{scopes=$scopes, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is AuthRequirement && id == other.id && oauth2 == other.oauth2 && providerId == other.providerId && providerType == other.providerType && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(id, oauth2, providerId, providerType, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "AuthRequirement{id=$id, oauth2=$oauth2, providerId=$providerId, providerType=$providerType, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is AuthRequest && authRequirement == other.authRequirement && userId == other.userId && nextUri == other.nextUri && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(authRequirement, userId, nextUri, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "AuthRequest{authRequirement=$authRequirement, userId=$userId, nextUri=$nextUri, additionalProperties=$additionalProperties}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthorizationContext.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthorizationContext.kt index 2293855..6adbac1 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthorizationContext.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthorizationContext.kt @@ -10,51 +10,68 @@ import dev.arcade.core.ExcludeMissing import dev.arcade.core.JsonField import dev.arcade.core.JsonMissing import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class AuthorizationContext -@JsonCreator +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( - @JsonProperty("token") @ExcludeMissing private val token: JsonField = JsonMissing.of(), - @JsonProperty("user_info") - @ExcludeMissing - private val userInfo: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val token: JsonField, + private val userInfo: JsonField, + private val additionalProperties: MutableMap, ) { - fun token(): Optional = Optional.ofNullable(token.getNullable("token")) - - fun userInfo(): Optional = Optional.ofNullable(userInfo.getNullable("user_info")) - + @JsonCreator + private constructor( + @JsonProperty("token") @ExcludeMissing token: JsonField = JsonMissing.of(), + @JsonProperty("user_info") @ExcludeMissing userInfo: JsonField = JsonMissing.of(), + ) : this(token, userInfo, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun token(): Optional = token.getOptional("token") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun userInfo(): Optional = userInfo.getOptional("user_info") + + /** + * Returns the raw JSON value of [token]. + * + * Unlike [token], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("token") @ExcludeMissing fun _token(): JsonField = token + /** + * Returns the raw JSON value of [userInfo]. + * + * Unlike [userInfo], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("user_info") @ExcludeMissing fun _userInfo(): JsonField = userInfo + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): AuthorizationContext = apply { - if (validated) { - return@apply - } - - token() - userInfo().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [AuthorizationContext]. */ @JvmStatic fun builder() = Builder() } @@ -74,10 +91,23 @@ private constructor( fun token(token: String) = token(JsonField.of(token)) + /** + * Sets [Builder.token] to an arbitrary JSON 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: JsonField) = apply { this.token = token } fun userInfo(userInfo: UserInfo) = userInfo(JsonField.of(userInfo)) + /** + * Sets [Builder.userInfo] to an arbitrary JSON value. + * + * You should usually call [Builder.userInfo] with a well-typed [UserInfo] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun userInfo(userInfo: JsonField) = apply { this.userInfo = userInfo } fun additionalProperties(additionalProperties: Map) = apply { @@ -99,36 +129,61 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [AuthorizationContext]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): AuthorizationContext = - AuthorizationContext(token, userInfo, additionalProperties.toImmutable()) + AuthorizationContext(token, userInfo, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): AuthorizationContext = apply { + if (validated) { + return@apply + } + + token() + userInfo().ifPresent { it.validate() } + validated = true } - @NoAutoDetect + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (token.asKnown().isPresent) 1 else 0) + + (userInfo.asKnown().getOrNull()?.validity() ?: 0) + class UserInfo @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): UserInfo = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [UserInfo]. */ @JvmStatic fun builder() = Builder() } @@ -161,20 +216,51 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [UserInfo]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): UserInfo = UserInfo(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): UserInfo = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 /* spotless:off */ other is UserInfo && additionalProperties == other.additionalProperties /* spotless:on */ + return other is UserInfo && additionalProperties == other.additionalProperties } - /* spotless:off */ private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ override fun hashCode(): Int = hashCode @@ -186,12 +272,13 @@ private constructor( return true } - return /* spotless:off */ other is AuthorizationContext && token == other.token && userInfo == other.userInfo && additionalProperties == other.additionalProperties /* spotless:on */ + return other is AuthorizationContext && + token == other.token && + userInfo == other.userInfo && + additionalProperties == other.additionalProperties } - /* spotless:off */ private val hashCode: Int by lazy { Objects.hash(token, userInfo, additionalProperties) } - /* spotless:on */ override fun hashCode(): Int = hashCode diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthorizationResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthorizationResponse.kt index 6583854..0eddad8 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthorizationResponse.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthorizationResponse.kt @@ -11,93 +11,150 @@ import dev.arcade.core.ExcludeMissing import dev.arcade.core.JsonField import dev.arcade.core.JsonMissing import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap +import dev.arcade.core.checkKnown import dev.arcade.core.toImmutable import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class AuthorizationResponse -@JsonCreator +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("context") - @ExcludeMissing - private val context: JsonField = JsonMissing.of(), - @JsonProperty("provider_id") - @ExcludeMissing - private val providerId: JsonField = JsonMissing.of(), - @JsonProperty("scopes") - @ExcludeMissing - private val scopes: JsonField> = JsonMissing.of(), - @JsonProperty("status") - @ExcludeMissing - private val status: JsonField = JsonMissing.of(), - @JsonProperty("url") @ExcludeMissing private val url: JsonField = JsonMissing.of(), - @JsonProperty("user_id") - @ExcludeMissing - private val userId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val context: JsonField, + private val providerId: JsonField, + private val scopes: JsonField>, + private val status: JsonField, + private val url: JsonField, + private val userId: JsonField, + private val additionalProperties: MutableMap, ) { - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - fun context(): Optional = - Optional.ofNullable(context.getNullable("context")) - - fun providerId(): Optional = Optional.ofNullable(providerId.getNullable("provider_id")) - - fun scopes(): Optional> = Optional.ofNullable(scopes.getNullable("scopes")) - - fun status(): Optional = Optional.ofNullable(status.getNullable("status")) - - fun url(): Optional = Optional.ofNullable(url.getNullable("url")) - - fun userId(): Optional = Optional.ofNullable(userId.getNullable("user_id")) - + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("context") + @ExcludeMissing + context: JsonField = JsonMissing.of(), + @JsonProperty("provider_id") + @ExcludeMissing + providerId: JsonField = JsonMissing.of(), + @JsonProperty("scopes") @ExcludeMissing scopes: JsonField> = JsonMissing.of(), + @JsonProperty("status") @ExcludeMissing status: JsonField = JsonMissing.of(), + @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + ) : this(id, context, providerId, scopes, status, url, userId, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun context(): Optional = context.getOptional("context") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun providerId(): Optional = providerId.getOptional("provider_id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun scopes(): Optional> = scopes.getOptional("scopes") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun status(): Optional = status.getOptional("status") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun url(): Optional = url.getOptional("url") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun userId(): Optional = userId.getOptional("user_id") + + /** + * 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 [context]. + * + * Unlike [context], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("context") @ExcludeMissing fun _context(): JsonField = context + /** + * Returns the raw JSON value of [providerId]. + * + * Unlike [providerId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("provider_id") @ExcludeMissing fun _providerId(): JsonField = providerId + /** + * Returns the raw JSON value of [scopes]. + * + * Unlike [scopes], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("scopes") @ExcludeMissing fun _scopes(): JsonField> = scopes + /** + * 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 [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 [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): AuthorizationResponse = apply { - if (validated) { - return@apply - } - - id() - context().ifPresent { it.validate() } - providerId() - scopes() - status() - url() - userId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [AuthorizationResponse]. */ @JvmStatic fun builder() = Builder() } @@ -127,45 +184,89 @@ private constructor( 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 context(context: AuthorizationContext) = context(JsonField.of(context)) + /** + * Sets [Builder.context] to an arbitrary JSON value. + * + * You should usually call [Builder.context] with a well-typed [AuthorizationContext] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun context(context: JsonField) = apply { this.context = context } fun providerId(providerId: String) = providerId(JsonField.of(providerId)) + /** + * Sets [Builder.providerId] to an arbitrary JSON value. + * + * You should usually call [Builder.providerId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun providerId(providerId: JsonField) = apply { this.providerId = providerId } fun scopes(scopes: List) = scopes(JsonField.of(scopes)) + /** + * Sets [Builder.scopes] to an arbitrary JSON value. + * + * You should usually call [Builder.scopes] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun scopes(scopes: JsonField>) = apply { this.scopes = scopes.map { it.toMutableList() } } + /** + * Adds a single [String] to [scopes]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addScope(scope: String) = apply { scopes = - (scopes ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(scope) + (scopes ?: JsonField.of(mutableListOf())).also { + checkKnown("scopes", it).add(scope) } } 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 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 userId(userId: String) = userId(JsonField.of(userId)) + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun userId(userId: JsonField) = apply { this.userId = userId } fun additionalProperties(additionalProperties: Map) = apply { @@ -187,6 +288,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [AuthorizationResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): AuthorizationResponse = AuthorizationResponse( id, @@ -196,10 +302,50 @@ private constructor( status, url, userId, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): AuthorizationResponse = apply { + if (validated) { + return@apply + } + + id() + context().ifPresent { it.validate() } + providerId() + scopes() + status().ifPresent { it.validate() } + url() + userId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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) + + (context.asKnown().getOrNull()?.validity() ?: 0) + + (if (providerId.asKnown().isPresent) 1 else 0) + + (scopes.asKnown().getOrNull()?.size ?: 0) + + (status.asKnown().getOrNull()?.validity() ?: 0) + + (if (url.asKnown().isPresent) 1 else 0) + + (if (userId.asKnown().isPresent) 1 else 0) + class Status @JsonCreator private constructor(private val value: JsonField) : Enum { /** @@ -297,12 +443,39 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { ArcadeInvalidDataException("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: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 /* spotless:off */ other is Status && value == other.value /* spotless:on */ + return other is Status && value == other.value } override fun hashCode() = value.hashCode() @@ -315,12 +488,20 @@ private constructor( return true } - return /* spotless:off */ other is AuthorizationResponse && id == other.id && context == other.context && providerId == other.providerId && scopes == other.scopes && status == other.status && url == other.url && userId == other.userId && additionalProperties == other.additionalProperties /* spotless:on */ + return other is AuthorizationResponse && + id == other.id && + context == other.context && + providerId == other.providerId && + scopes == other.scopes && + status == other.status && + url == other.url && + userId == other.userId && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(id, context, providerId, scopes, status, url, userId, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash(id, context, providerId, scopes, status, url, userId, additionalProperties) + } override fun hashCode(): Int = hashCode diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthorizeToolRequest.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthorizeToolRequest.kt deleted file mode 100644 index e234a7a..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthorizeToolRequest.kt +++ /dev/null @@ -1,174 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.checkRequired -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import java.util.Objects -import java.util.Optional - -@NoAutoDetect -class AuthorizeToolRequest -@JsonCreator -private constructor( - @JsonProperty("tool_name") - @ExcludeMissing - private val toolName: JsonField = JsonMissing.of(), - @JsonProperty("next_uri") - @ExcludeMissing - private val nextUri: JsonField = JsonMissing.of(), - @JsonProperty("tool_version") - @ExcludeMissing - private val toolVersion: JsonField = JsonMissing.of(), - @JsonProperty("user_id") - @ExcludeMissing - private val userId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), -) { - - fun toolName(): String = toolName.getRequired("tool_name") - - /** Optional: if provided, the user will be redirected to this URI after authorization */ - fun nextUri(): Optional = Optional.ofNullable(nextUri.getNullable("next_uri")) - - /** Optional: if not provided, any version is used */ - fun toolVersion(): Optional = - Optional.ofNullable(toolVersion.getNullable("tool_version")) - - /** Required only when calling with an API key */ - fun userId(): Optional = Optional.ofNullable(userId.getNullable("user_id")) - - @JsonProperty("tool_name") @ExcludeMissing fun _toolName(): JsonField = toolName - - /** Optional: if provided, the user will be redirected to this URI after authorization */ - @JsonProperty("next_uri") @ExcludeMissing fun _nextUri(): JsonField = nextUri - - /** Optional: if not provided, any version is used */ - @JsonProperty("tool_version") - @ExcludeMissing - fun _toolVersion(): JsonField = toolVersion - - /** Required only when calling with an API key */ - @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): AuthorizeToolRequest = apply { - if (validated) { - return@apply - } - - toolName() - nextUri() - toolVersion() - userId() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [AuthorizeToolRequest]. */ - class Builder internal constructor() { - - private var toolName: JsonField? = null - private var nextUri: JsonField = JsonMissing.of() - private var toolVersion: JsonField = JsonMissing.of() - private var userId: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(authorizeToolRequest: AuthorizeToolRequest) = apply { - toolName = authorizeToolRequest.toolName - nextUri = authorizeToolRequest.nextUri - toolVersion = authorizeToolRequest.toolVersion - userId = authorizeToolRequest.userId - additionalProperties = authorizeToolRequest.additionalProperties.toMutableMap() - } - - fun toolName(toolName: String) = toolName(JsonField.of(toolName)) - - fun toolName(toolName: JsonField) = apply { this.toolName = toolName } - - /** Optional: if provided, the user will be redirected to this URI after authorization */ - fun nextUri(nextUri: String) = nextUri(JsonField.of(nextUri)) - - /** Optional: if provided, the user will be redirected to this URI after authorization */ - fun nextUri(nextUri: JsonField) = apply { this.nextUri = nextUri } - - /** Optional: if not provided, any version is used */ - fun toolVersion(toolVersion: String) = toolVersion(JsonField.of(toolVersion)) - - /** Optional: if not provided, any version is used */ - fun toolVersion(toolVersion: JsonField) = apply { this.toolVersion = toolVersion } - - /** Required only when calling with an API key */ - fun userId(userId: String) = userId(JsonField.of(userId)) - - /** Required only when calling with an API key */ - fun userId(userId: JsonField) = apply { this.userId = userId } - - 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) - } - - fun build(): AuthorizeToolRequest = - AuthorizeToolRequest( - checkRequired("toolName", toolName), - nextUri, - toolVersion, - userId, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is AuthorizeToolRequest && toolName == other.toolName && nextUri == other.nextUri && toolVersion == other.toolVersion && userId == other.userId && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(toolName, nextUri, toolVersion, userId, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "AuthorizeToolRequest{toolName=$toolName, nextUri=$nextUri, toolVersion=$toolVersion, userId=$userId, additionalProperties=$additionalProperties}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ChatMessage.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/ChatMessage.kt deleted file mode 100644 index 1a46a07..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ChatMessage.kt +++ /dev/null @@ -1,536 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.Enum -import dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.checkRequired -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import dev.arcade.errors.ArcadeInvalidDataException -import java.util.Objects -import java.util.Optional - -@NoAutoDetect -class ChatMessage -@JsonCreator -private constructor( - @JsonProperty("content") - @ExcludeMissing - private val content: JsonField = JsonMissing.of(), - @JsonProperty("role") @ExcludeMissing private val role: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing private val name: JsonField = JsonMissing.of(), - @JsonProperty("tool_call_id") - @ExcludeMissing - private val toolCallId: JsonField = JsonMissing.of(), - @JsonProperty("tool_calls") - @ExcludeMissing - private val toolCalls: JsonField> = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), -) { - - /** The content of the message. */ - fun content(): String = content.getRequired("content") - - /** The role of the author of this message. One of system, user, tool, or assistant. */ - fun role(): String = role.getRequired("role") - - /** tool Name */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) - - /** tool_call_id */ - fun toolCallId(): Optional = Optional.ofNullable(toolCallId.getNullable("tool_call_id")) - - /** tool calls if any */ - fun toolCalls(): Optional> = - Optional.ofNullable(toolCalls.getNullable("tool_calls")) - - /** The content of the message. */ - @JsonProperty("content") @ExcludeMissing fun _content(): JsonField = content - - /** The role of the author of this message. One of system, user, tool, or assistant. */ - @JsonProperty("role") @ExcludeMissing fun _role(): JsonField = role - - /** tool Name */ - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - - /** tool_call_id */ - @JsonProperty("tool_call_id") @ExcludeMissing fun _toolCallId(): JsonField = toolCallId - - /** tool calls if any */ - @JsonProperty("tool_calls") - @ExcludeMissing - fun _toolCalls(): JsonField> = toolCalls - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ChatMessage = apply { - if (validated) { - return@apply - } - - content() - role() - name() - toolCallId() - toolCalls().ifPresent { it.forEach { it.validate() } } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ChatMessage]. */ - class Builder internal constructor() { - - private var content: JsonField? = null - private var role: JsonField? = null - private var name: JsonField = JsonMissing.of() - private var toolCallId: JsonField = JsonMissing.of() - private var toolCalls: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(chatMessage: ChatMessage) = apply { - content = chatMessage.content - role = chatMessage.role - name = chatMessage.name - toolCallId = chatMessage.toolCallId - toolCalls = chatMessage.toolCalls.map { it.toMutableList() } - additionalProperties = chatMessage.additionalProperties.toMutableMap() - } - - /** The content of the message. */ - fun content(content: String) = content(JsonField.of(content)) - - /** The content of the message. */ - fun content(content: JsonField) = apply { this.content = content } - - /** The role of the author of this message. One of system, user, tool, or assistant. */ - fun role(role: String) = role(JsonField.of(role)) - - /** The role of the author of this message. One of system, user, tool, or assistant. */ - fun role(role: JsonField) = apply { this.role = role } - - /** tool Name */ - fun name(name: String) = name(JsonField.of(name)) - - /** tool Name */ - fun name(name: JsonField) = apply { this.name = name } - - /** tool_call_id */ - fun toolCallId(toolCallId: String) = toolCallId(JsonField.of(toolCallId)) - - /** tool_call_id */ - fun toolCallId(toolCallId: JsonField) = apply { this.toolCallId = toolCallId } - - /** tool calls if any */ - fun toolCalls(toolCalls: List) = toolCalls(JsonField.of(toolCalls)) - - /** tool calls if any */ - fun toolCalls(toolCalls: JsonField>) = apply { - this.toolCalls = toolCalls.map { it.toMutableList() } - } - - /** tool calls if any */ - fun addToolCall(toolCall: ToolCall) = apply { - toolCalls = - (toolCalls ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(toolCall) - } - } - - 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) - } - - fun build(): ChatMessage = - ChatMessage( - checkRequired("content", content), - checkRequired("role", role), - name, - toolCallId, - (toolCalls ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class ToolCall - @JsonCreator - private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("function") - @ExcludeMissing - private val function: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - fun function(): Optional = Optional.ofNullable(function.getNullable("function")) - - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - - @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - - @JsonProperty("function") @ExcludeMissing fun _function(): JsonField = function - - @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ToolCall = apply { - if (validated) { - return@apply - } - - id() - function().ifPresent { it.validate() } - type() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ToolCall]. */ - class Builder internal constructor() { - - private var id: JsonField = JsonMissing.of() - private var function: JsonField = JsonMissing.of() - private var type: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(toolCall: ToolCall) = apply { - id = toolCall.id - function = toolCall.function - type = toolCall.type - additionalProperties = toolCall.additionalProperties.toMutableMap() - } - - fun id(id: String) = id(JsonField.of(id)) - - fun id(id: JsonField) = apply { this.id = id } - - fun function(function: Function) = function(JsonField.of(function)) - - fun function(function: JsonField) = apply { this.function = function } - - fun type(type: Type) = type(JsonField.of(type)) - - 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) - } - - fun build(): ToolCall = ToolCall(id, function, type, additionalProperties.toImmutable()) - } - - @NoAutoDetect - class Function - @JsonCreator - private constructor( - @JsonProperty("arguments") - @ExcludeMissing - private val arguments: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun arguments(): Optional = - Optional.ofNullable(arguments.getNullable("arguments")) - - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) - - @JsonProperty("arguments") - @ExcludeMissing - fun _arguments(): JsonField = arguments - - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Function = apply { - if (validated) { - return@apply - } - - arguments() - name() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Function]. */ - class Builder internal constructor() { - - private var arguments: JsonField = JsonMissing.of() - private var name: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(function: Function) = apply { - arguments = function.arguments - name = function.name - additionalProperties = function.additionalProperties.toMutableMap() - } - - fun arguments(arguments: String) = arguments(JsonField.of(arguments)) - - fun arguments(arguments: JsonField) = apply { this.arguments = arguments } - - fun name(name: String) = name(JsonField.of(name)) - - 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) - } - - fun build(): Function = - Function(arguments, name, additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Function && arguments == other.arguments && name == other.name && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(arguments, name, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Function{arguments=$arguments, name=$name, additionalProperties=$additionalProperties}" - } - - 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 FUNCTION = of("function") - - @JvmStatic fun of(value: String) = Type(JsonField.of(value)) - } - - /** An enum containing [Type]'s known values. */ - enum class Known { - FUNCTION - } - - /** - * 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 { - FUNCTION, - /** 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) { - FUNCTION -> Value.FUNCTION - 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 ArcadeInvalidDataException if this class instance's value is a not a known - * member. - */ - fun known(): Known = - when (this) { - FUNCTION -> Known.FUNCTION - else -> throw ArcadeInvalidDataException("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 ArcadeInvalidDataException if this class instance's value does not have the - * expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - ArcadeInvalidDataException("Value is not a String") - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Type && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ToolCall && id == other.id && function == other.function && type == other.type && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(id, function, type, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ToolCall{id=$id, function=$function, type=$type, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ChatMessage && content == other.content && role == other.role && name == other.name && toolCallId == other.toolCallId && toolCalls == other.toolCalls && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(content, role, name, toolCallId, toolCalls, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ChatMessage{content=$content, role=$role, name=$name, toolCallId=$toolCallId, toolCalls=$toolCalls, additionalProperties=$additionalProperties}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ChatRequest.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/ChatRequest.kt deleted file mode 100644 index 208e264..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ChatRequest.kt +++ /dev/null @@ -1,911 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.Enum -import dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import dev.arcade.errors.ArcadeInvalidDataException -import java.util.Objects -import java.util.Optional - -@NoAutoDetect -class ChatRequest -@JsonCreator -private constructor( - @JsonProperty("frequency_penalty") - @ExcludeMissing - private val frequencyPenalty: JsonField = JsonMissing.of(), - @JsonProperty("logit_bias") - @ExcludeMissing - private val logitBias: JsonField = JsonMissing.of(), - @JsonProperty("logprobs") - @ExcludeMissing - private val logprobs: JsonField = JsonMissing.of(), - @JsonProperty("max_tokens") - @ExcludeMissing - private val maxTokens: JsonField = JsonMissing.of(), - @JsonProperty("messages") - @ExcludeMissing - private val messages: JsonField> = JsonMissing.of(), - @JsonProperty("model") @ExcludeMissing private val model: JsonField = JsonMissing.of(), - @JsonProperty("n") @ExcludeMissing private val n: JsonField = JsonMissing.of(), - @JsonProperty("parallel_tool_calls") - @ExcludeMissing - private val parallelToolCalls: JsonField = JsonMissing.of(), - @JsonProperty("presence_penalty") - @ExcludeMissing - private val presencePenalty: JsonField = JsonMissing.of(), - @JsonProperty("response_format") - @ExcludeMissing - private val responseFormat: JsonField = JsonMissing.of(), - @JsonProperty("seed") @ExcludeMissing private val seed: JsonField = JsonMissing.of(), - @JsonProperty("stop") - @ExcludeMissing - private val stop: JsonField> = JsonMissing.of(), - @JsonProperty("stream") - @ExcludeMissing - private val stream: JsonField = JsonMissing.of(), - @JsonProperty("stream_options") - @ExcludeMissing - private val streamOptions: JsonField = JsonMissing.of(), - @JsonProperty("temperature") - @ExcludeMissing - private val temperature: JsonField = JsonMissing.of(), - @JsonProperty("tool_choice") - @ExcludeMissing - private val toolChoice: JsonValue = JsonMissing.of(), - @JsonProperty("tools") @ExcludeMissing private val tools: JsonValue = JsonMissing.of(), - @JsonProperty("top_logprobs") - @ExcludeMissing - private val topLogprobs: JsonField = JsonMissing.of(), - @JsonProperty("top_p") @ExcludeMissing private val topP: JsonField = JsonMissing.of(), - @JsonProperty("user") @ExcludeMissing private val user: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), -) { - - fun frequencyPenalty(): Optional = - Optional.ofNullable(frequencyPenalty.getNullable("frequency_penalty")) - - /** - * LogitBias is must be a token id string (specified by their token ID in the tokenizer), not a - * word string. incorrect: `"logit_bias":{"You": 6}`, correct: `"logit_bias":{"1639": 6}` refs: - * https://platform.openai.com/docs/api-reference/chat/create#chat/create-logit_bias - */ - fun logitBias(): Optional = Optional.ofNullable(logitBias.getNullable("logit_bias")) - - /** - * LogProbs indicates whether to return log probabilities of the output tokens or not. If true, - * returns the log probabilities of each output token returned in the content of message. This - * option is currently not available on the gpt-4-vision-preview model. - */ - fun logprobs(): Optional = Optional.ofNullable(logprobs.getNullable("logprobs")) - - fun maxTokens(): Optional = Optional.ofNullable(maxTokens.getNullable("max_tokens")) - - fun messages(): Optional> = - Optional.ofNullable(messages.getNullable("messages")) - - fun model(): Optional = Optional.ofNullable(model.getNullable("model")) - - fun n(): Optional = Optional.ofNullable(n.getNullable("n")) - - /** Disable the default behavior of parallel tool calls by setting it: false. */ - fun parallelToolCalls(): Optional = - Optional.ofNullable(parallelToolCalls.getNullable("parallel_tool_calls")) - - fun presencePenalty(): Optional = - Optional.ofNullable(presencePenalty.getNullable("presence_penalty")) - - fun responseFormat(): Optional = - Optional.ofNullable(responseFormat.getNullable("response_format")) - - fun seed(): Optional = Optional.ofNullable(seed.getNullable("seed")) - - fun stop(): Optional> = Optional.ofNullable(stop.getNullable("stop")) - - fun stream(): Optional = Optional.ofNullable(stream.getNullable("stream")) - - /** Options for streaming response. Only set this when you set stream: true. */ - fun streamOptions(): Optional = - Optional.ofNullable(streamOptions.getNullable("stream_options")) - - fun temperature(): Optional = - Optional.ofNullable(temperature.getNullable("temperature")) - - /** This can be either a string or an ToolChoice object. */ - @JsonProperty("tool_choice") @ExcludeMissing fun _toolChoice(): JsonValue = toolChoice - - @JsonProperty("tools") @ExcludeMissing fun _tools(): JsonValue = tools - - /** - * TopLogProbs is an integer between 0 and 5 specifying the number of most likely tokens to - * return at each token position, each with an associated log probability. logprobs must be set - * to true if this parameter is used. - */ - fun topLogprobs(): Optional = Optional.ofNullable(topLogprobs.getNullable("top_logprobs")) - - fun topP(): Optional = Optional.ofNullable(topP.getNullable("top_p")) - - fun user(): Optional = Optional.ofNullable(user.getNullable("user")) - - @JsonProperty("frequency_penalty") - @ExcludeMissing - fun _frequencyPenalty(): JsonField = frequencyPenalty - - /** - * LogitBias is must be a token id string (specified by their token ID in the tokenizer), not a - * word string. incorrect: `"logit_bias":{"You": 6}`, correct: `"logit_bias":{"1639": 6}` refs: - * https://platform.openai.com/docs/api-reference/chat/create#chat/create-logit_bias - */ - @JsonProperty("logit_bias") @ExcludeMissing fun _logitBias(): JsonField = logitBias - - /** - * LogProbs indicates whether to return log probabilities of the output tokens or not. If true, - * returns the log probabilities of each output token returned in the content of message. This - * option is currently not available on the gpt-4-vision-preview model. - */ - @JsonProperty("logprobs") @ExcludeMissing fun _logprobs(): JsonField = logprobs - - @JsonProperty("max_tokens") @ExcludeMissing fun _maxTokens(): JsonField = maxTokens - - @JsonProperty("messages") - @ExcludeMissing - fun _messages(): JsonField> = messages - - @JsonProperty("model") @ExcludeMissing fun _model(): JsonField = model - - @JsonProperty("n") @ExcludeMissing fun _n(): JsonField = n - - /** Disable the default behavior of parallel tool calls by setting it: false. */ - @JsonProperty("parallel_tool_calls") - @ExcludeMissing - fun _parallelToolCalls(): JsonField = parallelToolCalls - - @JsonProperty("presence_penalty") - @ExcludeMissing - fun _presencePenalty(): JsonField = presencePenalty - - @JsonProperty("response_format") - @ExcludeMissing - fun _responseFormat(): JsonField = responseFormat - - @JsonProperty("seed") @ExcludeMissing fun _seed(): JsonField = seed - - @JsonProperty("stop") @ExcludeMissing fun _stop(): JsonField> = stop - - @JsonProperty("stream") @ExcludeMissing fun _stream(): JsonField = stream - - /** Options for streaming response. Only set this when you set stream: true. */ - @JsonProperty("stream_options") - @ExcludeMissing - fun _streamOptions(): JsonField = streamOptions - - @JsonProperty("temperature") @ExcludeMissing fun _temperature(): JsonField = temperature - - /** - * TopLogProbs is an integer between 0 and 5 specifying the number of most likely tokens to - * return at each token position, each with an associated log probability. logprobs must be set - * to true if this parameter is used. - */ - @JsonProperty("top_logprobs") @ExcludeMissing fun _topLogprobs(): JsonField = topLogprobs - - @JsonProperty("top_p") @ExcludeMissing fun _topP(): JsonField = topP - - @JsonProperty("user") @ExcludeMissing fun _user(): JsonField = user - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ChatRequest = apply { - if (validated) { - return@apply - } - - frequencyPenalty() - logitBias().ifPresent { it.validate() } - logprobs() - maxTokens() - messages().ifPresent { it.forEach { it.validate() } } - model() - n() - parallelToolCalls() - presencePenalty() - responseFormat().ifPresent { it.validate() } - seed() - stop() - stream() - streamOptions().ifPresent { it.validate() } - temperature() - topLogprobs() - topP() - user() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ChatRequest]. */ - class Builder internal constructor() { - - private var frequencyPenalty: JsonField = JsonMissing.of() - private var logitBias: JsonField = JsonMissing.of() - private var logprobs: JsonField = JsonMissing.of() - private var maxTokens: JsonField = JsonMissing.of() - private var messages: JsonField>? = null - private var model: JsonField = JsonMissing.of() - private var n: JsonField = JsonMissing.of() - private var parallelToolCalls: JsonField = JsonMissing.of() - private var presencePenalty: JsonField = JsonMissing.of() - private var responseFormat: JsonField = JsonMissing.of() - private var seed: JsonField = JsonMissing.of() - private var stop: JsonField>? = null - private var stream: JsonField = JsonMissing.of() - private var streamOptions: JsonField = JsonMissing.of() - private var temperature: JsonField = JsonMissing.of() - private var toolChoice: JsonValue = JsonMissing.of() - private var tools: JsonValue = JsonMissing.of() - private var topLogprobs: JsonField = JsonMissing.of() - private var topP: JsonField = JsonMissing.of() - private var user: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(chatRequest: ChatRequest) = apply { - frequencyPenalty = chatRequest.frequencyPenalty - logitBias = chatRequest.logitBias - logprobs = chatRequest.logprobs - maxTokens = chatRequest.maxTokens - messages = chatRequest.messages.map { it.toMutableList() } - model = chatRequest.model - n = chatRequest.n - parallelToolCalls = chatRequest.parallelToolCalls - presencePenalty = chatRequest.presencePenalty - responseFormat = chatRequest.responseFormat - seed = chatRequest.seed - stop = chatRequest.stop.map { it.toMutableList() } - stream = chatRequest.stream - streamOptions = chatRequest.streamOptions - temperature = chatRequest.temperature - toolChoice = chatRequest.toolChoice - tools = chatRequest.tools - topLogprobs = chatRequest.topLogprobs - topP = chatRequest.topP - user = chatRequest.user - additionalProperties = chatRequest.additionalProperties.toMutableMap() - } - - fun frequencyPenalty(frequencyPenalty: Double) = - frequencyPenalty(JsonField.of(frequencyPenalty)) - - fun frequencyPenalty(frequencyPenalty: JsonField) = apply { - this.frequencyPenalty = frequencyPenalty - } - - /** - * LogitBias is must be a token id string (specified by their token ID in the tokenizer), - * not a word string. incorrect: `"logit_bias":{"You": 6}`, correct: `"logit_bias":{"1639": - * 6}` refs: - * https://platform.openai.com/docs/api-reference/chat/create#chat/create-logit_bias - */ - fun logitBias(logitBias: LogitBias) = logitBias(JsonField.of(logitBias)) - - /** - * LogitBias is must be a token id string (specified by their token ID in the tokenizer), - * not a word string. incorrect: `"logit_bias":{"You": 6}`, correct: `"logit_bias":{"1639": - * 6}` refs: - * https://platform.openai.com/docs/api-reference/chat/create#chat/create-logit_bias - */ - fun logitBias(logitBias: JsonField) = apply { this.logitBias = logitBias } - - /** - * LogProbs indicates whether to return log probabilities of the output tokens or not. If - * true, returns the log probabilities of each output token returned in the content of - * message. This option is currently not available on the gpt-4-vision-preview model. - */ - fun logprobs(logprobs: Boolean) = logprobs(JsonField.of(logprobs)) - - /** - * LogProbs indicates whether to return log probabilities of the output tokens or not. If - * true, returns the log probabilities of each output token returned in the content of - * message. This option is currently not available on the gpt-4-vision-preview model. - */ - fun logprobs(logprobs: JsonField) = apply { this.logprobs = logprobs } - - fun maxTokens(maxTokens: Long) = maxTokens(JsonField.of(maxTokens)) - - fun maxTokens(maxTokens: JsonField) = apply { this.maxTokens = maxTokens } - - fun messages(messages: List) = messages(JsonField.of(messages)) - - fun messages(messages: JsonField>) = apply { - this.messages = messages.map { it.toMutableList() } - } - - fun addMessage(message: ChatMessage) = apply { - messages = - (messages ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(message) - } - } - - fun model(model: String) = model(JsonField.of(model)) - - fun model(model: JsonField) = apply { this.model = model } - - fun n(n: Long) = n(JsonField.of(n)) - - fun n(n: JsonField) = apply { this.n = n } - - /** Disable the default behavior of parallel tool calls by setting it: false. */ - fun parallelToolCalls(parallelToolCalls: Boolean) = - parallelToolCalls(JsonField.of(parallelToolCalls)) - - /** Disable the default behavior of parallel tool calls by setting it: false. */ - fun parallelToolCalls(parallelToolCalls: JsonField) = apply { - this.parallelToolCalls = parallelToolCalls - } - - fun presencePenalty(presencePenalty: Double) = - presencePenalty(JsonField.of(presencePenalty)) - - fun presencePenalty(presencePenalty: JsonField) = apply { - this.presencePenalty = presencePenalty - } - - fun responseFormat(responseFormat: ResponseFormat) = - responseFormat(JsonField.of(responseFormat)) - - fun responseFormat(responseFormat: JsonField) = apply { - this.responseFormat = responseFormat - } - - fun seed(seed: Long) = seed(JsonField.of(seed)) - - fun seed(seed: JsonField) = apply { this.seed = seed } - - fun stop(stop: List) = stop(JsonField.of(stop)) - - fun stop(stop: JsonField>) = apply { - this.stop = stop.map { it.toMutableList() } - } - - fun addStop(stop: String) = apply { - this.stop = - (this.stop ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(stop) - } - } - - fun stream(stream: Boolean) = stream(JsonField.of(stream)) - - fun stream(stream: JsonField) = apply { this.stream = stream } - - /** Options for streaming response. Only set this when you set stream: true. */ - fun streamOptions(streamOptions: StreamOptions) = streamOptions(JsonField.of(streamOptions)) - - /** Options for streaming response. Only set this when you set stream: true. */ - fun streamOptions(streamOptions: JsonField) = apply { - this.streamOptions = streamOptions - } - - fun temperature(temperature: Double) = temperature(JsonField.of(temperature)) - - fun temperature(temperature: JsonField) = apply { this.temperature = temperature } - - /** This can be either a string or an ToolChoice object. */ - fun toolChoice(toolChoice: JsonValue) = apply { this.toolChoice = toolChoice } - - fun tools(tools: JsonValue) = apply { this.tools = tools } - - /** - * TopLogProbs is an integer between 0 and 5 specifying the number of most likely tokens to - * return at each token position, each with an associated log probability. logprobs must be - * set to true if this parameter is used. - */ - fun topLogprobs(topLogprobs: Long) = topLogprobs(JsonField.of(topLogprobs)) - - /** - * TopLogProbs is an integer between 0 and 5 specifying the number of most likely tokens to - * return at each token position, each with an associated log probability. logprobs must be - * set to true if this parameter is used. - */ - fun topLogprobs(topLogprobs: JsonField) = apply { this.topLogprobs = topLogprobs } - - fun topP(topP: Double) = topP(JsonField.of(topP)) - - fun topP(topP: JsonField) = apply { this.topP = topP } - - fun user(user: String) = user(JsonField.of(user)) - - fun user(user: JsonField) = apply { this.user = user } - - 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) - } - - fun build(): ChatRequest = - ChatRequest( - frequencyPenalty, - logitBias, - logprobs, - maxTokens, - (messages ?: JsonMissing.of()).map { it.toImmutable() }, - model, - n, - parallelToolCalls, - presencePenalty, - responseFormat, - seed, - (stop ?: JsonMissing.of()).map { it.toImmutable() }, - stream, - streamOptions, - temperature, - toolChoice, - tools, - topLogprobs, - topP, - user, - additionalProperties.toImmutable(), - ) - } - - /** - * LogitBias is must be a token id string (specified by their token ID in the tokenizer), not a - * word string. incorrect: `"logit_bias":{"You": 6}`, correct: `"logit_bias":{"1639": 6}` refs: - * https://platform.openai.com/docs/api-reference/chat/create#chat/create-logit_bias - */ - @NoAutoDetect - class LogitBias - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): LogitBias = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [LogitBias]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(logitBias: LogitBias) = apply { - additionalProperties = logitBias.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) - } - - fun build(): LogitBias = LogitBias(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is LogitBias && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "LogitBias{additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class ResponseFormat - @JsonCreator - private constructor( - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - - @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ResponseFormat = apply { - if (validated) { - return@apply - } - - type() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ResponseFormat]. */ - class Builder internal constructor() { - - private var type: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(responseFormat: ResponseFormat) = apply { - type = responseFormat.type - additionalProperties = responseFormat.additionalProperties.toMutableMap() - } - - fun type(type: Type) = type(JsonField.of(type)) - - 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) - } - - fun build(): ResponseFormat = ResponseFormat(type, additionalProperties.toImmutable()) - } - - 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 JSON_OBJECT = of("json_object") - - @JvmField val TEXT = of("text") - - @JvmStatic fun of(value: String) = Type(JsonField.of(value)) - } - - /** An enum containing [Type]'s known values. */ - enum class Known { - JSON_OBJECT, - TEXT, - } - - /** - * 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 { - JSON_OBJECT, - TEXT, - /** 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) { - JSON_OBJECT -> Value.JSON_OBJECT - TEXT -> Value.TEXT - 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 ArcadeInvalidDataException if this class instance's value is a not a known - * member. - */ - fun known(): Known = - when (this) { - JSON_OBJECT -> Known.JSON_OBJECT - TEXT -> Known.TEXT - else -> throw ArcadeInvalidDataException("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 ArcadeInvalidDataException if this class instance's value does not have the - * expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - ArcadeInvalidDataException("Value is not a String") - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Type && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ResponseFormat && type == other.type && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(type, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ResponseFormat{type=$type, additionalProperties=$additionalProperties}" - } - - /** Options for streaming response. Only set this when you set stream: true. */ - @NoAutoDetect - class StreamOptions - @JsonCreator - private constructor( - @JsonProperty("include_usage") - @ExcludeMissing - private val includeUsage: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** - * If set, an additional chunk will be streamed before the data: [DONE] message. The usage - * field on this chunk shows the token usage statistics for the entire request, and the - * choices field will always be an empty array. All other chunks will also include a usage - * field, but with a null value. - */ - fun includeUsage(): Optional = - Optional.ofNullable(includeUsage.getNullable("include_usage")) - - /** - * If set, an additional chunk will be streamed before the data: [DONE] message. The usage - * field on this chunk shows the token usage statistics for the entire request, and the - * choices field will always be an empty array. All other chunks will also include a usage - * field, but with a null value. - */ - @JsonProperty("include_usage") - @ExcludeMissing - fun _includeUsage(): JsonField = includeUsage - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): StreamOptions = apply { - if (validated) { - return@apply - } - - includeUsage() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [StreamOptions]. */ - class Builder internal constructor() { - - private var includeUsage: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(streamOptions: StreamOptions) = apply { - includeUsage = streamOptions.includeUsage - additionalProperties = streamOptions.additionalProperties.toMutableMap() - } - - /** - * If set, an additional chunk will be streamed before the data: [DONE] message. The - * usage field on this chunk shows the token usage statistics for the entire request, - * and the choices field will always be an empty array. All other chunks will also - * include a usage field, but with a null value. - */ - fun includeUsage(includeUsage: Boolean) = includeUsage(JsonField.of(includeUsage)) - - /** - * If set, an additional chunk will be streamed before the data: [DONE] message. The - * usage field on this chunk shows the token usage statistics for the entire request, - * and the choices field will always be an empty array. All other chunks will also - * include a usage field, but with a null value. - */ - fun includeUsage(includeUsage: JsonField) = apply { - this.includeUsage = includeUsage - } - - 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) - } - - fun build(): StreamOptions = - StreamOptions(includeUsage, additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is StreamOptions && includeUsage == other.includeUsage && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(includeUsage, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "StreamOptions{includeUsage=$includeUsage, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ChatRequest && frequencyPenalty == other.frequencyPenalty && logitBias == other.logitBias && logprobs == other.logprobs && maxTokens == other.maxTokens && messages == other.messages && model == other.model && n == other.n && parallelToolCalls == other.parallelToolCalls && presencePenalty == other.presencePenalty && responseFormat == other.responseFormat && seed == other.seed && stop == other.stop && stream == other.stream && streamOptions == other.streamOptions && temperature == other.temperature && toolChoice == other.toolChoice && tools == other.tools && topLogprobs == other.topLogprobs && topP == other.topP && user == other.user && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(frequencyPenalty, logitBias, logprobs, maxTokens, messages, model, n, parallelToolCalls, presencePenalty, responseFormat, seed, stop, stream, streamOptions, temperature, toolChoice, tools, topLogprobs, topP, user, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ChatRequest{frequencyPenalty=$frequencyPenalty, logitBias=$logitBias, logprobs=$logprobs, maxTokens=$maxTokens, messages=$messages, model=$model, n=$n, parallelToolCalls=$parallelToolCalls, presencePenalty=$presencePenalty, responseFormat=$responseFormat, seed=$seed, stop=$stop, stream=$stream, streamOptions=$streamOptions, temperature=$temperature, toolChoice=$toolChoice, tools=$tools, topLogprobs=$topLogprobs, topP=$topP, user=$user, additionalProperties=$additionalProperties}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ChatResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/ChatResponse.kt deleted file mode 100644 index c5852c7..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ChatResponse.kt +++ /dev/null @@ -1,218 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import java.util.Objects -import java.util.Optional - -@NoAutoDetect -class ChatResponse -@JsonCreator -private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("choices") - @ExcludeMissing - private val choices: JsonField> = JsonMissing.of(), - @JsonProperty("created") - @ExcludeMissing - private val created: JsonField = JsonMissing.of(), - @JsonProperty("model") @ExcludeMissing private val model: JsonField = JsonMissing.of(), - @JsonProperty("object") - @ExcludeMissing - private val object_: JsonField = JsonMissing.of(), - @JsonProperty("system_fingerprint") - @ExcludeMissing - private val systemFingerprint: JsonField = JsonMissing.of(), - @JsonProperty("usage") @ExcludeMissing private val usage: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), -) { - - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - fun choices(): Optional> = Optional.ofNullable(choices.getNullable("choices")) - - fun created(): Optional = Optional.ofNullable(created.getNullable("created")) - - fun model(): Optional = Optional.ofNullable(model.getNullable("model")) - - fun object_(): Optional = Optional.ofNullable(object_.getNullable("object")) - - fun systemFingerprint(): Optional = - Optional.ofNullable(systemFingerprint.getNullable("system_fingerprint")) - - fun usage(): Optional = Optional.ofNullable(usage.getNullable("usage")) - - @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - - @JsonProperty("choices") @ExcludeMissing fun _choices(): JsonField> = choices - - @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created - - @JsonProperty("model") @ExcludeMissing fun _model(): JsonField = model - - @JsonProperty("object") @ExcludeMissing fun _object_(): JsonField = object_ - - @JsonProperty("system_fingerprint") - @ExcludeMissing - fun _systemFingerprint(): JsonField = systemFingerprint - - @JsonProperty("usage") @ExcludeMissing fun _usage(): JsonField = usage - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ChatResponse = apply { - if (validated) { - return@apply - } - - id() - choices().ifPresent { it.forEach { it.validate() } } - created() - model() - object_() - systemFingerprint() - usage().ifPresent { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ChatResponse]. */ - class Builder internal constructor() { - - private var id: JsonField = JsonMissing.of() - private var choices: JsonField>? = null - private var created: JsonField = JsonMissing.of() - private var model: JsonField = JsonMissing.of() - private var object_: JsonField = JsonMissing.of() - private var systemFingerprint: JsonField = JsonMissing.of() - private var usage: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(chatResponse: ChatResponse) = apply { - id = chatResponse.id - choices = chatResponse.choices.map { it.toMutableList() } - created = chatResponse.created - model = chatResponse.model - object_ = chatResponse.object_ - systemFingerprint = chatResponse.systemFingerprint - usage = chatResponse.usage - additionalProperties = chatResponse.additionalProperties.toMutableMap() - } - - fun id(id: String) = id(JsonField.of(id)) - - fun id(id: JsonField) = apply { this.id = id } - - fun choices(choices: List) = choices(JsonField.of(choices)) - - fun choices(choices: JsonField>) = apply { - this.choices = choices.map { it.toMutableList() } - } - - fun addChoice(choice: Choice) = apply { - choices = - (choices ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(choice) - } - } - - fun created(created: Long) = created(JsonField.of(created)) - - fun created(created: JsonField) = apply { this.created = created } - - fun model(model: String) = model(JsonField.of(model)) - - fun model(model: JsonField) = apply { this.model = model } - - fun object_(object_: String) = object_(JsonField.of(object_)) - - fun object_(object_: JsonField) = apply { this.object_ = object_ } - - fun systemFingerprint(systemFingerprint: String) = - systemFingerprint(JsonField.of(systemFingerprint)) - - fun systemFingerprint(systemFingerprint: JsonField) = apply { - this.systemFingerprint = systemFingerprint - } - - fun usage(usage: Usage) = usage(JsonField.of(usage)) - - fun usage(usage: JsonField) = apply { this.usage = usage } - - 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) - } - - fun build(): ChatResponse = - ChatResponse( - id, - (choices ?: JsonMissing.of()).map { it.toImmutable() }, - created, - model, - object_, - systemFingerprint, - usage, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ChatResponse && id == other.id && choices == other.choices && created == other.created && model == other.model && object_ == other.object_ && systemFingerprint == other.systemFingerprint && usage == other.usage && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(id, choices, created, model, object_, systemFingerprint, usage, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ChatResponse{id=$id, choices=$choices, created=$created, model=$model, object_=$object_, systemFingerprint=$systemFingerprint, usage=$usage, additionalProperties=$additionalProperties}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/Choice.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/Choice.kt deleted file mode 100644 index 8849407..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/Choice.kt +++ /dev/null @@ -1,221 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import java.util.Objects -import java.util.Optional - -@NoAutoDetect -class Choice -@JsonCreator -private constructor( - @JsonProperty("finish_reason") - @ExcludeMissing - private val finishReason: JsonField = JsonMissing.of(), - @JsonProperty("index") @ExcludeMissing private val index: JsonField = JsonMissing.of(), - @JsonProperty("logprobs") @ExcludeMissing private val logprobs: JsonValue = JsonMissing.of(), - @JsonProperty("message") - @ExcludeMissing - private val message: JsonField = JsonMissing.of(), - @JsonProperty("tool_authorizations") - @ExcludeMissing - private val toolAuthorizations: JsonField> = JsonMissing.of(), - @JsonProperty("tool_messages") - @ExcludeMissing - private val toolMessages: JsonField> = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), -) { - - fun finishReason(): Optional = - Optional.ofNullable(finishReason.getNullable("finish_reason")) - - fun index(): Optional = Optional.ofNullable(index.getNullable("index")) - - @JsonProperty("logprobs") @ExcludeMissing fun _logprobs(): JsonValue = logprobs - - fun message(): Optional = Optional.ofNullable(message.getNullable("message")) - - fun toolAuthorizations(): Optional> = - Optional.ofNullable(toolAuthorizations.getNullable("tool_authorizations")) - - fun toolMessages(): Optional> = - Optional.ofNullable(toolMessages.getNullable("tool_messages")) - - @JsonProperty("finish_reason") - @ExcludeMissing - fun _finishReason(): JsonField = finishReason - - @JsonProperty("index") @ExcludeMissing fun _index(): JsonField = index - - @JsonProperty("message") @ExcludeMissing fun _message(): JsonField = message - - @JsonProperty("tool_authorizations") - @ExcludeMissing - fun _toolAuthorizations(): JsonField> = toolAuthorizations - - @JsonProperty("tool_messages") - @ExcludeMissing - fun _toolMessages(): JsonField> = toolMessages - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Choice = apply { - if (validated) { - return@apply - } - - finishReason() - index() - message().ifPresent { it.validate() } - toolAuthorizations().ifPresent { it.forEach { it.validate() } } - toolMessages().ifPresent { it.forEach { it.validate() } } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Choice]. */ - class Builder internal constructor() { - - private var finishReason: JsonField = JsonMissing.of() - private var index: JsonField = JsonMissing.of() - private var logprobs: JsonValue = JsonMissing.of() - private var message: JsonField = JsonMissing.of() - private var toolAuthorizations: JsonField>? = null - private var toolMessages: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(choice: Choice) = apply { - finishReason = choice.finishReason - index = choice.index - logprobs = choice.logprobs - message = choice.message - toolAuthorizations = choice.toolAuthorizations.map { it.toMutableList() } - toolMessages = choice.toolMessages.map { it.toMutableList() } - additionalProperties = choice.additionalProperties.toMutableMap() - } - - fun finishReason(finishReason: String) = finishReason(JsonField.of(finishReason)) - - fun finishReason(finishReason: JsonField) = apply { - this.finishReason = finishReason - } - - fun index(index: Long) = index(JsonField.of(index)) - - fun index(index: JsonField) = apply { this.index = index } - - fun logprobs(logprobs: JsonValue) = apply { this.logprobs = logprobs } - - fun message(message: ChatMessage) = message(JsonField.of(message)) - - fun message(message: JsonField) = apply { this.message = message } - - fun toolAuthorizations(toolAuthorizations: List) = - toolAuthorizations(JsonField.of(toolAuthorizations)) - - fun toolAuthorizations(toolAuthorizations: JsonField>) = apply { - this.toolAuthorizations = toolAuthorizations.map { it.toMutableList() } - } - - fun addToolAuthorization(toolAuthorization: AuthorizationResponse) = apply { - toolAuthorizations = - (toolAuthorizations ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(toolAuthorization) - } - } - - fun toolMessages(toolMessages: List) = toolMessages(JsonField.of(toolMessages)) - - fun toolMessages(toolMessages: JsonField>) = apply { - this.toolMessages = toolMessages.map { it.toMutableList() } - } - - fun addToolMessage(toolMessage: ChatMessage) = apply { - toolMessages = - (toolMessages ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(toolMessage) - } - } - - 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) - } - - fun build(): Choice = - Choice( - finishReason, - index, - logprobs, - message, - (toolAuthorizations ?: JsonMissing.of()).map { it.toImmutable() }, - (toolMessages ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Choice && finishReason == other.finishReason && index == other.index && logprobs == other.logprobs && message == other.message && toolAuthorizations == other.toolAuthorizations && toolMessages == other.toolMessages && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(finishReason, index, logprobs, message, toolAuthorizations, toolMessages, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Choice{finishReason=$finishReason, index=$index, logprobs=$logprobs, message=$message, toolAuthorizations=$toolAuthorizations, toolMessages=$toolMessages, additionalProperties=$additionalProperties}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ConfirmUserRequest.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/ConfirmUserRequest.kt deleted file mode 100644 index 7730057..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ConfirmUserRequest.kt +++ /dev/null @@ -1,128 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.checkRequired -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import java.util.Objects - -@NoAutoDetect -class ConfirmUserRequest -@JsonCreator -private constructor( - @JsonProperty("flow_id") - @ExcludeMissing - private val flowId: JsonField = JsonMissing.of(), - @JsonProperty("user_id") - @ExcludeMissing - private val userId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), -) { - - fun flowId(): String = flowId.getRequired("flow_id") - - fun userId(): String = userId.getRequired("user_id") - - @JsonProperty("flow_id") @ExcludeMissing fun _flowId(): JsonField = flowId - - @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ConfirmUserRequest = apply { - if (validated) { - return@apply - } - - flowId() - userId() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ConfirmUserRequest]. */ - class Builder internal constructor() { - - private var flowId: JsonField? = null - private var userId: JsonField? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(confirmUserRequest: ConfirmUserRequest) = apply { - flowId = confirmUserRequest.flowId - userId = confirmUserRequest.userId - additionalProperties = confirmUserRequest.additionalProperties.toMutableMap() - } - - fun flowId(flowId: String) = flowId(JsonField.of(flowId)) - - fun flowId(flowId: JsonField) = apply { this.flowId = flowId } - - fun userId(userId: String) = userId(JsonField.of(userId)) - - fun userId(userId: JsonField) = apply { this.userId = userId } - - 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) - } - - fun build(): ConfirmUserRequest = - ConfirmUserRequest( - checkRequired("flowId", flowId), - checkRequired("userId", userId), - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ConfirmUserRequest && flowId == other.flowId && userId == other.userId && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(flowId, userId, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ConfirmUserRequest{flowId=$flowId, userId=$userId, additionalProperties=$additionalProperties}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ConfirmUserResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/ConfirmUserResponse.kt deleted file mode 100644 index ee54e05..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ConfirmUserResponse.kt +++ /dev/null @@ -1,129 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.checkRequired -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import java.util.Objects -import java.util.Optional - -@NoAutoDetect -class ConfirmUserResponse -@JsonCreator -private constructor( - @JsonProperty("auth_id") - @ExcludeMissing - private val authId: JsonField = JsonMissing.of(), - @JsonProperty("next_uri") - @ExcludeMissing - private val nextUri: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), -) { - - fun authId(): String = authId.getRequired("auth_id") - - fun nextUri(): Optional = Optional.ofNullable(nextUri.getNullable("next_uri")) - - @JsonProperty("auth_id") @ExcludeMissing fun _authId(): JsonField = authId - - @JsonProperty("next_uri") @ExcludeMissing fun _nextUri(): JsonField = nextUri - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ConfirmUserResponse = apply { - if (validated) { - return@apply - } - - authId() - nextUri() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ConfirmUserResponse]. */ - class Builder internal constructor() { - - private var authId: JsonField? = null - private var nextUri: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(confirmUserResponse: ConfirmUserResponse) = apply { - authId = confirmUserResponse.authId - nextUri = confirmUserResponse.nextUri - additionalProperties = confirmUserResponse.additionalProperties.toMutableMap() - } - - fun authId(authId: String) = authId(JsonField.of(authId)) - - fun authId(authId: JsonField) = apply { this.authId = authId } - - fun nextUri(nextUri: String) = nextUri(JsonField.of(nextUri)) - - fun nextUri(nextUri: JsonField) = apply { this.nextUri = nextUri } - - 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) - } - - fun build(): ConfirmUserResponse = - ConfirmUserResponse( - checkRequired("authId", authId), - nextUri, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ConfirmUserResponse && authId == other.authId && nextUri == other.nextUri && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(authId, nextUri, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ConfirmUserResponse{authId=$authId, nextUri=$nextUri, additionalProperties=$additionalProperties}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/CreateWorkerRequest.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/CreateWorkerRequest.kt deleted file mode 100644 index 799aabc..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/CreateWorkerRequest.kt +++ /dev/null @@ -1,800 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.checkRequired -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import java.util.Objects -import java.util.Optional - -@NoAutoDetect -class CreateWorkerRequest -@JsonCreator -private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("enabled") - @ExcludeMissing - private val enabled: JsonField = JsonMissing.of(), - @JsonProperty("http") @ExcludeMissing private val http: JsonField = JsonMissing.of(), - @JsonProperty("mcp") @ExcludeMissing private val mcp: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), -) { - - fun id(): String = id.getRequired("id") - - fun enabled(): Optional = Optional.ofNullable(enabled.getNullable("enabled")) - - fun http(): Optional = Optional.ofNullable(http.getNullable("http")) - - fun mcp(): Optional = Optional.ofNullable(mcp.getNullable("mcp")) - - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - - @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - - @JsonProperty("enabled") @ExcludeMissing fun _enabled(): JsonField = enabled - - @JsonProperty("http") @ExcludeMissing fun _http(): JsonField = http - - @JsonProperty("mcp") @ExcludeMissing fun _mcp(): JsonField = mcp - - @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): CreateWorkerRequest = apply { - if (validated) { - return@apply - } - - id() - enabled() - http().ifPresent { it.validate() } - mcp().ifPresent { it.validate() } - type() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [CreateWorkerRequest]. */ - class Builder internal constructor() { - - private var id: JsonField? = null - private var enabled: JsonField = JsonMissing.of() - private var http: JsonField = JsonMissing.of() - private var mcp: JsonField = JsonMissing.of() - private var type: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(createWorkerRequest: CreateWorkerRequest) = apply { - id = createWorkerRequest.id - enabled = createWorkerRequest.enabled - http = createWorkerRequest.http - mcp = createWorkerRequest.mcp - type = createWorkerRequest.type - additionalProperties = createWorkerRequest.additionalProperties.toMutableMap() - } - - fun id(id: String) = id(JsonField.of(id)) - - fun id(id: JsonField) = apply { this.id = id } - - fun enabled(enabled: Boolean) = enabled(JsonField.of(enabled)) - - fun enabled(enabled: JsonField) = apply { this.enabled = enabled } - - fun http(http: Http) = http(JsonField.of(http)) - - fun http(http: JsonField) = apply { this.http = http } - - fun mcp(mcp: Mcp) = mcp(JsonField.of(mcp)) - - fun mcp(mcp: JsonField) = apply { this.mcp = mcp } - - fun type(type: String) = type(JsonField.of(type)) - - 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) - } - - fun build(): CreateWorkerRequest = - CreateWorkerRequest( - checkRequired("id", id), - enabled, - http, - mcp, - type, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class Http - @JsonCreator - private constructor( - @JsonProperty("retry") - @ExcludeMissing - private val retry: JsonField = JsonMissing.of(), - @JsonProperty("secret") - @ExcludeMissing - private val secret: JsonField = JsonMissing.of(), - @JsonProperty("timeout") - @ExcludeMissing - private val timeout: JsonField = JsonMissing.of(), - @JsonProperty("uri") @ExcludeMissing private val uri: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun retry(): Long = retry.getRequired("retry") - - fun secret(): String = secret.getRequired("secret") - - fun timeout(): Long = timeout.getRequired("timeout") - - fun uri(): String = uri.getRequired("uri") - - @JsonProperty("retry") @ExcludeMissing fun _retry(): JsonField = retry - - @JsonProperty("secret") @ExcludeMissing fun _secret(): JsonField = secret - - @JsonProperty("timeout") @ExcludeMissing fun _timeout(): JsonField = timeout - - @JsonProperty("uri") @ExcludeMissing fun _uri(): JsonField = uri - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Http = apply { - if (validated) { - return@apply - } - - retry() - secret() - timeout() - uri() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Http]. */ - class Builder internal constructor() { - - private var retry: JsonField? = null - private var secret: JsonField? = null - private var timeout: JsonField? = null - private var uri: JsonField? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(http: Http) = apply { - retry = http.retry - secret = http.secret - timeout = http.timeout - uri = http.uri - additionalProperties = http.additionalProperties.toMutableMap() - } - - fun retry(retry: Long) = retry(JsonField.of(retry)) - - fun retry(retry: JsonField) = apply { this.retry = retry } - - fun secret(secret: String) = secret(JsonField.of(secret)) - - fun secret(secret: JsonField) = apply { this.secret = secret } - - fun timeout(timeout: Long) = timeout(JsonField.of(timeout)) - - fun timeout(timeout: JsonField) = apply { this.timeout = timeout } - - fun uri(uri: String) = uri(JsonField.of(uri)) - - fun uri(uri: JsonField) = apply { this.uri = uri } - - 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) - } - - fun build(): Http = - Http( - checkRequired("retry", retry), - checkRequired("secret", secret), - checkRequired("timeout", timeout), - checkRequired("uri", uri), - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Http && retry == other.retry && secret == other.secret && timeout == other.timeout && uri == other.uri && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(retry, secret, timeout, uri, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Http{retry=$retry, secret=$secret, timeout=$timeout, uri=$uri, additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class Mcp - @JsonCreator - private constructor( - @JsonProperty("retry") - @ExcludeMissing - private val retry: JsonField = JsonMissing.of(), - @JsonProperty("timeout") - @ExcludeMissing - private val timeout: JsonField = JsonMissing.of(), - @JsonProperty("uri") @ExcludeMissing private val uri: JsonField = JsonMissing.of(), - @JsonProperty("headers") - @ExcludeMissing - private val headers: JsonField = JsonMissing.of(), - @JsonProperty("oauth2") - @ExcludeMissing - private val oauth2: JsonField = JsonMissing.of(), - @JsonProperty("secrets") - @ExcludeMissing - private val secrets: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun retry(): Long = retry.getRequired("retry") - - fun timeout(): Long = timeout.getRequired("timeout") - - fun uri(): String = uri.getRequired("uri") - - fun headers(): Optional = Optional.ofNullable(headers.getNullable("headers")) - - fun oauth2(): Optional = Optional.ofNullable(oauth2.getNullable("oauth2")) - - fun secrets(): Optional = Optional.ofNullable(secrets.getNullable("secrets")) - - @JsonProperty("retry") @ExcludeMissing fun _retry(): JsonField = retry - - @JsonProperty("timeout") @ExcludeMissing fun _timeout(): JsonField = timeout - - @JsonProperty("uri") @ExcludeMissing fun _uri(): JsonField = uri - - @JsonProperty("headers") @ExcludeMissing fun _headers(): JsonField = headers - - @JsonProperty("oauth2") @ExcludeMissing fun _oauth2(): JsonField = oauth2 - - @JsonProperty("secrets") @ExcludeMissing fun _secrets(): JsonField = secrets - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Mcp = apply { - if (validated) { - return@apply - } - - retry() - timeout() - uri() - headers().ifPresent { it.validate() } - oauth2().ifPresent { it.validate() } - secrets().ifPresent { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Mcp]. */ - class Builder internal constructor() { - - private var retry: JsonField? = null - private var timeout: JsonField? = null - private var uri: JsonField? = null - private var headers: JsonField = JsonMissing.of() - private var oauth2: JsonField = JsonMissing.of() - private var secrets: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(mcp: Mcp) = apply { - retry = mcp.retry - timeout = mcp.timeout - uri = mcp.uri - headers = mcp.headers - oauth2 = mcp.oauth2 - secrets = mcp.secrets - additionalProperties = mcp.additionalProperties.toMutableMap() - } - - fun retry(retry: Long) = retry(JsonField.of(retry)) - - fun retry(retry: JsonField) = apply { this.retry = retry } - - fun timeout(timeout: Long) = timeout(JsonField.of(timeout)) - - fun timeout(timeout: JsonField) = apply { this.timeout = timeout } - - fun uri(uri: String) = uri(JsonField.of(uri)) - - fun uri(uri: JsonField) = apply { this.uri = uri } - - fun headers(headers: Headers) = headers(JsonField.of(headers)) - - fun headers(headers: JsonField) = apply { this.headers = headers } - - fun oauth2(oauth2: Oauth2) = oauth2(JsonField.of(oauth2)) - - fun oauth2(oauth2: JsonField) = apply { this.oauth2 = oauth2 } - - fun secrets(secrets: Secrets) = secrets(JsonField.of(secrets)) - - fun secrets(secrets: JsonField) = apply { this.secrets = secrets } - - 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) - } - - fun build(): Mcp = - Mcp( - checkRequired("retry", retry), - checkRequired("timeout", timeout), - checkRequired("uri", uri), - headers, - oauth2, - secrets, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class Headers - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Headers = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Headers]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(headers: Headers) = apply { - additionalProperties = headers.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) - } - - fun build(): Headers = Headers(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Headers && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "Headers{additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class Oauth2 - @JsonCreator - private constructor( - @JsonProperty("authorization_url") - @ExcludeMissing - private val authorizationUrl: JsonField = JsonMissing.of(), - @JsonProperty("client_id") - @ExcludeMissing - private val clientId: JsonField = JsonMissing.of(), - @JsonProperty("client_secret") - @ExcludeMissing - private val clientSecret: JsonField = JsonMissing.of(), - @JsonProperty("external_id") - @ExcludeMissing - private val externalId: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun authorizationUrl(): Optional = - Optional.ofNullable(authorizationUrl.getNullable("authorization_url")) - - fun clientId(): Optional = - Optional.ofNullable(clientId.getNullable("client_id")) - - fun clientSecret(): Optional = - Optional.ofNullable(clientSecret.getNullable("client_secret")) - - fun externalId(): Optional = - Optional.ofNullable(externalId.getNullable("external_id")) - - @JsonProperty("authorization_url") - @ExcludeMissing - fun _authorizationUrl(): JsonField = authorizationUrl - - @JsonProperty("client_id") @ExcludeMissing fun _clientId(): JsonField = clientId - - @JsonProperty("client_secret") - @ExcludeMissing - fun _clientSecret(): JsonField = clientSecret - - @JsonProperty("external_id") - @ExcludeMissing - fun _externalId(): JsonField = externalId - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Oauth2 = apply { - if (validated) { - return@apply - } - - authorizationUrl() - clientId() - clientSecret() - externalId() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Oauth2]. */ - class Builder internal constructor() { - - private var authorizationUrl: JsonField = JsonMissing.of() - private var clientId: JsonField = JsonMissing.of() - private var clientSecret: JsonField = JsonMissing.of() - private var externalId: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(oauth2: Oauth2) = apply { - authorizationUrl = oauth2.authorizationUrl - clientId = oauth2.clientId - clientSecret = oauth2.clientSecret - externalId = oauth2.externalId - additionalProperties = oauth2.additionalProperties.toMutableMap() - } - - fun authorizationUrl(authorizationUrl: String) = - authorizationUrl(JsonField.of(authorizationUrl)) - - fun authorizationUrl(authorizationUrl: JsonField) = apply { - this.authorizationUrl = authorizationUrl - } - - fun clientId(clientId: String) = clientId(JsonField.of(clientId)) - - fun clientId(clientId: JsonField) = apply { this.clientId = clientId } - - fun clientSecret(clientSecret: String) = clientSecret(JsonField.of(clientSecret)) - - fun clientSecret(clientSecret: JsonField) = apply { - this.clientSecret = clientSecret - } - - fun externalId(externalId: String) = externalId(JsonField.of(externalId)) - - fun externalId(externalId: JsonField) = apply { - this.externalId = externalId - } - - 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) - } - - fun build(): Oauth2 = - Oauth2( - authorizationUrl, - clientId, - clientSecret, - externalId, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Oauth2 && authorizationUrl == other.authorizationUrl && clientId == other.clientId && clientSecret == other.clientSecret && externalId == other.externalId && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(authorizationUrl, clientId, clientSecret, externalId, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Oauth2{authorizationUrl=$authorizationUrl, clientId=$clientId, clientSecret=$clientSecret, externalId=$externalId, additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class Secrets - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Secrets = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Secrets]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(secrets: Secrets) = apply { - additionalProperties = secrets.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) - } - - fun build(): Secrets = Secrets(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Secrets && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "Secrets{additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Mcp && retry == other.retry && timeout == other.timeout && uri == other.uri && headers == other.headers && oauth2 == other.oauth2 && secrets == other.secrets && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(retry, timeout, uri, headers, oauth2, secrets, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Mcp{retry=$retry, timeout=$timeout, uri=$uri, headers=$headers, oauth2=$oauth2, secrets=$secrets, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is CreateWorkerRequest && id == other.id && enabled == other.enabled && http == other.http && mcp == other.mcp && type == other.type && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(id, enabled, http, mcp, type, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "CreateWorkerRequest{id=$id, enabled=$enabled, http=$http, mcp=$mcp, type=$type, additionalProperties=$additionalProperties}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/Error.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/Error.kt index ddfffcd..40800cb 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/Error.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/Error.kt @@ -10,51 +10,66 @@ import dev.arcade.core.ExcludeMissing import dev.arcade.core.JsonField import dev.arcade.core.JsonMissing import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional -@NoAutoDetect class Error -@JsonCreator +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( - @JsonProperty("message") - @ExcludeMissing - private val message: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing private val name: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val message: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, ) { - fun message(): Optional = Optional.ofNullable(message.getNullable("message")) - - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) - + @JsonCreator + private constructor( + @JsonProperty("message") @ExcludeMissing message: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + ) : this(message, name, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun message(): Optional = message.getOptional("message") + + /** + * @throws ArcadeInvalidDataException 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 [message]. + * + * Unlike [message], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("message") @ExcludeMissing fun _message(): JsonField = message + /** + * 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 = additionalProperties - - private var validated: Boolean = false - - fun validate(): Error = apply { - if (validated) { - return@apply - } - - message() - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Error]. */ @JvmStatic fun builder() = Builder() } @@ -74,10 +89,22 @@ private constructor( fun message(message: String) = message(JsonField.of(message)) + /** + * Sets [Builder.message] to an arbitrary JSON value. + * + * You should usually call [Builder.message] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun message(message: JsonField) = apply { this.message = message } 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 { @@ -99,20 +126,55 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Error = Error(message, name, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Error]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Error = Error(message, name, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Error = apply { + if (validated) { + return@apply + } + + message() + name() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (message.asKnown().isPresent) 1 else 0) + (if (name.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is Error && message == other.message && name == other.name && additionalProperties == other.additionalProperties /* spotless:on */ + return other is Error && + message == other.message && + name == other.name && + additionalProperties == other.additionalProperties } - /* spotless:off */ private val hashCode: Int by lazy { Objects.hash(message, name, additionalProperties) } - /* spotless:on */ override fun hashCode(): Int = hashCode diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ExecuteToolRequest.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/ExecuteToolRequest.kt deleted file mode 100644 index 486a36d..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ExecuteToolRequest.kt +++ /dev/null @@ -1,313 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.checkRequired -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import java.util.Objects -import java.util.Optional - -@NoAutoDetect -class ExecuteToolRequest -@JsonCreator -private constructor( - @JsonProperty("tool_name") - @ExcludeMissing - private val toolName: JsonField = JsonMissing.of(), - @JsonProperty("include_error_stacktrace") - @ExcludeMissing - private val includeErrorStacktrace: JsonField = JsonMissing.of(), - @JsonProperty("input") @ExcludeMissing private val input: JsonField = JsonMissing.of(), - @JsonProperty("run_at") @ExcludeMissing private val runAt: JsonField = JsonMissing.of(), - @JsonProperty("tool_version") - @ExcludeMissing - private val toolVersion: JsonField = JsonMissing.of(), - @JsonProperty("user_id") - @ExcludeMissing - private val userId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), -) { - - fun toolName(): String = toolName.getRequired("tool_name") - - /** - * Whether to include the error stacktrace in the response. If not provided, the error - * stacktrace is not included. - */ - fun includeErrorStacktrace(): Optional = - Optional.ofNullable(includeErrorStacktrace.getNullable("include_error_stacktrace")) - - /** JSON input to the tool, if any */ - fun input(): Optional = Optional.ofNullable(input.getNullable("input")) - - /** - * The time at which the tool should be run (optional). If not provided, the tool is run - * immediately. Format ISO 8601: YYYY-MM-DDTHH:MM:SS - */ - fun runAt(): Optional = Optional.ofNullable(runAt.getNullable("run_at")) - - /** The tool version to use (optional). If not provided, any version is used */ - fun toolVersion(): Optional = - Optional.ofNullable(toolVersion.getNullable("tool_version")) - - fun userId(): Optional = Optional.ofNullable(userId.getNullable("user_id")) - - @JsonProperty("tool_name") @ExcludeMissing fun _toolName(): JsonField = toolName - - /** - * Whether to include the error stacktrace in the response. If not provided, the error - * stacktrace is not included. - */ - @JsonProperty("include_error_stacktrace") - @ExcludeMissing - fun _includeErrorStacktrace(): JsonField = includeErrorStacktrace - - /** JSON input to the tool, if any */ - @JsonProperty("input") @ExcludeMissing fun _input(): JsonField = input - - /** - * The time at which the tool should be run (optional). If not provided, the tool is run - * immediately. Format ISO 8601: YYYY-MM-DDTHH:MM:SS - */ - @JsonProperty("run_at") @ExcludeMissing fun _runAt(): JsonField = runAt - - /** The tool version to use (optional). If not provided, any version is used */ - @JsonProperty("tool_version") - @ExcludeMissing - fun _toolVersion(): JsonField = toolVersion - - @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ExecuteToolRequest = apply { - if (validated) { - return@apply - } - - toolName() - includeErrorStacktrace() - input().ifPresent { it.validate() } - runAt() - toolVersion() - userId() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ExecuteToolRequest]. */ - class Builder internal constructor() { - - private var toolName: JsonField? = null - private var includeErrorStacktrace: JsonField = JsonMissing.of() - private var input: JsonField = JsonMissing.of() - private var runAt: JsonField = JsonMissing.of() - private var toolVersion: JsonField = JsonMissing.of() - private var userId: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(executeToolRequest: ExecuteToolRequest) = apply { - toolName = executeToolRequest.toolName - includeErrorStacktrace = executeToolRequest.includeErrorStacktrace - input = executeToolRequest.input - runAt = executeToolRequest.runAt - toolVersion = executeToolRequest.toolVersion - userId = executeToolRequest.userId - additionalProperties = executeToolRequest.additionalProperties.toMutableMap() - } - - fun toolName(toolName: String) = toolName(JsonField.of(toolName)) - - fun toolName(toolName: JsonField) = apply { this.toolName = toolName } - - /** - * Whether to include the error stacktrace in the response. If not provided, the error - * stacktrace is not included. - */ - fun includeErrorStacktrace(includeErrorStacktrace: Boolean) = - includeErrorStacktrace(JsonField.of(includeErrorStacktrace)) - - /** - * Whether to include the error stacktrace in the response. If not provided, the error - * stacktrace is not included. - */ - fun includeErrorStacktrace(includeErrorStacktrace: JsonField) = apply { - this.includeErrorStacktrace = includeErrorStacktrace - } - - /** JSON input to the tool, if any */ - fun input(input: Input) = input(JsonField.of(input)) - - /** JSON input to the tool, if any */ - fun input(input: JsonField) = apply { this.input = input } - - /** - * The time at which the tool should be run (optional). If not provided, the tool is run - * immediately. Format ISO 8601: YYYY-MM-DDTHH:MM:SS - */ - fun runAt(runAt: String) = runAt(JsonField.of(runAt)) - - /** - * The time at which the tool should be run (optional). If not provided, the tool is run - * immediately. Format ISO 8601: YYYY-MM-DDTHH:MM:SS - */ - fun runAt(runAt: JsonField) = apply { this.runAt = runAt } - - /** The tool version to use (optional). If not provided, any version is used */ - fun toolVersion(toolVersion: String) = toolVersion(JsonField.of(toolVersion)) - - /** The tool version to use (optional). If not provided, any version is used */ - fun toolVersion(toolVersion: JsonField) = apply { this.toolVersion = toolVersion } - - fun userId(userId: String) = userId(JsonField.of(userId)) - - fun userId(userId: JsonField) = apply { this.userId = userId } - - 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) - } - - fun build(): ExecuteToolRequest = - ExecuteToolRequest( - checkRequired("toolName", toolName), - includeErrorStacktrace, - input, - runAt, - toolVersion, - userId, - additionalProperties.toImmutable(), - ) - } - - /** JSON input to the tool, if any */ - @NoAutoDetect - class Input - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Input = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Input]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(input: Input) = apply { - additionalProperties = input.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) - } - - fun build(): Input = Input(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Input && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "Input{additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ExecuteToolRequest && toolName == other.toolName && includeErrorStacktrace == other.includeErrorStacktrace && input == other.input && runAt == other.runAt && toolVersion == other.toolVersion && userId == other.userId && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(toolName, includeErrorStacktrace, input, runAt, toolVersion, userId, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ExecuteToolRequest{toolName=$toolName, includeErrorStacktrace=$includeErrorStacktrace, input=$input, runAt=$runAt, toolVersion=$toolVersion, userId=$userId, additionalProperties=$additionalProperties}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ExecuteToolResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/ExecuteToolResponse.kt deleted file mode 100644 index b82e8c3..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ExecuteToolResponse.kt +++ /dev/null @@ -1,1082 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.Enum -import dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.checkRequired -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import dev.arcade.errors.ArcadeInvalidDataException -import java.util.Objects -import java.util.Optional - -@NoAutoDetect -class ExecuteToolResponse -@JsonCreator -private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("duration") - @ExcludeMissing - private val duration: JsonField = JsonMissing.of(), - @JsonProperty("execution_id") - @ExcludeMissing - private val executionId: JsonField = JsonMissing.of(), - @JsonProperty("execution_type") - @ExcludeMissing - private val executionType: JsonField = JsonMissing.of(), - @JsonProperty("finished_at") - @ExcludeMissing - private val finishedAt: JsonField = JsonMissing.of(), - @JsonProperty("output") - @ExcludeMissing - private val output: JsonField = JsonMissing.of(), - @JsonProperty("run_at") @ExcludeMissing private val runAt: JsonField = JsonMissing.of(), - @JsonProperty("status") - @ExcludeMissing - private val status: JsonField = JsonMissing.of(), - @JsonProperty("success") - @ExcludeMissing - private val success: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), -) { - - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - fun duration(): Optional = Optional.ofNullable(duration.getNullable("duration")) - - fun executionId(): Optional = - Optional.ofNullable(executionId.getNullable("execution_id")) - - fun executionType(): Optional = - Optional.ofNullable(executionType.getNullable("execution_type")) - - fun finishedAt(): Optional = Optional.ofNullable(finishedAt.getNullable("finished_at")) - - fun output(): Optional = Optional.ofNullable(output.getNullable("output")) - - fun runAt(): Optional = Optional.ofNullable(runAt.getNullable("run_at")) - - fun status(): Optional = Optional.ofNullable(status.getNullable("status")) - - /** - * Whether the request was successful. For immediately-executed requests, this will be true if - * the tool call succeeded. For scheduled requests, this will be true if the request was - * scheduled successfully. - */ - fun success(): Optional = Optional.ofNullable(success.getNullable("success")) - - @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - - @JsonProperty("duration") @ExcludeMissing fun _duration(): JsonField = duration - - @JsonProperty("execution_id") - @ExcludeMissing - fun _executionId(): JsonField = executionId - - @JsonProperty("execution_type") - @ExcludeMissing - fun _executionType(): JsonField = executionType - - @JsonProperty("finished_at") @ExcludeMissing fun _finishedAt(): JsonField = finishedAt - - @JsonProperty("output") @ExcludeMissing fun _output(): JsonField = output - - @JsonProperty("run_at") @ExcludeMissing fun _runAt(): JsonField = runAt - - @JsonProperty("status") @ExcludeMissing fun _status(): JsonField = status - - /** - * Whether the request was successful. For immediately-executed requests, this will be true if - * the tool call succeeded. For scheduled requests, this will be true if the request was - * scheduled successfully. - */ - @JsonProperty("success") @ExcludeMissing fun _success(): JsonField = success - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ExecuteToolResponse = apply { - if (validated) { - return@apply - } - - id() - duration() - executionId() - executionType() - finishedAt() - output().ifPresent { it.validate() } - runAt() - status() - success() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ExecuteToolResponse]. */ - class Builder internal constructor() { - - private var id: JsonField = JsonMissing.of() - private var duration: JsonField = JsonMissing.of() - private var executionId: JsonField = JsonMissing.of() - private var executionType: JsonField = JsonMissing.of() - private var finishedAt: JsonField = JsonMissing.of() - private var output: JsonField = JsonMissing.of() - private var runAt: JsonField = JsonMissing.of() - private var status: JsonField = JsonMissing.of() - private var success: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(executeToolResponse: ExecuteToolResponse) = apply { - id = executeToolResponse.id - duration = executeToolResponse.duration - executionId = executeToolResponse.executionId - executionType = executeToolResponse.executionType - finishedAt = executeToolResponse.finishedAt - output = executeToolResponse.output - runAt = executeToolResponse.runAt - status = executeToolResponse.status - success = executeToolResponse.success - additionalProperties = executeToolResponse.additionalProperties.toMutableMap() - } - - fun id(id: String) = id(JsonField.of(id)) - - fun id(id: JsonField) = apply { this.id = id } - - fun duration(duration: Double) = duration(JsonField.of(duration)) - - fun duration(duration: JsonField) = apply { this.duration = duration } - - fun executionId(executionId: String) = executionId(JsonField.of(executionId)) - - fun executionId(executionId: JsonField) = apply { this.executionId = executionId } - - fun executionType(executionType: String) = executionType(JsonField.of(executionType)) - - fun executionType(executionType: JsonField) = apply { - this.executionType = executionType - } - - fun finishedAt(finishedAt: String) = finishedAt(JsonField.of(finishedAt)) - - fun finishedAt(finishedAt: JsonField) = apply { this.finishedAt = finishedAt } - - fun output(output: Output) = output(JsonField.of(output)) - - fun output(output: JsonField) = apply { this.output = output } - - fun runAt(runAt: String) = runAt(JsonField.of(runAt)) - - fun runAt(runAt: JsonField) = apply { this.runAt = runAt } - - fun status(status: String) = status(JsonField.of(status)) - - fun status(status: JsonField) = apply { this.status = status } - - /** - * Whether the request was successful. For immediately-executed requests, this will be true - * if the tool call succeeded. For scheduled requests, this will be true if the request was - * scheduled successfully. - */ - fun success(success: Boolean) = success(JsonField.of(success)) - - /** - * Whether the request was successful. For immediately-executed requests, this will be true - * if the tool call succeeded. For scheduled requests, this will be true if the request was - * scheduled successfully. - */ - fun success(success: JsonField) = apply { this.success = success } - - 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) - } - - fun build(): ExecuteToolResponse = - ExecuteToolResponse( - id, - duration, - executionId, - executionType, - finishedAt, - output, - runAt, - status, - success, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class Output - @JsonCreator - private constructor( - @JsonProperty("authorization") - @ExcludeMissing - private val authorization: JsonField = JsonMissing.of(), - @JsonProperty("error") - @ExcludeMissing - private val error: JsonField = JsonMissing.of(), - @JsonProperty("logs") - @ExcludeMissing - private val logs: JsonField> = JsonMissing.of(), - @JsonProperty("value") @ExcludeMissing private val value: JsonValue = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun authorization(): Optional = - Optional.ofNullable(authorization.getNullable("authorization")) - - fun error(): Optional = Optional.ofNullable(error.getNullable("error")) - - fun logs(): Optional> = Optional.ofNullable(logs.getNullable("logs")) - - @JsonProperty("value") @ExcludeMissing fun _value(): JsonValue = value - - @JsonProperty("authorization") - @ExcludeMissing - fun _authorization(): JsonField = authorization - - @JsonProperty("error") @ExcludeMissing fun _error(): JsonField = error - - @JsonProperty("logs") @ExcludeMissing fun _logs(): JsonField> = logs - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Output = apply { - if (validated) { - return@apply - } - - authorization().ifPresent { it.validate() } - error().ifPresent { it.validate() } - logs().ifPresent { it.forEach { it.validate() } } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Output]. */ - class Builder internal constructor() { - - private var authorization: JsonField = JsonMissing.of() - private var error: JsonField = JsonMissing.of() - private var logs: JsonField>? = null - private var value: JsonValue = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(output: Output) = apply { - authorization = output.authorization - error = output.error - logs = output.logs.map { it.toMutableList() } - value = output.value - additionalProperties = output.additionalProperties.toMutableMap() - } - - fun authorization(authorization: AuthorizationResponse) = - authorization(JsonField.of(authorization)) - - fun authorization(authorization: JsonField) = apply { - this.authorization = authorization - } - - fun error(error: Error) = error(JsonField.of(error)) - - fun error(error: JsonField) = apply { this.error = error } - - fun logs(logs: List) = logs(JsonField.of(logs)) - - fun logs(logs: JsonField>) = apply { - this.logs = logs.map { it.toMutableList() } - } - - fun addLog(log: Log) = apply { - logs = - (logs ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(log) - } - } - - fun value(value: JsonValue) = 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) - } - - fun build(): Output = - Output( - authorization, - error, - (logs ?: JsonMissing.of()).map { it.toImmutable() }, - value, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class Error - @JsonCreator - private constructor( - @JsonProperty("can_retry") - @ExcludeMissing - private val canRetry: JsonField = JsonMissing.of(), - @JsonProperty("kind") - @ExcludeMissing - private val kind: JsonField = JsonMissing.of(), - @JsonProperty("message") - @ExcludeMissing - private val message: JsonField = JsonMissing.of(), - @JsonProperty("additional_prompt_content") - @ExcludeMissing - private val additionalPromptContent: JsonField = JsonMissing.of(), - @JsonProperty("developer_message") - @ExcludeMissing - private val developerMessage: JsonField = JsonMissing.of(), - @JsonProperty("extra") - @ExcludeMissing - private val extra: JsonField = JsonMissing.of(), - @JsonProperty("retry_after_ms") - @ExcludeMissing - private val retryAfterMs: JsonField = JsonMissing.of(), - @JsonProperty("stacktrace") - @ExcludeMissing - private val stacktrace: JsonField = JsonMissing.of(), - @JsonProperty("status_code") - @ExcludeMissing - private val statusCode: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun canRetry(): Boolean = canRetry.getRequired("can_retry") - - fun kind(): Kind = kind.getRequired("kind") - - fun message(): String = message.getRequired("message") - - fun additionalPromptContent(): Optional = - Optional.ofNullable( - additionalPromptContent.getNullable("additional_prompt_content") - ) - - fun developerMessage(): Optional = - Optional.ofNullable(developerMessage.getNullable("developer_message")) - - fun extra(): Optional = Optional.ofNullable(extra.getNullable("extra")) - - fun retryAfterMs(): Optional = - Optional.ofNullable(retryAfterMs.getNullable("retry_after_ms")) - - fun stacktrace(): Optional = - Optional.ofNullable(stacktrace.getNullable("stacktrace")) - - fun statusCode(): Optional = - Optional.ofNullable(statusCode.getNullable("status_code")) - - @JsonProperty("can_retry") - @ExcludeMissing - fun _canRetry(): JsonField = canRetry - - @JsonProperty("kind") @ExcludeMissing fun _kind(): JsonField = kind - - @JsonProperty("message") @ExcludeMissing fun _message(): JsonField = message - - @JsonProperty("additional_prompt_content") - @ExcludeMissing - fun _additionalPromptContent(): JsonField = additionalPromptContent - - @JsonProperty("developer_message") - @ExcludeMissing - fun _developerMessage(): JsonField = developerMessage - - @JsonProperty("extra") @ExcludeMissing fun _extra(): JsonField = extra - - @JsonProperty("retry_after_ms") - @ExcludeMissing - fun _retryAfterMs(): JsonField = retryAfterMs - - @JsonProperty("stacktrace") - @ExcludeMissing - fun _stacktrace(): JsonField = stacktrace - - @JsonProperty("status_code") - @ExcludeMissing - fun _statusCode(): JsonField = statusCode - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Error = apply { - if (validated) { - return@apply - } - - canRetry() - kind() - message() - additionalPromptContent() - developerMessage() - extra().ifPresent { it.validate() } - retryAfterMs() - stacktrace() - statusCode() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Error]. */ - class Builder internal constructor() { - - private var canRetry: JsonField? = null - private var kind: JsonField? = null - private var message: JsonField? = null - private var additionalPromptContent: JsonField = JsonMissing.of() - private var developerMessage: JsonField = JsonMissing.of() - private var extra: JsonField = JsonMissing.of() - private var retryAfterMs: JsonField = JsonMissing.of() - private var stacktrace: JsonField = JsonMissing.of() - private var statusCode: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(error: Error) = apply { - canRetry = error.canRetry - kind = error.kind - message = error.message - additionalPromptContent = error.additionalPromptContent - developerMessage = error.developerMessage - extra = error.extra - retryAfterMs = error.retryAfterMs - stacktrace = error.stacktrace - statusCode = error.statusCode - additionalProperties = error.additionalProperties.toMutableMap() - } - - fun canRetry(canRetry: Boolean) = canRetry(JsonField.of(canRetry)) - - fun canRetry(canRetry: JsonField) = apply { this.canRetry = canRetry } - - fun kind(kind: Kind) = kind(JsonField.of(kind)) - - fun kind(kind: JsonField) = apply { this.kind = kind } - - fun message(message: String) = message(JsonField.of(message)) - - fun message(message: JsonField) = apply { this.message = message } - - fun additionalPromptContent(additionalPromptContent: String) = - additionalPromptContent(JsonField.of(additionalPromptContent)) - - fun additionalPromptContent(additionalPromptContent: JsonField) = apply { - this.additionalPromptContent = additionalPromptContent - } - - fun developerMessage(developerMessage: String) = - developerMessage(JsonField.of(developerMessage)) - - fun developerMessage(developerMessage: JsonField) = apply { - this.developerMessage = developerMessage - } - - fun extra(extra: Extra) = extra(JsonField.of(extra)) - - fun extra(extra: JsonField) = apply { this.extra = extra } - - fun retryAfterMs(retryAfterMs: Long) = retryAfterMs(JsonField.of(retryAfterMs)) - - fun retryAfterMs(retryAfterMs: JsonField) = apply { - this.retryAfterMs = retryAfterMs - } - - fun stacktrace(stacktrace: String) = stacktrace(JsonField.of(stacktrace)) - - fun stacktrace(stacktrace: JsonField) = apply { - this.stacktrace = stacktrace - } - - fun statusCode(statusCode: Long) = statusCode(JsonField.of(statusCode)) - - fun statusCode(statusCode: JsonField) = apply { this.statusCode = statusCode } - - 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) - } - - fun build(): Error = - Error( - checkRequired("canRetry", canRetry), - checkRequired("kind", kind), - checkRequired("message", message), - additionalPromptContent, - developerMessage, - extra, - retryAfterMs, - stacktrace, - statusCode, - additionalProperties.toImmutable(), - ) - } - - class Kind @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 TOOLKIT_LOAD_FAILED = of("TOOLKIT_LOAD_FAILED") - - @JvmField - val TOOL_DEFINITION_BAD_DEFINITION = of("TOOL_DEFINITION_BAD_DEFINITION") - - @JvmField - val TOOL_DEFINITION_BAD_INPUT_SCHEMA = of("TOOL_DEFINITION_BAD_INPUT_SCHEMA") - - @JvmField - val TOOL_DEFINITION_BAD_OUTPUT_SCHEMA = of("TOOL_DEFINITION_BAD_OUTPUT_SCHEMA") - - @JvmField val TOOL_REQUIREMENTS_NOT_MET = of("TOOL_REQUIREMENTS_NOT_MET") - - @JvmField val TOOL_RUNTIME_BAD_INPUT_VALUE = of("TOOL_RUNTIME_BAD_INPUT_VALUE") - - @JvmField - val TOOL_RUNTIME_BAD_OUTPUT_VALUE = of("TOOL_RUNTIME_BAD_OUTPUT_VALUE") - - @JvmField val TOOL_RUNTIME_RETRY = of("TOOL_RUNTIME_RETRY") - - @JvmField - val TOOL_RUNTIME_CONTEXT_REQUIRED = of("TOOL_RUNTIME_CONTEXT_REQUIRED") - - @JvmField val TOOL_RUNTIME_FATAL = of("TOOL_RUNTIME_FATAL") - - @JvmField val UPSTREAM_RUNTIME_BAD_REQUEST = of("UPSTREAM_RUNTIME_BAD_REQUEST") - - @JvmField val UPSTREAM_RUNTIME_AUTH_ERROR = of("UPSTREAM_RUNTIME_AUTH_ERROR") - - @JvmField val UPSTREAM_RUNTIME_NOT_FOUND = of("UPSTREAM_RUNTIME_NOT_FOUND") - - @JvmField - val UPSTREAM_RUNTIME_VALIDATION_ERROR = of("UPSTREAM_RUNTIME_VALIDATION_ERROR") - - @JvmField val UPSTREAM_RUNTIME_RATE_LIMIT = of("UPSTREAM_RUNTIME_RATE_LIMIT") - - @JvmField - val UPSTREAM_RUNTIME_SERVER_ERROR = of("UPSTREAM_RUNTIME_SERVER_ERROR") - - @JvmField val UPSTREAM_RUNTIME_UNMAPPED = of("UPSTREAM_RUNTIME_UNMAPPED") - - @JvmField val UNKNOWN = of("UNKNOWN") - - @JvmStatic fun of(value: String) = Kind(JsonField.of(value)) - } - - /** An enum containing [Kind]'s known values. */ - enum class Known { - TOOLKIT_LOAD_FAILED, - TOOL_DEFINITION_BAD_DEFINITION, - TOOL_DEFINITION_BAD_INPUT_SCHEMA, - TOOL_DEFINITION_BAD_OUTPUT_SCHEMA, - TOOL_REQUIREMENTS_NOT_MET, - TOOL_RUNTIME_BAD_INPUT_VALUE, - TOOL_RUNTIME_BAD_OUTPUT_VALUE, - TOOL_RUNTIME_RETRY, - TOOL_RUNTIME_CONTEXT_REQUIRED, - TOOL_RUNTIME_FATAL, - UPSTREAM_RUNTIME_BAD_REQUEST, - UPSTREAM_RUNTIME_AUTH_ERROR, - UPSTREAM_RUNTIME_NOT_FOUND, - UPSTREAM_RUNTIME_VALIDATION_ERROR, - UPSTREAM_RUNTIME_RATE_LIMIT, - UPSTREAM_RUNTIME_SERVER_ERROR, - UPSTREAM_RUNTIME_UNMAPPED, - UNKNOWN, - } - - /** - * An enum containing [Kind]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [Kind] 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 { - TOOLKIT_LOAD_FAILED, - TOOL_DEFINITION_BAD_DEFINITION, - TOOL_DEFINITION_BAD_INPUT_SCHEMA, - TOOL_DEFINITION_BAD_OUTPUT_SCHEMA, - TOOL_REQUIREMENTS_NOT_MET, - TOOL_RUNTIME_BAD_INPUT_VALUE, - TOOL_RUNTIME_BAD_OUTPUT_VALUE, - TOOL_RUNTIME_RETRY, - TOOL_RUNTIME_CONTEXT_REQUIRED, - TOOL_RUNTIME_FATAL, - UPSTREAM_RUNTIME_BAD_REQUEST, - UPSTREAM_RUNTIME_AUTH_ERROR, - UPSTREAM_RUNTIME_NOT_FOUND, - UPSTREAM_RUNTIME_VALIDATION_ERROR, - UPSTREAM_RUNTIME_RATE_LIMIT, - UPSTREAM_RUNTIME_SERVER_ERROR, - UPSTREAM_RUNTIME_UNMAPPED, - UNKNOWN, - /** - * An enum member indicating that [Kind] 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) { - TOOLKIT_LOAD_FAILED -> Value.TOOLKIT_LOAD_FAILED - TOOL_DEFINITION_BAD_DEFINITION -> Value.TOOL_DEFINITION_BAD_DEFINITION - TOOL_DEFINITION_BAD_INPUT_SCHEMA -> Value.TOOL_DEFINITION_BAD_INPUT_SCHEMA - TOOL_DEFINITION_BAD_OUTPUT_SCHEMA -> Value.TOOL_DEFINITION_BAD_OUTPUT_SCHEMA - TOOL_REQUIREMENTS_NOT_MET -> Value.TOOL_REQUIREMENTS_NOT_MET - TOOL_RUNTIME_BAD_INPUT_VALUE -> Value.TOOL_RUNTIME_BAD_INPUT_VALUE - TOOL_RUNTIME_BAD_OUTPUT_VALUE -> Value.TOOL_RUNTIME_BAD_OUTPUT_VALUE - TOOL_RUNTIME_RETRY -> Value.TOOL_RUNTIME_RETRY - TOOL_RUNTIME_CONTEXT_REQUIRED -> Value.TOOL_RUNTIME_CONTEXT_REQUIRED - TOOL_RUNTIME_FATAL -> Value.TOOL_RUNTIME_FATAL - UPSTREAM_RUNTIME_BAD_REQUEST -> Value.UPSTREAM_RUNTIME_BAD_REQUEST - UPSTREAM_RUNTIME_AUTH_ERROR -> Value.UPSTREAM_RUNTIME_AUTH_ERROR - UPSTREAM_RUNTIME_NOT_FOUND -> Value.UPSTREAM_RUNTIME_NOT_FOUND - UPSTREAM_RUNTIME_VALIDATION_ERROR -> Value.UPSTREAM_RUNTIME_VALIDATION_ERROR - UPSTREAM_RUNTIME_RATE_LIMIT -> Value.UPSTREAM_RUNTIME_RATE_LIMIT - UPSTREAM_RUNTIME_SERVER_ERROR -> Value.UPSTREAM_RUNTIME_SERVER_ERROR - UPSTREAM_RUNTIME_UNMAPPED -> Value.UPSTREAM_RUNTIME_UNMAPPED - UNKNOWN -> Value.UNKNOWN - 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 ArcadeInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - TOOLKIT_LOAD_FAILED -> Known.TOOLKIT_LOAD_FAILED - TOOL_DEFINITION_BAD_DEFINITION -> Known.TOOL_DEFINITION_BAD_DEFINITION - TOOL_DEFINITION_BAD_INPUT_SCHEMA -> Known.TOOL_DEFINITION_BAD_INPUT_SCHEMA - TOOL_DEFINITION_BAD_OUTPUT_SCHEMA -> Known.TOOL_DEFINITION_BAD_OUTPUT_SCHEMA - TOOL_REQUIREMENTS_NOT_MET -> Known.TOOL_REQUIREMENTS_NOT_MET - TOOL_RUNTIME_BAD_INPUT_VALUE -> Known.TOOL_RUNTIME_BAD_INPUT_VALUE - TOOL_RUNTIME_BAD_OUTPUT_VALUE -> Known.TOOL_RUNTIME_BAD_OUTPUT_VALUE - TOOL_RUNTIME_RETRY -> Known.TOOL_RUNTIME_RETRY - TOOL_RUNTIME_CONTEXT_REQUIRED -> Known.TOOL_RUNTIME_CONTEXT_REQUIRED - TOOL_RUNTIME_FATAL -> Known.TOOL_RUNTIME_FATAL - UPSTREAM_RUNTIME_BAD_REQUEST -> Known.UPSTREAM_RUNTIME_BAD_REQUEST - UPSTREAM_RUNTIME_AUTH_ERROR -> Known.UPSTREAM_RUNTIME_AUTH_ERROR - UPSTREAM_RUNTIME_NOT_FOUND -> Known.UPSTREAM_RUNTIME_NOT_FOUND - UPSTREAM_RUNTIME_VALIDATION_ERROR -> Known.UPSTREAM_RUNTIME_VALIDATION_ERROR - UPSTREAM_RUNTIME_RATE_LIMIT -> Known.UPSTREAM_RUNTIME_RATE_LIMIT - UPSTREAM_RUNTIME_SERVER_ERROR -> Known.UPSTREAM_RUNTIME_SERVER_ERROR - UPSTREAM_RUNTIME_UNMAPPED -> Known.UPSTREAM_RUNTIME_UNMAPPED - UNKNOWN -> Known.UNKNOWN - else -> throw ArcadeInvalidDataException("Unknown Kind: $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 ArcadeInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - ArcadeInvalidDataException("Value is not a String") - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Kind && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - @NoAutoDetect - class Extra - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Extra = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Extra]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(extra: Extra) = apply { - additionalProperties = extra.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) - } - - fun build(): Extra = Extra(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Extra && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "Extra{additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Error && canRetry == other.canRetry && kind == other.kind && message == other.message && additionalPromptContent == other.additionalPromptContent && developerMessage == other.developerMessage && extra == other.extra && retryAfterMs == other.retryAfterMs && stacktrace == other.stacktrace && statusCode == other.statusCode && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(canRetry, kind, message, additionalPromptContent, developerMessage, extra, retryAfterMs, stacktrace, statusCode, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Error{canRetry=$canRetry, kind=$kind, message=$message, additionalPromptContent=$additionalPromptContent, developerMessage=$developerMessage, extra=$extra, retryAfterMs=$retryAfterMs, stacktrace=$stacktrace, statusCode=$statusCode, additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class Log - @JsonCreator - private constructor( - @JsonProperty("level") - @ExcludeMissing - private val level: JsonField = JsonMissing.of(), - @JsonProperty("message") - @ExcludeMissing - private val message: JsonField = JsonMissing.of(), - @JsonProperty("subtype") - @ExcludeMissing - private val subtype: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun level(): String = level.getRequired("level") - - fun message(): String = message.getRequired("message") - - fun subtype(): Optional = Optional.ofNullable(subtype.getNullable("subtype")) - - @JsonProperty("level") @ExcludeMissing fun _level(): JsonField = level - - @JsonProperty("message") @ExcludeMissing fun _message(): JsonField = message - - @JsonProperty("subtype") @ExcludeMissing fun _subtype(): JsonField = subtype - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Log = apply { - if (validated) { - return@apply - } - - level() - message() - subtype() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Log]. */ - class Builder internal constructor() { - - private var level: JsonField? = null - private var message: JsonField? = null - private var subtype: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(log: Log) = apply { - level = log.level - message = log.message - subtype = log.subtype - additionalProperties = log.additionalProperties.toMutableMap() - } - - fun level(level: String) = level(JsonField.of(level)) - - fun level(level: JsonField) = apply { this.level = level } - - fun message(message: String) = message(JsonField.of(message)) - - fun message(message: JsonField) = apply { this.message = message } - - fun subtype(subtype: String) = subtype(JsonField.of(subtype)) - - fun subtype(subtype: JsonField) = apply { this.subtype = subtype } - - 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) - } - - fun build(): Log = - Log( - checkRequired("level", level), - checkRequired("message", message), - subtype, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Log && level == other.level && message == other.message && subtype == other.subtype && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(level, message, subtype, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Log{level=$level, message=$message, subtype=$subtype, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Output && authorization == other.authorization && error == other.error && logs == other.logs && value == other.value && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(authorization, error, logs, value, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Output{authorization=$authorization, error=$error, logs=$logs, value=$value, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ExecuteToolResponse && id == other.id && duration == other.duration && executionId == other.executionId && executionType == other.executionType && finishedAt == other.finishedAt && output == other.output && runAt == other.runAt && status == other.status && success == other.success && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(id, duration, executionId, executionType, finishedAt, output, runAt, status, success, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ExecuteToolResponse{id=$id, duration=$duration, executionId=$executionId, executionType=$executionType, finishedAt=$finishedAt, output=$output, runAt=$runAt, status=$status, success=$success, additionalProperties=$additionalProperties}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/HealthSchema.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/HealthSchema.kt deleted file mode 100644 index 0569fb5..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/HealthSchema.kt +++ /dev/null @@ -1,109 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import java.util.Objects -import java.util.Optional - -@NoAutoDetect -class HealthSchema -@JsonCreator -private constructor( - @JsonProperty("healthy") - @ExcludeMissing - private val healthy: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), -) { - - fun healthy(): Optional = Optional.ofNullable(healthy.getNullable("healthy")) - - @JsonProperty("healthy") @ExcludeMissing fun _healthy(): JsonField = healthy - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): HealthSchema = apply { - if (validated) { - return@apply - } - - healthy() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [HealthSchema]. */ - class Builder internal constructor() { - - private var healthy: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(healthSchema: HealthSchema) = apply { - healthy = healthSchema.healthy - additionalProperties = healthSchema.additionalProperties.toMutableMap() - } - - fun healthy(healthy: Boolean) = healthy(JsonField.of(healthy)) - - fun healthy(healthy: JsonField) = apply { this.healthy = healthy } - - 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) - } - - fun build(): HealthSchema = HealthSchema(healthy, additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is HealthSchema && healthy == other.healthy && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(healthy, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "HealthSchema{healthy=$healthy, additionalProperties=$additionalProperties}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/SecretResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/SecretResponse.kt deleted file mode 100644 index a904140..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/SecretResponse.kt +++ /dev/null @@ -1,435 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.Enum -import dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import dev.arcade.errors.ArcadeInvalidDataException -import java.util.Objects -import java.util.Optional - -@NoAutoDetect -class SecretResponse -@JsonCreator -private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("binding") - @ExcludeMissing - private val binding: JsonField = JsonMissing.of(), - @JsonProperty("created_at") - @ExcludeMissing - private val createdAt: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("hint") @ExcludeMissing private val hint: JsonField = JsonMissing.of(), - @JsonProperty("key") @ExcludeMissing private val key: JsonField = JsonMissing.of(), - @JsonProperty("last_accessed_at") - @ExcludeMissing - private val lastAccessedAt: JsonField = JsonMissing.of(), - @JsonProperty("updated_at") - @ExcludeMissing - private val updatedAt: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), -) { - - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - fun binding(): Optional = Optional.ofNullable(binding.getNullable("binding")) - - fun createdAt(): Optional = Optional.ofNullable(createdAt.getNullable("created_at")) - - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) - - fun hint(): Optional = Optional.ofNullable(hint.getNullable("hint")) - - fun key(): Optional = Optional.ofNullable(key.getNullable("key")) - - fun lastAccessedAt(): Optional = - Optional.ofNullable(lastAccessedAt.getNullable("last_accessed_at")) - - fun updatedAt(): Optional = Optional.ofNullable(updatedAt.getNullable("updated_at")) - - @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - - @JsonProperty("binding") @ExcludeMissing fun _binding(): JsonField = binding - - @JsonProperty("created_at") @ExcludeMissing fun _createdAt(): JsonField = createdAt - - @JsonProperty("description") @ExcludeMissing fun _description(): JsonField = description - - @JsonProperty("hint") @ExcludeMissing fun _hint(): JsonField = hint - - @JsonProperty("key") @ExcludeMissing fun _key(): JsonField = key - - @JsonProperty("last_accessed_at") - @ExcludeMissing - fun _lastAccessedAt(): JsonField = lastAccessedAt - - @JsonProperty("updated_at") @ExcludeMissing fun _updatedAt(): JsonField = updatedAt - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SecretResponse = apply { - if (validated) { - return@apply - } - - id() - binding().ifPresent { it.validate() } - createdAt() - description() - hint() - key() - lastAccessedAt() - updatedAt() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [SecretResponse]. */ - class Builder internal constructor() { - - private var id: JsonField = JsonMissing.of() - private var binding: JsonField = JsonMissing.of() - private var createdAt: JsonField = JsonMissing.of() - private var description: JsonField = JsonMissing.of() - private var hint: JsonField = JsonMissing.of() - private var key: JsonField = JsonMissing.of() - private var lastAccessedAt: JsonField = JsonMissing.of() - private var updatedAt: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(secretResponse: SecretResponse) = apply { - id = secretResponse.id - binding = secretResponse.binding - createdAt = secretResponse.createdAt - description = secretResponse.description - hint = secretResponse.hint - key = secretResponse.key - lastAccessedAt = secretResponse.lastAccessedAt - updatedAt = secretResponse.updatedAt - additionalProperties = secretResponse.additionalProperties.toMutableMap() - } - - fun id(id: String) = id(JsonField.of(id)) - - fun id(id: JsonField) = apply { this.id = id } - - fun binding(binding: Binding) = binding(JsonField.of(binding)) - - fun binding(binding: JsonField) = apply { this.binding = binding } - - fun createdAt(createdAt: String) = createdAt(JsonField.of(createdAt)) - - fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } - - fun description(description: String) = description(JsonField.of(description)) - - fun description(description: JsonField) = apply { this.description = description } - - fun hint(hint: String) = hint(JsonField.of(hint)) - - fun hint(hint: JsonField) = apply { this.hint = hint } - - fun key(key: String) = key(JsonField.of(key)) - - fun key(key: JsonField) = apply { this.key = key } - - fun lastAccessedAt(lastAccessedAt: String) = lastAccessedAt(JsonField.of(lastAccessedAt)) - - fun lastAccessedAt(lastAccessedAt: JsonField) = apply { - this.lastAccessedAt = lastAccessedAt - } - - fun updatedAt(updatedAt: String) = updatedAt(JsonField.of(updatedAt)) - - 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) - } - - fun build(): SecretResponse = - SecretResponse( - id, - binding, - createdAt, - description, - hint, - key, - lastAccessedAt, - updatedAt, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class Binding - @JsonCreator - private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - - @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - - @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Binding = apply { - if (validated) { - return@apply - } - - id() - type() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Binding]. */ - class Builder internal constructor() { - - private var id: JsonField = JsonMissing.of() - private var type: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(binding: Binding) = apply { - id = binding.id - type = binding.type - additionalProperties = binding.additionalProperties.toMutableMap() - } - - fun id(id: String) = id(JsonField.of(id)) - - fun id(id: JsonField) = apply { this.id = id } - - fun type(type: Type) = type(JsonField.of(type)) - - 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) - } - - fun build(): Binding = Binding(id, type, additionalProperties.toImmutable()) - } - - 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 STATIC = of("static") - - @JvmField val TENANT = of("tenant") - - @JvmField val PROJECT = of("project") - - @JvmField val ACCOUNT = of("account") - - @JvmStatic fun of(value: String) = Type(JsonField.of(value)) - } - - /** An enum containing [Type]'s known values. */ - enum class Known { - STATIC, - TENANT, - PROJECT, - ACCOUNT, - } - - /** - * 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 { - STATIC, - TENANT, - PROJECT, - ACCOUNT, - /** 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) { - STATIC -> Value.STATIC - TENANT -> Value.TENANT - PROJECT -> Value.PROJECT - ACCOUNT -> Value.ACCOUNT - 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 ArcadeInvalidDataException if this class instance's value is a not a known - * member. - */ - fun known(): Known = - when (this) { - STATIC -> Known.STATIC - TENANT -> Known.TENANT - PROJECT -> Known.PROJECT - ACCOUNT -> Known.ACCOUNT - else -> throw ArcadeInvalidDataException("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 ArcadeInvalidDataException if this class instance's value does not have the - * expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - ArcadeInvalidDataException("Value is not a String") - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Type && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Binding && id == other.id && type == other.type && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(id, type, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Binding{id=$id, type=$type, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is SecretResponse && id == other.id && binding == other.binding && createdAt == other.createdAt && description == other.description && hint == other.hint && key == other.key && lastAccessedAt == other.lastAccessedAt && updatedAt == other.updatedAt && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(id, binding, createdAt, description, hint, key, lastAccessedAt, updatedAt, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "SecretResponse{id=$id, binding=$binding, createdAt=$createdAt, description=$description, hint=$hint, key=$key, lastAccessedAt=$lastAccessedAt, updatedAt=$updatedAt, additionalProperties=$additionalProperties}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolDefinition.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolDefinition.kt deleted file mode 100644 index 394ab44..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolDefinition.kt +++ /dev/null @@ -1,1739 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.Enum -import dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.checkRequired -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import dev.arcade.errors.ArcadeInvalidDataException -import java.util.Objects -import java.util.Optional - -@NoAutoDetect -class ToolDefinition -@JsonCreator -private constructor( - @JsonProperty("fully_qualified_name") - @ExcludeMissing - private val fullyQualifiedName: JsonField = JsonMissing.of(), - @JsonProperty("input") @ExcludeMissing private val input: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing private val name: JsonField = JsonMissing.of(), - @JsonProperty("qualified_name") - @ExcludeMissing - private val qualifiedName: JsonField = JsonMissing.of(), - @JsonProperty("toolkit") - @ExcludeMissing - private val toolkit: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("formatted_schema") - @ExcludeMissing - private val formattedSchema: JsonField = JsonMissing.of(), - @JsonProperty("output") - @ExcludeMissing - private val output: JsonField = JsonMissing.of(), - @JsonProperty("requirements") - @ExcludeMissing - private val requirements: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), -) { - - fun fullyQualifiedName(): String = fullyQualifiedName.getRequired("fully_qualified_name") - - fun input(): Input = input.getRequired("input") - - fun name(): String = name.getRequired("name") - - fun qualifiedName(): String = qualifiedName.getRequired("qualified_name") - - fun toolkit(): Toolkit = toolkit.getRequired("toolkit") - - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) - - fun formattedSchema(): Optional = - Optional.ofNullable(formattedSchema.getNullable("formatted_schema")) - - fun output(): Optional = Optional.ofNullable(output.getNullable("output")) - - fun requirements(): Optional = - Optional.ofNullable(requirements.getNullable("requirements")) - - @JsonProperty("fully_qualified_name") - @ExcludeMissing - fun _fullyQualifiedName(): JsonField = fullyQualifiedName - - @JsonProperty("input") @ExcludeMissing fun _input(): JsonField = input - - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - - @JsonProperty("qualified_name") - @ExcludeMissing - fun _qualifiedName(): JsonField = qualifiedName - - @JsonProperty("toolkit") @ExcludeMissing fun _toolkit(): JsonField = toolkit - - @JsonProperty("description") @ExcludeMissing fun _description(): JsonField = description - - @JsonProperty("formatted_schema") - @ExcludeMissing - fun _formattedSchema(): JsonField = formattedSchema - - @JsonProperty("output") @ExcludeMissing fun _output(): JsonField = output - - @JsonProperty("requirements") - @ExcludeMissing - fun _requirements(): JsonField = requirements - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ToolDefinition = apply { - if (validated) { - return@apply - } - - fullyQualifiedName() - input().validate() - name() - qualifiedName() - toolkit().validate() - description() - formattedSchema().ifPresent { it.validate() } - output().ifPresent { it.validate() } - requirements().ifPresent { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ToolDefinition]. */ - class Builder internal constructor() { - - private var fullyQualifiedName: JsonField? = null - private var input: JsonField? = null - private var name: JsonField? = null - private var qualifiedName: JsonField? = null - private var toolkit: JsonField? = null - private var description: JsonField = JsonMissing.of() - private var formattedSchema: JsonField = JsonMissing.of() - private var output: JsonField = JsonMissing.of() - private var requirements: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(toolDefinition: ToolDefinition) = apply { - fullyQualifiedName = toolDefinition.fullyQualifiedName - input = toolDefinition.input - name = toolDefinition.name - qualifiedName = toolDefinition.qualifiedName - toolkit = toolDefinition.toolkit - description = toolDefinition.description - formattedSchema = toolDefinition.formattedSchema - output = toolDefinition.output - requirements = toolDefinition.requirements - additionalProperties = toolDefinition.additionalProperties.toMutableMap() - } - - fun fullyQualifiedName(fullyQualifiedName: String) = - fullyQualifiedName(JsonField.of(fullyQualifiedName)) - - fun fullyQualifiedName(fullyQualifiedName: JsonField) = apply { - this.fullyQualifiedName = fullyQualifiedName - } - - fun input(input: Input) = input(JsonField.of(input)) - - fun input(input: JsonField) = apply { this.input = input } - - fun name(name: String) = name(JsonField.of(name)) - - fun name(name: JsonField) = apply { this.name = name } - - fun qualifiedName(qualifiedName: String) = qualifiedName(JsonField.of(qualifiedName)) - - fun qualifiedName(qualifiedName: JsonField) = apply { - this.qualifiedName = qualifiedName - } - - fun toolkit(toolkit: Toolkit) = toolkit(JsonField.of(toolkit)) - - fun toolkit(toolkit: JsonField) = apply { this.toolkit = toolkit } - - fun description(description: String) = description(JsonField.of(description)) - - fun description(description: JsonField) = apply { this.description = description } - - fun formattedSchema(formattedSchema: FormattedSchema) = - formattedSchema(JsonField.of(formattedSchema)) - - fun formattedSchema(formattedSchema: JsonField) = apply { - this.formattedSchema = formattedSchema - } - - fun output(output: Output) = output(JsonField.of(output)) - - fun output(output: JsonField) = apply { this.output = output } - - fun requirements(requirements: Requirements) = requirements(JsonField.of(requirements)) - - fun requirements(requirements: JsonField) = apply { - this.requirements = requirements - } - - 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) - } - - fun build(): ToolDefinition = - ToolDefinition( - checkRequired("fullyQualifiedName", fullyQualifiedName), - checkRequired("input", input), - checkRequired("name", name), - checkRequired("qualifiedName", qualifiedName), - checkRequired("toolkit", toolkit), - description, - formattedSchema, - output, - requirements, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class Input - @JsonCreator - private constructor( - @JsonProperty("parameters") - @ExcludeMissing - private val parameters: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun parameters(): Optional> = - Optional.ofNullable(parameters.getNullable("parameters")) - - @JsonProperty("parameters") - @ExcludeMissing - fun _parameters(): JsonField> = parameters - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Input = apply { - if (validated) { - return@apply - } - - parameters().ifPresent { it.forEach { it.validate() } } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Input]. */ - class Builder internal constructor() { - - private var parameters: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(input: Input) = apply { - parameters = input.parameters.map { it.toMutableList() } - additionalProperties = input.additionalProperties.toMutableMap() - } - - fun parameters(parameters: List) = parameters(JsonField.of(parameters)) - - fun parameters(parameters: JsonField>) = apply { - this.parameters = parameters.map { it.toMutableList() } - } - - fun addParameter(parameter: Parameter) = apply { - parameters = - (parameters ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(parameter) - } - } - - 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) - } - - fun build(): Input = - Input( - (parameters ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class Parameter - @JsonCreator - private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("value_schema") - @ExcludeMissing - private val valueSchema: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("inferrable") - @ExcludeMissing - private val inferrable: JsonField = JsonMissing.of(), - @JsonProperty("required") - @ExcludeMissing - private val required: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun name(): String = name.getRequired("name") - - fun valueSchema(): ValueSchema = valueSchema.getRequired("value_schema") - - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) - - fun inferrable(): Optional = - Optional.ofNullable(inferrable.getNullable("inferrable")) - - fun required(): Optional = - Optional.ofNullable(required.getNullable("required")) - - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - - @JsonProperty("value_schema") - @ExcludeMissing - fun _valueSchema(): JsonField = valueSchema - - @JsonProperty("description") - @ExcludeMissing - fun _description(): JsonField = description - - @JsonProperty("inferrable") - @ExcludeMissing - fun _inferrable(): JsonField = inferrable - - @JsonProperty("required") @ExcludeMissing fun _required(): JsonField = required - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Parameter = apply { - if (validated) { - return@apply - } - - name() - valueSchema().validate() - description() - inferrable() - required() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Parameter]. */ - class Builder internal constructor() { - - private var name: JsonField? = null - private var valueSchema: JsonField? = null - private var description: JsonField = JsonMissing.of() - private var inferrable: JsonField = JsonMissing.of() - private var required: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(parameter: Parameter) = apply { - name = parameter.name - valueSchema = parameter.valueSchema - description = parameter.description - inferrable = parameter.inferrable - required = parameter.required - additionalProperties = parameter.additionalProperties.toMutableMap() - } - - fun name(name: String) = name(JsonField.of(name)) - - fun name(name: JsonField) = apply { this.name = name } - - fun valueSchema(valueSchema: ValueSchema) = valueSchema(JsonField.of(valueSchema)) - - fun valueSchema(valueSchema: JsonField) = apply { - this.valueSchema = valueSchema - } - - fun description(description: String) = description(JsonField.of(description)) - - fun description(description: JsonField) = apply { - this.description = description - } - - fun inferrable(inferrable: Boolean) = inferrable(JsonField.of(inferrable)) - - fun inferrable(inferrable: JsonField) = apply { - this.inferrable = inferrable - } - - fun required(required: Boolean) = required(JsonField.of(required)) - - fun required(required: JsonField) = apply { this.required = required } - - 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) - } - - fun build(): Parameter = - Parameter( - checkRequired("name", name), - checkRequired("valueSchema", valueSchema), - description, - inferrable, - required, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Parameter && name == other.name && valueSchema == other.valueSchema && description == other.description && inferrable == other.inferrable && required == other.required && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(name, valueSchema, description, inferrable, required, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Parameter{name=$name, valueSchema=$valueSchema, description=$description, inferrable=$inferrable, required=$required, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Input && parameters == other.parameters && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(parameters, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Input{parameters=$parameters, additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class Toolkit - @JsonCreator - private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("version") - @ExcludeMissing - private val version: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun name(): String = name.getRequired("name") - - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) - - fun version(): Optional = Optional.ofNullable(version.getNullable("version")) - - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - - @JsonProperty("description") - @ExcludeMissing - fun _description(): JsonField = description - - @JsonProperty("version") @ExcludeMissing fun _version(): JsonField = version - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Toolkit = apply { - if (validated) { - return@apply - } - - name() - description() - version() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Toolkit]. */ - class Builder internal constructor() { - - private var name: JsonField? = null - private var description: JsonField = JsonMissing.of() - private var version: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(toolkit: Toolkit) = apply { - name = toolkit.name - description = toolkit.description - version = toolkit.version - additionalProperties = toolkit.additionalProperties.toMutableMap() - } - - fun name(name: String) = name(JsonField.of(name)) - - fun name(name: JsonField) = apply { this.name = name } - - fun description(description: String) = description(JsonField.of(description)) - - fun description(description: JsonField) = apply { - this.description = description - } - - fun version(version: String) = version(JsonField.of(version)) - - fun version(version: JsonField) = apply { this.version = version } - - 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) - } - - fun build(): Toolkit = - Toolkit( - checkRequired("name", name), - description, - version, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Toolkit && name == other.name && description == other.description && version == other.version && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(name, description, version, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Toolkit{name=$name, description=$description, version=$version, additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class FormattedSchema - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): FormattedSchema = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [FormattedSchema]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(formattedSchema: FormattedSchema) = apply { - additionalProperties = formattedSchema.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) - } - - fun build(): FormattedSchema = FormattedSchema(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is FormattedSchema && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "FormattedSchema{additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class Output - @JsonCreator - private constructor( - @JsonProperty("available_modes") - @ExcludeMissing - private val availableModes: JsonField> = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("value_schema") - @ExcludeMissing - private val valueSchema: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun availableModes(): Optional> = - Optional.ofNullable(availableModes.getNullable("available_modes")) - - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) - - fun valueSchema(): Optional = - Optional.ofNullable(valueSchema.getNullable("value_schema")) - - @JsonProperty("available_modes") - @ExcludeMissing - fun _availableModes(): JsonField> = availableModes - - @JsonProperty("description") - @ExcludeMissing - fun _description(): JsonField = description - - @JsonProperty("value_schema") - @ExcludeMissing - fun _valueSchema(): JsonField = valueSchema - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Output = apply { - if (validated) { - return@apply - } - - availableModes() - description() - valueSchema().ifPresent { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Output]. */ - class Builder internal constructor() { - - private var availableModes: JsonField>? = null - private var description: JsonField = JsonMissing.of() - private var valueSchema: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(output: Output) = apply { - availableModes = output.availableModes.map { it.toMutableList() } - description = output.description - valueSchema = output.valueSchema - additionalProperties = output.additionalProperties.toMutableMap() - } - - fun availableModes(availableModes: List) = - availableModes(JsonField.of(availableModes)) - - fun availableModes(availableModes: JsonField>) = apply { - this.availableModes = availableModes.map { it.toMutableList() } - } - - fun addAvailableMode(availableMode: String) = apply { - availableModes = - (availableModes ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(availableMode) - } - } - - fun description(description: String) = description(JsonField.of(description)) - - fun description(description: JsonField) = apply { - this.description = description - } - - fun valueSchema(valueSchema: ValueSchema) = valueSchema(JsonField.of(valueSchema)) - - fun valueSchema(valueSchema: JsonField) = apply { - this.valueSchema = valueSchema - } - - 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) - } - - fun build(): Output = - Output( - (availableModes ?: JsonMissing.of()).map { it.toImmutable() }, - description, - valueSchema, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Output && availableModes == other.availableModes && description == other.description && valueSchema == other.valueSchema && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(availableModes, description, valueSchema, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Output{availableModes=$availableModes, description=$description, valueSchema=$valueSchema, additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class Requirements - @JsonCreator - private constructor( - @JsonProperty("authorization") - @ExcludeMissing - private val authorization: JsonField = JsonMissing.of(), - @JsonProperty("met") @ExcludeMissing private val met: JsonField = JsonMissing.of(), - @JsonProperty("secrets") - @ExcludeMissing - private val secrets: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun authorization(): Optional = - Optional.ofNullable(authorization.getNullable("authorization")) - - fun met(): Optional = Optional.ofNullable(met.getNullable("met")) - - fun secrets(): Optional> = Optional.ofNullable(secrets.getNullable("secrets")) - - @JsonProperty("authorization") - @ExcludeMissing - fun _authorization(): JsonField = authorization - - @JsonProperty("met") @ExcludeMissing fun _met(): JsonField = met - - @JsonProperty("secrets") @ExcludeMissing fun _secrets(): JsonField> = secrets - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Requirements = apply { - if (validated) { - return@apply - } - - authorization().ifPresent { it.validate() } - met() - secrets().ifPresent { it.forEach { it.validate() } } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Requirements]. */ - class Builder internal constructor() { - - private var authorization: JsonField = JsonMissing.of() - private var met: JsonField = JsonMissing.of() - private var secrets: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(requirements: Requirements) = apply { - authorization = requirements.authorization - met = requirements.met - secrets = requirements.secrets.map { it.toMutableList() } - additionalProperties = requirements.additionalProperties.toMutableMap() - } - - fun authorization(authorization: Authorization) = - authorization(JsonField.of(authorization)) - - fun authorization(authorization: JsonField) = apply { - this.authorization = authorization - } - - fun met(met: Boolean) = met(JsonField.of(met)) - - fun met(met: JsonField) = apply { this.met = met } - - fun secrets(secrets: List) = secrets(JsonField.of(secrets)) - - fun secrets(secrets: JsonField>) = apply { - this.secrets = secrets.map { it.toMutableList() } - } - - fun addSecret(secret: Secret) = apply { - secrets = - (secrets ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(secret) - } - } - - 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) - } - - fun build(): Requirements = - Requirements( - authorization, - met, - (secrets ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class Authorization - @JsonCreator - private constructor( - @JsonProperty("id") - @ExcludeMissing - private val id: JsonField = JsonMissing.of(), - @JsonProperty("oauth2") - @ExcludeMissing - private val oauth2: JsonField = JsonMissing.of(), - @JsonProperty("provider_id") - @ExcludeMissing - private val providerId: JsonField = JsonMissing.of(), - @JsonProperty("provider_type") - @ExcludeMissing - private val providerType: JsonField = JsonMissing.of(), - @JsonProperty("status") - @ExcludeMissing - private val status: JsonField = JsonMissing.of(), - @JsonProperty("status_reason") - @ExcludeMissing - private val statusReason: JsonField = JsonMissing.of(), - @JsonProperty("token_status") - @ExcludeMissing - private val tokenStatus: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - fun oauth2(): Optional = Optional.ofNullable(oauth2.getNullable("oauth2")) - - fun providerId(): Optional = - Optional.ofNullable(providerId.getNullable("provider_id")) - - fun providerType(): Optional = - Optional.ofNullable(providerType.getNullable("provider_type")) - - fun status(): Optional = Optional.ofNullable(status.getNullable("status")) - - fun statusReason(): Optional = - Optional.ofNullable(statusReason.getNullable("status_reason")) - - fun tokenStatus(): Optional = - Optional.ofNullable(tokenStatus.getNullable("token_status")) - - @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - - @JsonProperty("oauth2") @ExcludeMissing fun _oauth2(): JsonField = oauth2 - - @JsonProperty("provider_id") - @ExcludeMissing - fun _providerId(): JsonField = providerId - - @JsonProperty("provider_type") - @ExcludeMissing - fun _providerType(): JsonField = providerType - - @JsonProperty("status") @ExcludeMissing fun _status(): JsonField = status - - @JsonProperty("status_reason") - @ExcludeMissing - fun _statusReason(): JsonField = statusReason - - @JsonProperty("token_status") - @ExcludeMissing - fun _tokenStatus(): JsonField = tokenStatus - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Authorization = apply { - if (validated) { - return@apply - } - - id() - oauth2().ifPresent { it.validate() } - providerId() - providerType() - status() - statusReason() - tokenStatus() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Authorization]. */ - class Builder internal constructor() { - - private var id: JsonField = JsonMissing.of() - private var oauth2: JsonField = JsonMissing.of() - private var providerId: JsonField = JsonMissing.of() - private var providerType: JsonField = JsonMissing.of() - private var status: JsonField = JsonMissing.of() - private var statusReason: JsonField = JsonMissing.of() - private var tokenStatus: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(authorization: Authorization) = apply { - id = authorization.id - oauth2 = authorization.oauth2 - providerId = authorization.providerId - providerType = authorization.providerType - status = authorization.status - statusReason = authorization.statusReason - tokenStatus = authorization.tokenStatus - additionalProperties = authorization.additionalProperties.toMutableMap() - } - - fun id(id: String) = id(JsonField.of(id)) - - fun id(id: JsonField) = apply { this.id = id } - - fun oauth2(oauth2: Oauth2) = oauth2(JsonField.of(oauth2)) - - fun oauth2(oauth2: JsonField) = apply { this.oauth2 = oauth2 } - - fun providerId(providerId: String) = providerId(JsonField.of(providerId)) - - fun providerId(providerId: JsonField) = apply { - this.providerId = providerId - } - - fun providerType(providerType: String) = providerType(JsonField.of(providerType)) - - fun providerType(providerType: JsonField) = apply { - this.providerType = providerType - } - - fun status(status: Status) = status(JsonField.of(status)) - - fun status(status: JsonField) = apply { this.status = status } - - fun statusReason(statusReason: String) = statusReason(JsonField.of(statusReason)) - - fun statusReason(statusReason: JsonField) = apply { - this.statusReason = statusReason - } - - fun tokenStatus(tokenStatus: TokenStatus) = tokenStatus(JsonField.of(tokenStatus)) - - fun tokenStatus(tokenStatus: JsonField) = apply { - this.tokenStatus = tokenStatus - } - - 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) - } - - fun build(): Authorization = - Authorization( - id, - oauth2, - providerId, - providerType, - status, - statusReason, - tokenStatus, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class Oauth2 - @JsonCreator - private constructor( - @JsonProperty("scopes") - @ExcludeMissing - private val scopes: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun scopes(): Optional> = - Optional.ofNullable(scopes.getNullable("scopes")) - - @JsonProperty("scopes") - @ExcludeMissing - fun _scopes(): JsonField> = scopes - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Oauth2 = apply { - if (validated) { - return@apply - } - - scopes() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Oauth2]. */ - class Builder internal constructor() { - - private var scopes: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(oauth2: Oauth2) = apply { - scopes = oauth2.scopes.map { it.toMutableList() } - additionalProperties = oauth2.additionalProperties.toMutableMap() - } - - fun scopes(scopes: List) = scopes(JsonField.of(scopes)) - - fun scopes(scopes: JsonField>) = apply { - this.scopes = scopes.map { it.toMutableList() } - } - - fun addScope(scope: String) = apply { - scopes = - (scopes ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(scope) - } - } - - 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) - } - - fun build(): Oauth2 = - Oauth2( - (scopes ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Oauth2 && scopes == other.scopes && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(scopes, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Oauth2{scopes=$scopes, additionalProperties=$additionalProperties}" - } - - 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 ACTIVE = of("active") - - @JvmField val INACTIVE = of("inactive") - - @JvmStatic fun of(value: String) = Status(JsonField.of(value)) - } - - /** An enum containing [Status]'s known values. */ - enum class Known { - ACTIVE, - INACTIVE, - } - - /** - * 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 { - ACTIVE, - INACTIVE, - /** - * 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) { - ACTIVE -> Value.ACTIVE - INACTIVE -> Value.INACTIVE - 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 ArcadeInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - ACTIVE -> Known.ACTIVE - INACTIVE -> Known.INACTIVE - else -> throw ArcadeInvalidDataException("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 ArcadeInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - ArcadeInvalidDataException("Value is not a String") - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Status && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - class TokenStatus - @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 NOT_STARTED = of("not_started") - - @JvmField val PENDING = of("pending") - - @JvmField val COMPLETED = of("completed") - - @JvmField val FAILED = of("failed") - - @JvmStatic fun of(value: String) = TokenStatus(JsonField.of(value)) - } - - /** An enum containing [TokenStatus]'s known values. */ - enum class Known { - NOT_STARTED, - PENDING, - COMPLETED, - FAILED, - } - - /** - * An enum containing [TokenStatus]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [TokenStatus] 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 { - NOT_STARTED, - PENDING, - COMPLETED, - FAILED, - /** - * An enum member indicating that [TokenStatus] 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) { - NOT_STARTED -> Value.NOT_STARTED - PENDING -> Value.PENDING - COMPLETED -> Value.COMPLETED - 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 ArcadeInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - NOT_STARTED -> Known.NOT_STARTED - PENDING -> Known.PENDING - COMPLETED -> Known.COMPLETED - FAILED -> Known.FAILED - else -> throw ArcadeInvalidDataException("Unknown TokenStatus: $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 ArcadeInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - ArcadeInvalidDataException("Value is not a String") - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is TokenStatus && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Authorization && id == other.id && oauth2 == other.oauth2 && providerId == other.providerId && providerType == other.providerType && status == other.status && statusReason == other.statusReason && tokenStatus == other.tokenStatus && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(id, oauth2, providerId, providerType, status, statusReason, tokenStatus, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Authorization{id=$id, oauth2=$oauth2, providerId=$providerId, providerType=$providerType, status=$status, statusReason=$statusReason, tokenStatus=$tokenStatus, additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class Secret - @JsonCreator - private constructor( - @JsonProperty("key") - @ExcludeMissing - private val key: JsonField = JsonMissing.of(), - @JsonProperty("met") - @ExcludeMissing - private val met: JsonField = JsonMissing.of(), - @JsonProperty("status_reason") - @ExcludeMissing - private val statusReason: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun key(): String = key.getRequired("key") - - fun met(): Optional = Optional.ofNullable(met.getNullable("met")) - - fun statusReason(): Optional = - Optional.ofNullable(statusReason.getNullable("status_reason")) - - @JsonProperty("key") @ExcludeMissing fun _key(): JsonField = key - - @JsonProperty("met") @ExcludeMissing fun _met(): JsonField = met - - @JsonProperty("status_reason") - @ExcludeMissing - fun _statusReason(): JsonField = statusReason - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Secret = apply { - if (validated) { - return@apply - } - - key() - met() - statusReason() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Secret]. */ - class Builder internal constructor() { - - private var key: JsonField? = null - private var met: JsonField = JsonMissing.of() - private var statusReason: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(secret: Secret) = apply { - key = secret.key - met = secret.met - statusReason = secret.statusReason - additionalProperties = secret.additionalProperties.toMutableMap() - } - - fun key(key: String) = key(JsonField.of(key)) - - fun key(key: JsonField) = apply { this.key = key } - - fun met(met: Boolean) = met(JsonField.of(met)) - - fun met(met: JsonField) = apply { this.met = met } - - fun statusReason(statusReason: String) = statusReason(JsonField.of(statusReason)) - - fun statusReason(statusReason: JsonField) = apply { - this.statusReason = statusReason - } - - 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) - } - - fun build(): Secret = - Secret( - checkRequired("key", key), - met, - statusReason, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Secret && key == other.key && met == other.met && statusReason == other.statusReason && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(key, met, statusReason, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Secret{key=$key, met=$met, statusReason=$statusReason, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Requirements && authorization == other.authorization && met == other.met && secrets == other.secrets && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(authorization, met, secrets, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Requirements{authorization=$authorization, met=$met, secrets=$secrets, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ToolDefinition && fullyQualifiedName == other.fullyQualifiedName && input == other.input && name == other.name && qualifiedName == other.qualifiedName && toolkit == other.toolkit && description == other.description && formattedSchema == other.formattedSchema && output == other.output && requirements == other.requirements && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(fullyQualifiedName, input, name, qualifiedName, toolkit, description, formattedSchema, output, requirements, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ToolDefinition{fullyQualifiedName=$fullyQualifiedName, input=$input, name=$name, qualifiedName=$qualifiedName, toolkit=$toolkit, description=$description, formattedSchema=$formattedSchema, output=$output, requirements=$requirements, additionalProperties=$additionalProperties}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolExecution.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolExecution.kt deleted file mode 100644 index b1f5b64..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolExecution.kt +++ /dev/null @@ -1,293 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import java.util.Objects -import java.util.Optional - -@NoAutoDetect -class ToolExecution -@JsonCreator -private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("created_at") - @ExcludeMissing - private val createdAt: JsonField = JsonMissing.of(), - @JsonProperty("execution_status") - @ExcludeMissing - private val executionStatus: JsonField = JsonMissing.of(), - @JsonProperty("execution_type") - @ExcludeMissing - private val executionType: JsonField = JsonMissing.of(), - @JsonProperty("finished_at") - @ExcludeMissing - private val finishedAt: JsonField = JsonMissing.of(), - @JsonProperty("run_at") @ExcludeMissing private val runAt: JsonField = JsonMissing.of(), - @JsonProperty("started_at") - @ExcludeMissing - private val startedAt: JsonField = JsonMissing.of(), - @JsonProperty("tool_name") - @ExcludeMissing - private val toolName: JsonField = JsonMissing.of(), - @JsonProperty("toolkit_name") - @ExcludeMissing - private val toolkitName: JsonField = JsonMissing.of(), - @JsonProperty("toolkit_version") - @ExcludeMissing - private val toolkitVersion: JsonField = JsonMissing.of(), - @JsonProperty("updated_at") - @ExcludeMissing - private val updatedAt: JsonField = JsonMissing.of(), - @JsonProperty("user_id") - @ExcludeMissing - private val userId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), -) { - - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - fun createdAt(): Optional = Optional.ofNullable(createdAt.getNullable("created_at")) - - fun executionStatus(): Optional = - Optional.ofNullable(executionStatus.getNullable("execution_status")) - - fun executionType(): Optional = - Optional.ofNullable(executionType.getNullable("execution_type")) - - fun finishedAt(): Optional = Optional.ofNullable(finishedAt.getNullable("finished_at")) - - fun runAt(): Optional = Optional.ofNullable(runAt.getNullable("run_at")) - - fun startedAt(): Optional = Optional.ofNullable(startedAt.getNullable("started_at")) - - fun toolName(): Optional = Optional.ofNullable(toolName.getNullable("tool_name")) - - fun toolkitName(): Optional = - Optional.ofNullable(toolkitName.getNullable("toolkit_name")) - - fun toolkitVersion(): Optional = - Optional.ofNullable(toolkitVersion.getNullable("toolkit_version")) - - fun updatedAt(): Optional = Optional.ofNullable(updatedAt.getNullable("updated_at")) - - fun userId(): Optional = Optional.ofNullable(userId.getNullable("user_id")) - - @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - - @JsonProperty("created_at") @ExcludeMissing fun _createdAt(): JsonField = createdAt - - @JsonProperty("execution_status") - @ExcludeMissing - fun _executionStatus(): JsonField = executionStatus - - @JsonProperty("execution_type") - @ExcludeMissing - fun _executionType(): JsonField = executionType - - @JsonProperty("finished_at") @ExcludeMissing fun _finishedAt(): JsonField = finishedAt - - @JsonProperty("run_at") @ExcludeMissing fun _runAt(): JsonField = runAt - - @JsonProperty("started_at") @ExcludeMissing fun _startedAt(): JsonField = startedAt - - @JsonProperty("tool_name") @ExcludeMissing fun _toolName(): JsonField = toolName - - @JsonProperty("toolkit_name") - @ExcludeMissing - fun _toolkitName(): JsonField = toolkitName - - @JsonProperty("toolkit_version") - @ExcludeMissing - fun _toolkitVersion(): JsonField = toolkitVersion - - @JsonProperty("updated_at") @ExcludeMissing fun _updatedAt(): JsonField = updatedAt - - @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ToolExecution = apply { - if (validated) { - return@apply - } - - id() - createdAt() - executionStatus() - executionType() - finishedAt() - runAt() - startedAt() - toolName() - toolkitName() - toolkitVersion() - updatedAt() - userId() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ToolExecution]. */ - class Builder internal constructor() { - - private var id: JsonField = JsonMissing.of() - private var createdAt: JsonField = JsonMissing.of() - private var executionStatus: JsonField = JsonMissing.of() - private var executionType: JsonField = JsonMissing.of() - private var finishedAt: JsonField = JsonMissing.of() - private var runAt: JsonField = JsonMissing.of() - private var startedAt: JsonField = JsonMissing.of() - private var toolName: JsonField = JsonMissing.of() - private var toolkitName: JsonField = JsonMissing.of() - private var toolkitVersion: JsonField = JsonMissing.of() - private var updatedAt: JsonField = JsonMissing.of() - private var userId: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(toolExecution: ToolExecution) = apply { - id = toolExecution.id - createdAt = toolExecution.createdAt - executionStatus = toolExecution.executionStatus - executionType = toolExecution.executionType - finishedAt = toolExecution.finishedAt - runAt = toolExecution.runAt - startedAt = toolExecution.startedAt - toolName = toolExecution.toolName - toolkitName = toolExecution.toolkitName - toolkitVersion = toolExecution.toolkitVersion - updatedAt = toolExecution.updatedAt - userId = toolExecution.userId - additionalProperties = toolExecution.additionalProperties.toMutableMap() - } - - fun id(id: String) = id(JsonField.of(id)) - - fun id(id: JsonField) = apply { this.id = id } - - fun createdAt(createdAt: String) = createdAt(JsonField.of(createdAt)) - - fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } - - fun executionStatus(executionStatus: String) = - executionStatus(JsonField.of(executionStatus)) - - fun executionStatus(executionStatus: JsonField) = apply { - this.executionStatus = executionStatus - } - - fun executionType(executionType: String) = executionType(JsonField.of(executionType)) - - fun executionType(executionType: JsonField) = apply { - this.executionType = executionType - } - - fun finishedAt(finishedAt: String) = finishedAt(JsonField.of(finishedAt)) - - fun finishedAt(finishedAt: JsonField) = apply { this.finishedAt = finishedAt } - - fun runAt(runAt: String) = runAt(JsonField.of(runAt)) - - fun runAt(runAt: JsonField) = apply { this.runAt = runAt } - - fun startedAt(startedAt: String) = startedAt(JsonField.of(startedAt)) - - fun startedAt(startedAt: JsonField) = apply { this.startedAt = startedAt } - - fun toolName(toolName: String) = toolName(JsonField.of(toolName)) - - fun toolName(toolName: JsonField) = apply { this.toolName = toolName } - - fun toolkitName(toolkitName: String) = toolkitName(JsonField.of(toolkitName)) - - fun toolkitName(toolkitName: JsonField) = apply { this.toolkitName = toolkitName } - - fun toolkitVersion(toolkitVersion: String) = toolkitVersion(JsonField.of(toolkitVersion)) - - fun toolkitVersion(toolkitVersion: JsonField) = apply { - this.toolkitVersion = toolkitVersion - } - - fun updatedAt(updatedAt: String) = updatedAt(JsonField.of(updatedAt)) - - fun updatedAt(updatedAt: JsonField) = apply { this.updatedAt = updatedAt } - - fun userId(userId: String) = userId(JsonField.of(userId)) - - fun userId(userId: JsonField) = apply { this.userId = userId } - - 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) - } - - fun build(): ToolExecution = - ToolExecution( - id, - createdAt, - executionStatus, - executionType, - finishedAt, - runAt, - startedAt, - toolName, - toolkitName, - toolkitVersion, - updatedAt, - userId, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ToolExecution && id == other.id && createdAt == other.createdAt && executionStatus == other.executionStatus && executionType == other.executionType && finishedAt == other.finishedAt && runAt == other.runAt && startedAt == other.startedAt && toolName == other.toolName && toolkitName == other.toolkitName && toolkitVersion == other.toolkitVersion && updatedAt == other.updatedAt && userId == other.userId && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(id, createdAt, executionStatus, executionType, finishedAt, runAt, startedAt, toolName, toolkitName, toolkitVersion, updatedAt, userId, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ToolExecution{id=$id, createdAt=$createdAt, executionStatus=$executionStatus, executionType=$executionType, finishedAt=$finishedAt, runAt=$runAt, startedAt=$startedAt, toolName=$toolName, toolkitName=$toolkitName, toolkitVersion=$toolkitVersion, updatedAt=$updatedAt, userId=$userId, additionalProperties=$additionalProperties}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolFormattedListPage.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolFormattedListPage.kt deleted file mode 100644 index e160d88..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolFormattedListPage.kt +++ /dev/null @@ -1,213 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import dev.arcade.services.blocking.tools.FormattedService -import java.util.Objects -import java.util.Optional -import java.util.stream.Stream -import java.util.stream.StreamSupport - -/** - * Returns a page of tools from the engine configuration, optionally filtered by toolkit, formatted - * for a specific provider - */ -class ToolFormattedListPage -private constructor( - private val formattedService: FormattedService, - private val params: ToolFormattedListParams, - private val response: Response, -) { - - fun response(): Response = response - - fun items(): List = response().items() - - fun totalCount(): Optional = response().totalCount() - - fun offset(): Optional = response().offset() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ToolFormattedListPage && formattedService == other.formattedService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(formattedService, params, response) /* spotless:on */ - - override fun toString() = - "ToolFormattedListPage{formattedService=$formattedService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - if (items().isEmpty()) { - return false - } - - return offset().orElse(0) + items().count() < totalCount().orElse(Long.MAX_VALUE) - } - - fun getNextPageParams(): Optional { - if (!hasNextPage()) { - return Optional.empty() - } - - return Optional.of( - ToolFormattedListParams.builder() - .from(params) - .offset(offset().orElse(0) + items().count()) - .build() - ) - } - - fun getNextPage(): Optional { - return getNextPageParams().map { formattedService.list(it) } - } - - fun autoPager(): AutoPager = AutoPager(this) - - companion object { - - @JvmStatic - fun of( - formattedService: FormattedService, - params: ToolFormattedListParams, - response: Response, - ) = ToolFormattedListPage(formattedService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("items") - private val items: JsonField> = JsonMissing.of(), - @JsonProperty("total_count") private val totalCount: JsonField = JsonMissing.of(), - @JsonProperty("offset") private val offset: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun items(): List = items.getNullable("items") ?: listOf() - - fun totalCount(): Optional = - Optional.ofNullable(totalCount.getNullable("total_count")) - - fun offset(): Optional = Optional.ofNullable(offset.getNullable("offset")) - - @JsonProperty("items") - fun _items(): Optional>> = - Optional.ofNullable(items) - - @JsonProperty("total_count") - fun _totalCount(): Optional> = Optional.ofNullable(totalCount) - - @JsonProperty("offset") - fun _offset(): Optional> = Optional.ofNullable(offset) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - items().map { it.validate() } - totalCount() - offset() - validated = true - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && items == other.items && totalCount == other.totalCount && offset == other.offset && additionalProperties == other.additionalProperties /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(items, totalCount, offset, additionalProperties) /* spotless:on */ - - override fun toString() = - "Response{items=$items, totalCount=$totalCount, offset=$offset, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var items: JsonField> = JsonMissing.of() - private var totalCount: JsonField = JsonMissing.of() - private var offset: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.items = page.items - this.totalCount = page.totalCount - this.offset = page.offset - this.additionalProperties.putAll(page.additionalProperties) - } - - fun items(items: List) = items(JsonField.of(items)) - - fun items(items: JsonField>) = apply { - this.items = items - } - - fun totalCount(totalCount: Long) = totalCount(JsonField.of(totalCount)) - - fun totalCount(totalCount: JsonField) = apply { this.totalCount = totalCount } - - fun offset(offset: Long) = offset(JsonField.of(offset)) - - fun offset(offset: JsonField) = apply { this.offset = offset } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun build() = Response(items, totalCount, offset, additionalProperties.toImmutable()) - } - } - - class AutoPager(private val firstPage: ToolFormattedListPage) : - Iterable { - - override fun iterator(): Iterator = iterator { - var page = firstPage - var index = 0 - while (true) { - while (index < page.items().size) { - yield(page.items()[index++]) - } - page = page.getNextPage().orElse(null) ?: break - index = 0 - } - } - - fun stream(): Stream { - return StreamSupport.stream(spliterator(), false) - } - } -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolFormattedListPageAsync.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolFormattedListPageAsync.kt deleted file mode 100644 index e79537a..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolFormattedListPageAsync.kt +++ /dev/null @@ -1,225 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import dev.arcade.services.async.tools.FormattedServiceAsync -import java.util.Objects -import java.util.Optional -import java.util.concurrent.CompletableFuture -import java.util.concurrent.Executor -import java.util.function.Predicate - -/** - * Returns a page of tools from the engine configuration, optionally filtered by toolkit, formatted - * for a specific provider - */ -class ToolFormattedListPageAsync -private constructor( - private val formattedService: FormattedServiceAsync, - private val params: ToolFormattedListParams, - private val response: Response, -) { - - fun response(): Response = response - - fun items(): List = response().items() - - fun totalCount(): Optional = response().totalCount() - - fun offset(): Optional = response().offset() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ToolFormattedListPageAsync && formattedService == other.formattedService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(formattedService, params, response) /* spotless:on */ - - override fun toString() = - "ToolFormattedListPageAsync{formattedService=$formattedService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - if (items().isEmpty()) { - return false - } - - return offset().orElse(0) + items().count() < totalCount().orElse(Long.MAX_VALUE) - } - - fun getNextPageParams(): Optional { - if (!hasNextPage()) { - return Optional.empty() - } - - return Optional.of( - ToolFormattedListParams.builder() - .from(params) - .offset(offset().orElse(0) + items().count()) - .build() - ) - } - - fun getNextPage(): CompletableFuture> { - return getNextPageParams() - .map { formattedService.list(it).thenApply { Optional.of(it) } } - .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } - } - - fun autoPager(): AutoPager = AutoPager(this) - - companion object { - - @JvmStatic - fun of( - formattedService: FormattedServiceAsync, - params: ToolFormattedListParams, - response: Response, - ) = ToolFormattedListPageAsync(formattedService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("items") - private val items: JsonField> = JsonMissing.of(), - @JsonProperty("total_count") private val totalCount: JsonField = JsonMissing.of(), - @JsonProperty("offset") private val offset: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun items(): List = items.getNullable("items") ?: listOf() - - fun totalCount(): Optional = - Optional.ofNullable(totalCount.getNullable("total_count")) - - fun offset(): Optional = Optional.ofNullable(offset.getNullable("offset")) - - @JsonProperty("items") - fun _items(): Optional>> = - Optional.ofNullable(items) - - @JsonProperty("total_count") - fun _totalCount(): Optional> = Optional.ofNullable(totalCount) - - @JsonProperty("offset") - fun _offset(): Optional> = Optional.ofNullable(offset) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - items().map { it.validate() } - totalCount() - offset() - validated = true - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && items == other.items && totalCount == other.totalCount && offset == other.offset && additionalProperties == other.additionalProperties /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(items, totalCount, offset, additionalProperties) /* spotless:on */ - - override fun toString() = - "Response{items=$items, totalCount=$totalCount, offset=$offset, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var items: JsonField> = JsonMissing.of() - private var totalCount: JsonField = JsonMissing.of() - private var offset: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.items = page.items - this.totalCount = page.totalCount - this.offset = page.offset - this.additionalProperties.putAll(page.additionalProperties) - } - - fun items(items: List) = items(JsonField.of(items)) - - fun items(items: JsonField>) = apply { - this.items = items - } - - fun totalCount(totalCount: Long) = totalCount(JsonField.of(totalCount)) - - fun totalCount(totalCount: JsonField) = apply { this.totalCount = totalCount } - - fun offset(offset: Long) = offset(JsonField.of(offset)) - - fun offset(offset: JsonField) = apply { this.offset = offset } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun build() = Response(items, totalCount, offset, additionalProperties.toImmutable()) - } - } - - class AutoPager(private val firstPage: ToolFormattedListPageAsync) { - - fun forEach( - action: Predicate, - executor: Executor, - ): CompletableFuture { - fun CompletableFuture>.forEach( - action: (ToolFormattedListResponse) -> Boolean, - executor: Executor, - ): CompletableFuture = - thenComposeAsync( - { page -> - page - .filter { it.items().all(action) } - .map { it.getNextPage().forEach(action, executor) } - .orElseGet { CompletableFuture.completedFuture(null) } - }, - executor, - ) - return CompletableFuture.completedFuture(Optional.of(firstPage)) - .forEach(action::test, executor) - } - - fun toList(executor: Executor): CompletableFuture> { - val values = mutableListOf() - return forEach(values::add, executor).thenApply { values } - } - } -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolListPage.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolListPage.kt deleted file mode 100644 index df48c7e..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolListPage.kt +++ /dev/null @@ -1,203 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import dev.arcade.services.blocking.ToolService -import java.util.Objects -import java.util.Optional -import java.util.stream.Stream -import java.util.stream.StreamSupport - -/** Returns a page of tools from the engine configuration, optionally filtered by toolkit */ -class ToolListPage -private constructor( - private val toolsService: ToolService, - private val params: ToolListParams, - private val response: Response, -) { - - fun response(): Response = response - - fun items(): List = response().items() - - fun totalCount(): Optional = response().totalCount() - - fun offset(): Optional = response().offset() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ToolListPage && toolsService == other.toolsService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(toolsService, params, response) /* spotless:on */ - - override fun toString() = - "ToolListPage{toolsService=$toolsService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - if (items().isEmpty()) { - return false - } - - return offset().orElse(0) + items().count() < totalCount().orElse(Long.MAX_VALUE) - } - - fun getNextPageParams(): Optional { - if (!hasNextPage()) { - return Optional.empty() - } - - return Optional.of( - ToolListParams.builder() - .from(params) - .offset(offset().orElse(0) + items().count()) - .build() - ) - } - - fun getNextPage(): Optional { - return getNextPageParams().map { toolsService.list(it) } - } - - fun autoPager(): AutoPager = AutoPager(this) - - companion object { - - @JvmStatic - fun of(toolsService: ToolService, params: ToolListParams, response: Response) = - ToolListPage(toolsService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("items") - private val items: JsonField> = JsonMissing.of(), - @JsonProperty("total_count") private val totalCount: JsonField = JsonMissing.of(), - @JsonProperty("offset") private val offset: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun items(): List = items.getNullable("items") ?: listOf() - - fun totalCount(): Optional = - Optional.ofNullable(totalCount.getNullable("total_count")) - - fun offset(): Optional = Optional.ofNullable(offset.getNullable("offset")) - - @JsonProperty("items") - fun _items(): Optional>> = Optional.ofNullable(items) - - @JsonProperty("total_count") - fun _totalCount(): Optional> = Optional.ofNullable(totalCount) - - @JsonProperty("offset") - fun _offset(): Optional> = Optional.ofNullable(offset) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - items().map { it.validate() } - totalCount() - offset() - validated = true - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && items == other.items && totalCount == other.totalCount && offset == other.offset && additionalProperties == other.additionalProperties /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(items, totalCount, offset, additionalProperties) /* spotless:on */ - - override fun toString() = - "Response{items=$items, totalCount=$totalCount, offset=$offset, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var items: JsonField> = JsonMissing.of() - private var totalCount: JsonField = JsonMissing.of() - private var offset: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.items = page.items - this.totalCount = page.totalCount - this.offset = page.offset - this.additionalProperties.putAll(page.additionalProperties) - } - - fun items(items: List) = items(JsonField.of(items)) - - fun items(items: JsonField>) = apply { this.items = items } - - fun totalCount(totalCount: Long) = totalCount(JsonField.of(totalCount)) - - fun totalCount(totalCount: JsonField) = apply { this.totalCount = totalCount } - - fun offset(offset: Long) = offset(JsonField.of(offset)) - - fun offset(offset: JsonField) = apply { this.offset = offset } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun build() = Response(items, totalCount, offset, additionalProperties.toImmutable()) - } - } - - class AutoPager(private val firstPage: ToolListPage) : Iterable { - - override fun iterator(): Iterator = iterator { - var page = firstPage - var index = 0 - while (true) { - while (index < page.items().size) { - yield(page.items()[index++]) - } - page = page.getNextPage().orElse(null) ?: break - index = 0 - } - } - - fun stream(): Stream { - return StreamSupport.stream(spliterator(), false) - } - } -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolListPageAsync.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolListPageAsync.kt deleted file mode 100644 index 40fc7a1..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolListPageAsync.kt +++ /dev/null @@ -1,216 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import dev.arcade.services.async.ToolServiceAsync -import java.util.Objects -import java.util.Optional -import java.util.concurrent.CompletableFuture -import java.util.concurrent.Executor -import java.util.function.Predicate - -/** Returns a page of tools from the engine configuration, optionally filtered by toolkit */ -class ToolListPageAsync -private constructor( - private val toolsService: ToolServiceAsync, - private val params: ToolListParams, - private val response: Response, -) { - - fun response(): Response = response - - fun items(): List = response().items() - - fun totalCount(): Optional = response().totalCount() - - fun offset(): Optional = response().offset() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ToolListPageAsync && toolsService == other.toolsService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(toolsService, params, response) /* spotless:on */ - - override fun toString() = - "ToolListPageAsync{toolsService=$toolsService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - if (items().isEmpty()) { - return false - } - - return offset().orElse(0) + items().count() < totalCount().orElse(Long.MAX_VALUE) - } - - fun getNextPageParams(): Optional { - if (!hasNextPage()) { - return Optional.empty() - } - - return Optional.of( - ToolListParams.builder() - .from(params) - .offset(offset().orElse(0) + items().count()) - .build() - ) - } - - fun getNextPage(): CompletableFuture> { - return getNextPageParams() - .map { toolsService.list(it).thenApply { Optional.of(it) } } - .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } - } - - fun autoPager(): AutoPager = AutoPager(this) - - companion object { - - @JvmStatic - fun of(toolsService: ToolServiceAsync, params: ToolListParams, response: Response) = - ToolListPageAsync(toolsService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("items") - private val items: JsonField> = JsonMissing.of(), - @JsonProperty("total_count") private val totalCount: JsonField = JsonMissing.of(), - @JsonProperty("offset") private val offset: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun items(): List = items.getNullable("items") ?: listOf() - - fun totalCount(): Optional = - Optional.ofNullable(totalCount.getNullable("total_count")) - - fun offset(): Optional = Optional.ofNullable(offset.getNullable("offset")) - - @JsonProperty("items") - fun _items(): Optional>> = Optional.ofNullable(items) - - @JsonProperty("total_count") - fun _totalCount(): Optional> = Optional.ofNullable(totalCount) - - @JsonProperty("offset") - fun _offset(): Optional> = Optional.ofNullable(offset) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - items().map { it.validate() } - totalCount() - offset() - validated = true - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && items == other.items && totalCount == other.totalCount && offset == other.offset && additionalProperties == other.additionalProperties /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(items, totalCount, offset, additionalProperties) /* spotless:on */ - - override fun toString() = - "Response{items=$items, totalCount=$totalCount, offset=$offset, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var items: JsonField> = JsonMissing.of() - private var totalCount: JsonField = JsonMissing.of() - private var offset: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.items = page.items - this.totalCount = page.totalCount - this.offset = page.offset - this.additionalProperties.putAll(page.additionalProperties) - } - - fun items(items: List) = items(JsonField.of(items)) - - fun items(items: JsonField>) = apply { this.items = items } - - fun totalCount(totalCount: Long) = totalCount(JsonField.of(totalCount)) - - fun totalCount(totalCount: JsonField) = apply { this.totalCount = totalCount } - - fun offset(offset: Long) = offset(JsonField.of(offset)) - - fun offset(offset: JsonField) = apply { this.offset = offset } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun build() = Response(items, totalCount, offset, additionalProperties.toImmutable()) - } - } - - class AutoPager(private val firstPage: ToolListPageAsync) { - - fun forEach( - action: Predicate, - executor: Executor, - ): CompletableFuture { - fun CompletableFuture>.forEach( - action: (ToolDefinition) -> Boolean, - executor: Executor, - ): CompletableFuture = - thenComposeAsync( - { page -> - page - .filter { it.items().all(action) } - .map { it.getNextPage().forEach(action, executor) } - .orElseGet { CompletableFuture.completedFuture(null) } - }, - executor, - ) - return CompletableFuture.completedFuture(Optional.of(firstPage)) - .forEach(action::test, executor) - } - - fun toList(executor: Executor): CompletableFuture> { - val values = mutableListOf() - return forEach(values::add, executor).thenApply { values } - } - } -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolScheduledGetResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolScheduledGetResponse.kt deleted file mode 100644 index 808966e..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolScheduledGetResponse.kt +++ /dev/null @@ -1,417 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import java.util.Objects -import java.util.Optional - -@NoAutoDetect -class ToolScheduledGetResponse -@JsonCreator -private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("attempts") - @ExcludeMissing - private val attempts: JsonField> = JsonMissing.of(), - @JsonProperty("created_at") - @ExcludeMissing - private val createdAt: JsonField = JsonMissing.of(), - @JsonProperty("execution_status") - @ExcludeMissing - private val executionStatus: JsonField = JsonMissing.of(), - @JsonProperty("execution_type") - @ExcludeMissing - private val executionType: JsonField = JsonMissing.of(), - @JsonProperty("finished_at") - @ExcludeMissing - private val finishedAt: JsonField = JsonMissing.of(), - @JsonProperty("input") @ExcludeMissing private val input: JsonField = JsonMissing.of(), - @JsonProperty("run_at") @ExcludeMissing private val runAt: JsonField = JsonMissing.of(), - @JsonProperty("started_at") - @ExcludeMissing - private val startedAt: JsonField = JsonMissing.of(), - @JsonProperty("tool_name") - @ExcludeMissing - private val toolName: JsonField = JsonMissing.of(), - @JsonProperty("toolkit_name") - @ExcludeMissing - private val toolkitName: JsonField = JsonMissing.of(), - @JsonProperty("toolkit_version") - @ExcludeMissing - private val toolkitVersion: JsonField = JsonMissing.of(), - @JsonProperty("updated_at") - @ExcludeMissing - private val updatedAt: JsonField = JsonMissing.of(), - @JsonProperty("user_id") - @ExcludeMissing - private val userId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), -) { - - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - fun attempts(): Optional> = - Optional.ofNullable(attempts.getNullable("attempts")) - - fun createdAt(): Optional = Optional.ofNullable(createdAt.getNullable("created_at")) - - fun executionStatus(): Optional = - Optional.ofNullable(executionStatus.getNullable("execution_status")) - - fun executionType(): Optional = - Optional.ofNullable(executionType.getNullable("execution_type")) - - fun finishedAt(): Optional = Optional.ofNullable(finishedAt.getNullable("finished_at")) - - fun input(): Optional = Optional.ofNullable(input.getNullable("input")) - - fun runAt(): Optional = Optional.ofNullable(runAt.getNullable("run_at")) - - fun startedAt(): Optional = Optional.ofNullable(startedAt.getNullable("started_at")) - - fun toolName(): Optional = Optional.ofNullable(toolName.getNullable("tool_name")) - - fun toolkitName(): Optional = - Optional.ofNullable(toolkitName.getNullable("toolkit_name")) - - fun toolkitVersion(): Optional = - Optional.ofNullable(toolkitVersion.getNullable("toolkit_version")) - - fun updatedAt(): Optional = Optional.ofNullable(updatedAt.getNullable("updated_at")) - - fun userId(): Optional = Optional.ofNullable(userId.getNullable("user_id")) - - @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - - @JsonProperty("attempts") - @ExcludeMissing - fun _attempts(): JsonField> = attempts - - @JsonProperty("created_at") @ExcludeMissing fun _createdAt(): JsonField = createdAt - - @JsonProperty("execution_status") - @ExcludeMissing - fun _executionStatus(): JsonField = executionStatus - - @JsonProperty("execution_type") - @ExcludeMissing - fun _executionType(): JsonField = executionType - - @JsonProperty("finished_at") @ExcludeMissing fun _finishedAt(): JsonField = finishedAt - - @JsonProperty("input") @ExcludeMissing fun _input(): JsonField = input - - @JsonProperty("run_at") @ExcludeMissing fun _runAt(): JsonField = runAt - - @JsonProperty("started_at") @ExcludeMissing fun _startedAt(): JsonField = startedAt - - @JsonProperty("tool_name") @ExcludeMissing fun _toolName(): JsonField = toolName - - @JsonProperty("toolkit_name") - @ExcludeMissing - fun _toolkitName(): JsonField = toolkitName - - @JsonProperty("toolkit_version") - @ExcludeMissing - fun _toolkitVersion(): JsonField = toolkitVersion - - @JsonProperty("updated_at") @ExcludeMissing fun _updatedAt(): JsonField = updatedAt - - @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ToolScheduledGetResponse = apply { - if (validated) { - return@apply - } - - id() - attempts().ifPresent { it.forEach { it.validate() } } - createdAt() - executionStatus() - executionType() - finishedAt() - input().ifPresent { it.validate() } - runAt() - startedAt() - toolName() - toolkitName() - toolkitVersion() - updatedAt() - userId() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ToolScheduledGetResponse]. */ - class Builder internal constructor() { - - private var id: JsonField = JsonMissing.of() - private var attempts: JsonField>? = null - private var createdAt: JsonField = JsonMissing.of() - private var executionStatus: JsonField = JsonMissing.of() - private var executionType: JsonField = JsonMissing.of() - private var finishedAt: JsonField = JsonMissing.of() - private var input: JsonField = JsonMissing.of() - private var runAt: JsonField = JsonMissing.of() - private var startedAt: JsonField = JsonMissing.of() - private var toolName: JsonField = JsonMissing.of() - private var toolkitName: JsonField = JsonMissing.of() - private var toolkitVersion: JsonField = JsonMissing.of() - private var updatedAt: JsonField = JsonMissing.of() - private var userId: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(toolScheduledGetResponse: ToolScheduledGetResponse) = apply { - id = toolScheduledGetResponse.id - attempts = toolScheduledGetResponse.attempts.map { it.toMutableList() } - createdAt = toolScheduledGetResponse.createdAt - executionStatus = toolScheduledGetResponse.executionStatus - executionType = toolScheduledGetResponse.executionType - finishedAt = toolScheduledGetResponse.finishedAt - input = toolScheduledGetResponse.input - runAt = toolScheduledGetResponse.runAt - startedAt = toolScheduledGetResponse.startedAt - toolName = toolScheduledGetResponse.toolName - toolkitName = toolScheduledGetResponse.toolkitName - toolkitVersion = toolScheduledGetResponse.toolkitVersion - updatedAt = toolScheduledGetResponse.updatedAt - userId = toolScheduledGetResponse.userId - additionalProperties = toolScheduledGetResponse.additionalProperties.toMutableMap() - } - - fun id(id: String) = id(JsonField.of(id)) - - fun id(id: JsonField) = apply { this.id = id } - - fun attempts(attempts: List) = attempts(JsonField.of(attempts)) - - fun attempts(attempts: JsonField>) = apply { - this.attempts = attempts.map { it.toMutableList() } - } - - fun addAttempt(attempt: ToolExecutionAttempt) = apply { - attempts = - (attempts ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(attempt) - } - } - - fun createdAt(createdAt: String) = createdAt(JsonField.of(createdAt)) - - fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } - - fun executionStatus(executionStatus: String) = - executionStatus(JsonField.of(executionStatus)) - - fun executionStatus(executionStatus: JsonField) = apply { - this.executionStatus = executionStatus - } - - fun executionType(executionType: String) = executionType(JsonField.of(executionType)) - - fun executionType(executionType: JsonField) = apply { - this.executionType = executionType - } - - fun finishedAt(finishedAt: String) = finishedAt(JsonField.of(finishedAt)) - - fun finishedAt(finishedAt: JsonField) = apply { this.finishedAt = finishedAt } - - fun input(input: Input) = input(JsonField.of(input)) - - fun input(input: JsonField) = apply { this.input = input } - - fun runAt(runAt: String) = runAt(JsonField.of(runAt)) - - fun runAt(runAt: JsonField) = apply { this.runAt = runAt } - - fun startedAt(startedAt: String) = startedAt(JsonField.of(startedAt)) - - fun startedAt(startedAt: JsonField) = apply { this.startedAt = startedAt } - - fun toolName(toolName: String) = toolName(JsonField.of(toolName)) - - fun toolName(toolName: JsonField) = apply { this.toolName = toolName } - - fun toolkitName(toolkitName: String) = toolkitName(JsonField.of(toolkitName)) - - fun toolkitName(toolkitName: JsonField) = apply { this.toolkitName = toolkitName } - - fun toolkitVersion(toolkitVersion: String) = toolkitVersion(JsonField.of(toolkitVersion)) - - fun toolkitVersion(toolkitVersion: JsonField) = apply { - this.toolkitVersion = toolkitVersion - } - - fun updatedAt(updatedAt: String) = updatedAt(JsonField.of(updatedAt)) - - fun updatedAt(updatedAt: JsonField) = apply { this.updatedAt = updatedAt } - - fun userId(userId: String) = userId(JsonField.of(userId)) - - fun userId(userId: JsonField) = apply { this.userId = userId } - - 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) - } - - fun build(): ToolScheduledGetResponse = - ToolScheduledGetResponse( - id, - (attempts ?: JsonMissing.of()).map { it.toImmutable() }, - createdAt, - executionStatus, - executionType, - finishedAt, - input, - runAt, - startedAt, - toolName, - toolkitName, - toolkitVersion, - updatedAt, - userId, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class Input - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Input = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Input]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(input: Input) = apply { - additionalProperties = input.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) - } - - fun build(): Input = Input(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Input && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "Input{additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ToolScheduledGetResponse && id == other.id && attempts == other.attempts && createdAt == other.createdAt && executionStatus == other.executionStatus && executionType == other.executionType && finishedAt == other.finishedAt && input == other.input && runAt == other.runAt && startedAt == other.startedAt && toolName == other.toolName && toolkitName == other.toolkitName && toolkitVersion == other.toolkitVersion && updatedAt == other.updatedAt && userId == other.userId && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(id, attempts, createdAt, executionStatus, executionType, finishedAt, input, runAt, startedAt, toolName, toolkitName, toolkitVersion, updatedAt, userId, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ToolScheduledGetResponse{id=$id, attempts=$attempts, createdAt=$createdAt, executionStatus=$executionStatus, executionType=$executionType, finishedAt=$finishedAt, input=$input, runAt=$runAt, startedAt=$startedAt, toolName=$toolName, toolkitName=$toolkitName, toolkitVersion=$toolkitVersion, updatedAt=$updatedAt, userId=$userId, additionalProperties=$additionalProperties}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolScheduledListPage.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolScheduledListPage.kt deleted file mode 100644 index e75e666..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolScheduledListPage.kt +++ /dev/null @@ -1,205 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import dev.arcade.services.blocking.tools.ScheduledService -import java.util.Objects -import java.util.Optional -import java.util.stream.Stream -import java.util.stream.StreamSupport - -/** Returns a page of scheduled tool executions */ -class ToolScheduledListPage -private constructor( - private val scheduledService: ScheduledService, - private val params: ToolScheduledListParams, - private val response: Response, -) { - - fun response(): Response = response - - fun items(): List = response().items() - - fun totalCount(): Optional = response().totalCount() - - fun offset(): Optional = response().offset() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ToolScheduledListPage && scheduledService == other.scheduledService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(scheduledService, params, response) /* spotless:on */ - - override fun toString() = - "ToolScheduledListPage{scheduledService=$scheduledService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - if (items().isEmpty()) { - return false - } - - return offset().orElse(0) + items().count() < totalCount().orElse(Long.MAX_VALUE) - } - - fun getNextPageParams(): Optional { - if (!hasNextPage()) { - return Optional.empty() - } - - return Optional.of( - ToolScheduledListParams.builder() - .from(params) - .offset(offset().orElse(0) + items().count()) - .build() - ) - } - - fun getNextPage(): Optional { - return getNextPageParams().map { scheduledService.list(it) } - } - - fun autoPager(): AutoPager = AutoPager(this) - - companion object { - - @JvmStatic - fun of( - scheduledService: ScheduledService, - params: ToolScheduledListParams, - response: Response, - ) = ToolScheduledListPage(scheduledService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("items") private val items: JsonField> = JsonMissing.of(), - @JsonProperty("total_count") private val totalCount: JsonField = JsonMissing.of(), - @JsonProperty("offset") private val offset: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun items(): List = items.getNullable("items") ?: listOf() - - fun totalCount(): Optional = - Optional.ofNullable(totalCount.getNullable("total_count")) - - fun offset(): Optional = Optional.ofNullable(offset.getNullable("offset")) - - @JsonProperty("items") - fun _items(): Optional>> = Optional.ofNullable(items) - - @JsonProperty("total_count") - fun _totalCount(): Optional> = Optional.ofNullable(totalCount) - - @JsonProperty("offset") - fun _offset(): Optional> = Optional.ofNullable(offset) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - items().map { it.validate() } - totalCount() - offset() - validated = true - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && items == other.items && totalCount == other.totalCount && offset == other.offset && additionalProperties == other.additionalProperties /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(items, totalCount, offset, additionalProperties) /* spotless:on */ - - override fun toString() = - "Response{items=$items, totalCount=$totalCount, offset=$offset, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var items: JsonField> = JsonMissing.of() - private var totalCount: JsonField = JsonMissing.of() - private var offset: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.items = page.items - this.totalCount = page.totalCount - this.offset = page.offset - this.additionalProperties.putAll(page.additionalProperties) - } - - fun items(items: List) = items(JsonField.of(items)) - - fun items(items: JsonField>) = apply { this.items = items } - - fun totalCount(totalCount: Long) = totalCount(JsonField.of(totalCount)) - - fun totalCount(totalCount: JsonField) = apply { this.totalCount = totalCount } - - fun offset(offset: Long) = offset(JsonField.of(offset)) - - fun offset(offset: JsonField) = apply { this.offset = offset } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun build() = Response(items, totalCount, offset, additionalProperties.toImmutable()) - } - } - - class AutoPager(private val firstPage: ToolScheduledListPage) : Iterable { - - override fun iterator(): Iterator = iterator { - var page = firstPage - var index = 0 - while (true) { - while (index < page.items().size) { - yield(page.items()[index++]) - } - page = page.getNextPage().orElse(null) ?: break - index = 0 - } - } - - fun stream(): Stream { - return StreamSupport.stream(spliterator(), false) - } - } -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolScheduledListPageAsync.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolScheduledListPageAsync.kt deleted file mode 100644 index bbd1d06..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolScheduledListPageAsync.kt +++ /dev/null @@ -1,215 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import dev.arcade.services.async.tools.ScheduledServiceAsync -import java.util.Objects -import java.util.Optional -import java.util.concurrent.CompletableFuture -import java.util.concurrent.Executor -import java.util.function.Predicate - -/** Returns a page of scheduled tool executions */ -class ToolScheduledListPageAsync -private constructor( - private val scheduledService: ScheduledServiceAsync, - private val params: ToolScheduledListParams, - private val response: Response, -) { - - fun response(): Response = response - - fun items(): List = response().items() - - fun totalCount(): Optional = response().totalCount() - - fun offset(): Optional = response().offset() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ToolScheduledListPageAsync && scheduledService == other.scheduledService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(scheduledService, params, response) /* spotless:on */ - - override fun toString() = - "ToolScheduledListPageAsync{scheduledService=$scheduledService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - if (items().isEmpty()) { - return false - } - - return offset().orElse(0) + items().count() < totalCount().orElse(Long.MAX_VALUE) - } - - fun getNextPageParams(): Optional { - if (!hasNextPage()) { - return Optional.empty() - } - - return Optional.of( - ToolScheduledListParams.builder() - .from(params) - .offset(offset().orElse(0) + items().count()) - .build() - ) - } - - fun getNextPage(): CompletableFuture> { - return getNextPageParams() - .map { scheduledService.list(it).thenApply { Optional.of(it) } } - .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } - } - - fun autoPager(): AutoPager = AutoPager(this) - - companion object { - - @JvmStatic - fun of( - scheduledService: ScheduledServiceAsync, - params: ToolScheduledListParams, - response: Response, - ) = ToolScheduledListPageAsync(scheduledService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("items") private val items: JsonField> = JsonMissing.of(), - @JsonProperty("total_count") private val totalCount: JsonField = JsonMissing.of(), - @JsonProperty("offset") private val offset: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun items(): List = items.getNullable("items") ?: listOf() - - fun totalCount(): Optional = - Optional.ofNullable(totalCount.getNullable("total_count")) - - fun offset(): Optional = Optional.ofNullable(offset.getNullable("offset")) - - @JsonProperty("items") - fun _items(): Optional>> = Optional.ofNullable(items) - - @JsonProperty("total_count") - fun _totalCount(): Optional> = Optional.ofNullable(totalCount) - - @JsonProperty("offset") - fun _offset(): Optional> = Optional.ofNullable(offset) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - items().map { it.validate() } - totalCount() - offset() - validated = true - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && items == other.items && totalCount == other.totalCount && offset == other.offset && additionalProperties == other.additionalProperties /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(items, totalCount, offset, additionalProperties) /* spotless:on */ - - override fun toString() = - "Response{items=$items, totalCount=$totalCount, offset=$offset, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var items: JsonField> = JsonMissing.of() - private var totalCount: JsonField = JsonMissing.of() - private var offset: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.items = page.items - this.totalCount = page.totalCount - this.offset = page.offset - this.additionalProperties.putAll(page.additionalProperties) - } - - fun items(items: List) = items(JsonField.of(items)) - - fun items(items: JsonField>) = apply { this.items = items } - - fun totalCount(totalCount: Long) = totalCount(JsonField.of(totalCount)) - - fun totalCount(totalCount: JsonField) = apply { this.totalCount = totalCount } - - fun offset(offset: Long) = offset(JsonField.of(offset)) - - fun offset(offset: JsonField) = apply { this.offset = offset } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun build() = Response(items, totalCount, offset, additionalProperties.toImmutable()) - } - } - - class AutoPager(private val firstPage: ToolScheduledListPageAsync) { - - fun forEach(action: Predicate, executor: Executor): CompletableFuture { - fun CompletableFuture>.forEach( - action: (ToolExecution) -> Boolean, - executor: Executor, - ): CompletableFuture = - thenComposeAsync( - { page -> - page - .filter { it.items().all(action) } - .map { it.getNextPage().forEach(action, executor) } - .orElseGet { CompletableFuture.completedFuture(null) } - }, - executor, - ) - return CompletableFuture.completedFuture(Optional.of(firstPage)) - .forEach(action::test, executor) - } - - fun toList(executor: Executor): CompletableFuture> { - val values = mutableListOf() - return forEach(values::add, executor).thenApply { values } - } - } -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/UpdateWorkerRequest.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/UpdateWorkerRequest.kt deleted file mode 100644 index ecae2c3..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/UpdateWorkerRequest.kt +++ /dev/null @@ -1,742 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import java.util.Objects -import java.util.Optional - -@NoAutoDetect -class UpdateWorkerRequest -@JsonCreator -private constructor( - @JsonProperty("enabled") - @ExcludeMissing - private val enabled: JsonField = JsonMissing.of(), - @JsonProperty("http") @ExcludeMissing private val http: JsonField = JsonMissing.of(), - @JsonProperty("mcp") @ExcludeMissing private val mcp: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), -) { - - fun enabled(): Optional = Optional.ofNullable(enabled.getNullable("enabled")) - - fun http(): Optional = Optional.ofNullable(http.getNullable("http")) - - fun mcp(): Optional = Optional.ofNullable(mcp.getNullable("mcp")) - - @JsonProperty("enabled") @ExcludeMissing fun _enabled(): JsonField = enabled - - @JsonProperty("http") @ExcludeMissing fun _http(): JsonField = http - - @JsonProperty("mcp") @ExcludeMissing fun _mcp(): JsonField = mcp - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): UpdateWorkerRequest = apply { - if (validated) { - return@apply - } - - enabled() - http().ifPresent { it.validate() } - mcp().ifPresent { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [UpdateWorkerRequest]. */ - class Builder internal constructor() { - - private var enabled: JsonField = JsonMissing.of() - private var http: JsonField = JsonMissing.of() - private var mcp: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(updateWorkerRequest: UpdateWorkerRequest) = apply { - enabled = updateWorkerRequest.enabled - http = updateWorkerRequest.http - mcp = updateWorkerRequest.mcp - additionalProperties = updateWorkerRequest.additionalProperties.toMutableMap() - } - - fun enabled(enabled: Boolean) = enabled(JsonField.of(enabled)) - - fun enabled(enabled: JsonField) = apply { this.enabled = enabled } - - fun http(http: Http) = http(JsonField.of(http)) - - fun http(http: JsonField) = apply { this.http = http } - - fun mcp(mcp: Mcp) = mcp(JsonField.of(mcp)) - - fun mcp(mcp: JsonField) = apply { this.mcp = mcp } - - 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) - } - - fun build(): UpdateWorkerRequest = - UpdateWorkerRequest(enabled, http, mcp, additionalProperties.toImmutable()) - } - - @NoAutoDetect - class Http - @JsonCreator - private constructor( - @JsonProperty("retry") - @ExcludeMissing - private val retry: JsonField = JsonMissing.of(), - @JsonProperty("secret") - @ExcludeMissing - private val secret: JsonField = JsonMissing.of(), - @JsonProperty("timeout") - @ExcludeMissing - private val timeout: JsonField = JsonMissing.of(), - @JsonProperty("uri") @ExcludeMissing private val uri: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun retry(): Optional = Optional.ofNullable(retry.getNullable("retry")) - - fun secret(): Optional = Optional.ofNullable(secret.getNullable("secret")) - - fun timeout(): Optional = Optional.ofNullable(timeout.getNullable("timeout")) - - fun uri(): Optional = Optional.ofNullable(uri.getNullable("uri")) - - @JsonProperty("retry") @ExcludeMissing fun _retry(): JsonField = retry - - @JsonProperty("secret") @ExcludeMissing fun _secret(): JsonField = secret - - @JsonProperty("timeout") @ExcludeMissing fun _timeout(): JsonField = timeout - - @JsonProperty("uri") @ExcludeMissing fun _uri(): JsonField = uri - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Http = apply { - if (validated) { - return@apply - } - - retry() - secret() - timeout() - uri() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Http]. */ - class Builder internal constructor() { - - private var retry: JsonField = JsonMissing.of() - private var secret: JsonField = JsonMissing.of() - private var timeout: JsonField = JsonMissing.of() - private var uri: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(http: Http) = apply { - retry = http.retry - secret = http.secret - timeout = http.timeout - uri = http.uri - additionalProperties = http.additionalProperties.toMutableMap() - } - - fun retry(retry: Long) = retry(JsonField.of(retry)) - - fun retry(retry: JsonField) = apply { this.retry = retry } - - fun secret(secret: String) = secret(JsonField.of(secret)) - - fun secret(secret: JsonField) = apply { this.secret = secret } - - fun timeout(timeout: Long) = timeout(JsonField.of(timeout)) - - fun timeout(timeout: JsonField) = apply { this.timeout = timeout } - - fun uri(uri: String) = uri(JsonField.of(uri)) - - fun uri(uri: JsonField) = apply { this.uri = uri } - - 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) - } - - fun build(): Http = - Http(retry, secret, timeout, uri, additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Http && retry == other.retry && secret == other.secret && timeout == other.timeout && uri == other.uri && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(retry, secret, timeout, uri, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Http{retry=$retry, secret=$secret, timeout=$timeout, uri=$uri, additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class Mcp - @JsonCreator - private constructor( - @JsonProperty("headers") - @ExcludeMissing - private val headers: JsonField = JsonMissing.of(), - @JsonProperty("oauth2") - @ExcludeMissing - private val oauth2: JsonField = JsonMissing.of(), - @JsonProperty("retry") - @ExcludeMissing - private val retry: JsonField = JsonMissing.of(), - @JsonProperty("secrets") - @ExcludeMissing - private val secrets: JsonField = JsonMissing.of(), - @JsonProperty("timeout") - @ExcludeMissing - private val timeout: JsonField = JsonMissing.of(), - @JsonProperty("uri") @ExcludeMissing private val uri: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun headers(): Optional = Optional.ofNullable(headers.getNullable("headers")) - - fun oauth2(): Optional = Optional.ofNullable(oauth2.getNullable("oauth2")) - - fun retry(): Optional = Optional.ofNullable(retry.getNullable("retry")) - - fun secrets(): Optional = Optional.ofNullable(secrets.getNullable("secrets")) - - fun timeout(): Optional = Optional.ofNullable(timeout.getNullable("timeout")) - - fun uri(): Optional = Optional.ofNullable(uri.getNullable("uri")) - - @JsonProperty("headers") @ExcludeMissing fun _headers(): JsonField = headers - - @JsonProperty("oauth2") @ExcludeMissing fun _oauth2(): JsonField = oauth2 - - @JsonProperty("retry") @ExcludeMissing fun _retry(): JsonField = retry - - @JsonProperty("secrets") @ExcludeMissing fun _secrets(): JsonField = secrets - - @JsonProperty("timeout") @ExcludeMissing fun _timeout(): JsonField = timeout - - @JsonProperty("uri") @ExcludeMissing fun _uri(): JsonField = uri - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Mcp = apply { - if (validated) { - return@apply - } - - headers().ifPresent { it.validate() } - oauth2().ifPresent { it.validate() } - retry() - secrets().ifPresent { it.validate() } - timeout() - uri() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Mcp]. */ - class Builder internal constructor() { - - private var headers: JsonField = JsonMissing.of() - private var oauth2: JsonField = JsonMissing.of() - private var retry: JsonField = JsonMissing.of() - private var secrets: JsonField = JsonMissing.of() - private var timeout: JsonField = JsonMissing.of() - private var uri: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(mcp: Mcp) = apply { - headers = mcp.headers - oauth2 = mcp.oauth2 - retry = mcp.retry - secrets = mcp.secrets - timeout = mcp.timeout - uri = mcp.uri - additionalProperties = mcp.additionalProperties.toMutableMap() - } - - fun headers(headers: Headers) = headers(JsonField.of(headers)) - - fun headers(headers: JsonField) = apply { this.headers = headers } - - fun oauth2(oauth2: Oauth2) = oauth2(JsonField.of(oauth2)) - - fun oauth2(oauth2: JsonField) = apply { this.oauth2 = oauth2 } - - fun retry(retry: Long) = retry(JsonField.of(retry)) - - fun retry(retry: JsonField) = apply { this.retry = retry } - - fun secrets(secrets: Secrets) = secrets(JsonField.of(secrets)) - - fun secrets(secrets: JsonField) = apply { this.secrets = secrets } - - fun timeout(timeout: Long) = timeout(JsonField.of(timeout)) - - fun timeout(timeout: JsonField) = apply { this.timeout = timeout } - - fun uri(uri: String) = uri(JsonField.of(uri)) - - fun uri(uri: JsonField) = apply { this.uri = uri } - - 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) - } - - fun build(): Mcp = - Mcp( - headers, - oauth2, - retry, - secrets, - timeout, - uri, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class Headers - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Headers = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Headers]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(headers: Headers) = apply { - additionalProperties = headers.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) - } - - fun build(): Headers = Headers(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Headers && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "Headers{additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class Oauth2 - @JsonCreator - private constructor( - @JsonProperty("authorization_url") - @ExcludeMissing - private val authorizationUrl: JsonField = JsonMissing.of(), - @JsonProperty("client_id") - @ExcludeMissing - private val clientId: JsonField = JsonMissing.of(), - @JsonProperty("client_secret") - @ExcludeMissing - private val clientSecret: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun authorizationUrl(): Optional = - Optional.ofNullable(authorizationUrl.getNullable("authorization_url")) - - fun clientId(): Optional = - Optional.ofNullable(clientId.getNullable("client_id")) - - fun clientSecret(): Optional = - Optional.ofNullable(clientSecret.getNullable("client_secret")) - - @JsonProperty("authorization_url") - @ExcludeMissing - fun _authorizationUrl(): JsonField = authorizationUrl - - @JsonProperty("client_id") @ExcludeMissing fun _clientId(): JsonField = clientId - - @JsonProperty("client_secret") - @ExcludeMissing - fun _clientSecret(): JsonField = clientSecret - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Oauth2 = apply { - if (validated) { - return@apply - } - - authorizationUrl() - clientId() - clientSecret() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Oauth2]. */ - class Builder internal constructor() { - - private var authorizationUrl: JsonField = JsonMissing.of() - private var clientId: JsonField = JsonMissing.of() - private var clientSecret: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(oauth2: Oauth2) = apply { - authorizationUrl = oauth2.authorizationUrl - clientId = oauth2.clientId - clientSecret = oauth2.clientSecret - additionalProperties = oauth2.additionalProperties.toMutableMap() - } - - fun authorizationUrl(authorizationUrl: String) = - authorizationUrl(JsonField.of(authorizationUrl)) - - fun authorizationUrl(authorizationUrl: JsonField) = apply { - this.authorizationUrl = authorizationUrl - } - - fun clientId(clientId: String) = clientId(JsonField.of(clientId)) - - fun clientId(clientId: JsonField) = apply { this.clientId = clientId } - - fun clientSecret(clientSecret: String) = clientSecret(JsonField.of(clientSecret)) - - fun clientSecret(clientSecret: JsonField) = apply { - this.clientSecret = clientSecret - } - - 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) - } - - fun build(): Oauth2 = - Oauth2( - authorizationUrl, - clientId, - clientSecret, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Oauth2 && authorizationUrl == other.authorizationUrl && clientId == other.clientId && clientSecret == other.clientSecret && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(authorizationUrl, clientId, clientSecret, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Oauth2{authorizationUrl=$authorizationUrl, clientId=$clientId, clientSecret=$clientSecret, additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class Secrets - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Secrets = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Secrets]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(secrets: Secrets) = apply { - additionalProperties = secrets.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) - } - - fun build(): Secrets = Secrets(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Secrets && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "Secrets{additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Mcp && headers == other.headers && oauth2 == other.oauth2 && retry == other.retry && secrets == other.secrets && timeout == other.timeout && uri == other.uri && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(headers, oauth2, retry, secrets, timeout, uri, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Mcp{headers=$headers, oauth2=$oauth2, retry=$retry, secrets=$secrets, timeout=$timeout, uri=$uri, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is UpdateWorkerRequest && enabled == other.enabled && http == other.http && mcp == other.mcp && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(enabled, http, mcp, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "UpdateWorkerRequest{enabled=$enabled, http=$http, mcp=$mcp, additionalProperties=$additionalProperties}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/Usage.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/Usage.kt deleted file mode 100644 index 44af4a6..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/Usage.kt +++ /dev/null @@ -1,147 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import java.util.Objects -import java.util.Optional - -@NoAutoDetect -class Usage -@JsonCreator -private constructor( - @JsonProperty("completion_tokens") - @ExcludeMissing - private val completionTokens: JsonField = JsonMissing.of(), - @JsonProperty("prompt_tokens") - @ExcludeMissing - private val promptTokens: JsonField = JsonMissing.of(), - @JsonProperty("total_tokens") - @ExcludeMissing - private val totalTokens: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), -) { - - fun completionTokens(): Optional = - Optional.ofNullable(completionTokens.getNullable("completion_tokens")) - - fun promptTokens(): Optional = - Optional.ofNullable(promptTokens.getNullable("prompt_tokens")) - - fun totalTokens(): Optional = Optional.ofNullable(totalTokens.getNullable("total_tokens")) - - @JsonProperty("completion_tokens") - @ExcludeMissing - fun _completionTokens(): JsonField = completionTokens - - @JsonProperty("prompt_tokens") - @ExcludeMissing - fun _promptTokens(): JsonField = promptTokens - - @JsonProperty("total_tokens") @ExcludeMissing fun _totalTokens(): JsonField = totalTokens - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Usage = apply { - if (validated) { - return@apply - } - - completionTokens() - promptTokens() - totalTokens() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Usage]. */ - class Builder internal constructor() { - - private var completionTokens: JsonField = JsonMissing.of() - private var promptTokens: JsonField = JsonMissing.of() - private var totalTokens: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(usage: Usage) = apply { - completionTokens = usage.completionTokens - promptTokens = usage.promptTokens - totalTokens = usage.totalTokens - additionalProperties = usage.additionalProperties.toMutableMap() - } - - fun completionTokens(completionTokens: Long) = - completionTokens(JsonField.of(completionTokens)) - - fun completionTokens(completionTokens: JsonField) = apply { - this.completionTokens = completionTokens - } - - fun promptTokens(promptTokens: Long) = promptTokens(JsonField.of(promptTokens)) - - fun promptTokens(promptTokens: JsonField) = apply { this.promptTokens = promptTokens } - - fun totalTokens(totalTokens: Long) = totalTokens(JsonField.of(totalTokens)) - - fun totalTokens(totalTokens: JsonField) = apply { this.totalTokens = totalTokens } - - 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) - } - - fun build(): Usage = - Usage(completionTokens, promptTokens, totalTokens, additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Usage && completionTokens == other.completionTokens && promptTokens == other.promptTokens && totalTokens == other.totalTokens && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(completionTokens, promptTokens, totalTokens, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Usage{completionTokens=$completionTokens, promptTokens=$promptTokens, totalTokens=$totalTokens, additionalProperties=$additionalProperties}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/UserConnectionResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/UserConnectionResponse.kt deleted file mode 100644 index 020babb..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/UserConnectionResponse.kt +++ /dev/null @@ -1,267 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import java.util.Objects -import java.util.Optional - -@NoAutoDetect -class UserConnectionResponse -@JsonCreator -private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("connection_id") - @ExcludeMissing - private val connectionId: JsonField = JsonMissing.of(), - @JsonProperty("connection_status") - @ExcludeMissing - private val connectionStatus: JsonField = JsonMissing.of(), - @JsonProperty("provider_description") - @ExcludeMissing - private val providerDescription: JsonField = JsonMissing.of(), - @JsonProperty("provider_id") - @ExcludeMissing - private val providerId: JsonField = JsonMissing.of(), - @JsonProperty("provider_type") - @ExcludeMissing - private val providerType: JsonField = JsonMissing.of(), - @JsonProperty("provider_user_info") - @ExcludeMissing - private val providerUserInfo: JsonValue = JsonMissing.of(), - @JsonProperty("scopes") - @ExcludeMissing - private val scopes: JsonField> = JsonMissing.of(), - @JsonProperty("user_id") - @ExcludeMissing - private val userId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), -) { - - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - fun connectionId(): Optional = - Optional.ofNullable(connectionId.getNullable("connection_id")) - - fun connectionStatus(): Optional = - Optional.ofNullable(connectionStatus.getNullable("connection_status")) - - fun providerDescription(): Optional = - Optional.ofNullable(providerDescription.getNullable("provider_description")) - - fun providerId(): Optional = Optional.ofNullable(providerId.getNullable("provider_id")) - - fun providerType(): Optional = - Optional.ofNullable(providerType.getNullable("provider_type")) - - @JsonProperty("provider_user_info") - @ExcludeMissing - fun _providerUserInfo(): JsonValue = providerUserInfo - - fun scopes(): Optional> = Optional.ofNullable(scopes.getNullable("scopes")) - - fun userId(): Optional = Optional.ofNullable(userId.getNullable("user_id")) - - @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - - @JsonProperty("connection_id") - @ExcludeMissing - fun _connectionId(): JsonField = connectionId - - @JsonProperty("connection_status") - @ExcludeMissing - fun _connectionStatus(): JsonField = connectionStatus - - @JsonProperty("provider_description") - @ExcludeMissing - fun _providerDescription(): JsonField = providerDescription - - @JsonProperty("provider_id") @ExcludeMissing fun _providerId(): JsonField = providerId - - @JsonProperty("provider_type") - @ExcludeMissing - fun _providerType(): JsonField = providerType - - @JsonProperty("scopes") @ExcludeMissing fun _scopes(): JsonField> = scopes - - @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): UserConnectionResponse = apply { - if (validated) { - return@apply - } - - id() - connectionId() - connectionStatus() - providerDescription() - providerId() - providerType() - scopes() - userId() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [UserConnectionResponse]. */ - class Builder internal constructor() { - - private var id: JsonField = JsonMissing.of() - private var connectionId: JsonField = JsonMissing.of() - private var connectionStatus: JsonField = JsonMissing.of() - private var providerDescription: JsonField = JsonMissing.of() - private var providerId: JsonField = JsonMissing.of() - private var providerType: JsonField = JsonMissing.of() - private var providerUserInfo: JsonValue = JsonMissing.of() - private var scopes: JsonField>? = null - private var userId: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(userConnectionResponse: UserConnectionResponse) = apply { - id = userConnectionResponse.id - connectionId = userConnectionResponse.connectionId - connectionStatus = userConnectionResponse.connectionStatus - providerDescription = userConnectionResponse.providerDescription - providerId = userConnectionResponse.providerId - providerType = userConnectionResponse.providerType - providerUserInfo = userConnectionResponse.providerUserInfo - scopes = userConnectionResponse.scopes.map { it.toMutableList() } - userId = userConnectionResponse.userId - additionalProperties = userConnectionResponse.additionalProperties.toMutableMap() - } - - fun id(id: String) = id(JsonField.of(id)) - - fun id(id: JsonField) = apply { this.id = id } - - fun connectionId(connectionId: String) = connectionId(JsonField.of(connectionId)) - - fun connectionId(connectionId: JsonField) = apply { - this.connectionId = connectionId - } - - fun connectionStatus(connectionStatus: String) = - connectionStatus(JsonField.of(connectionStatus)) - - fun connectionStatus(connectionStatus: JsonField) = apply { - this.connectionStatus = connectionStatus - } - - fun providerDescription(providerDescription: String) = - providerDescription(JsonField.of(providerDescription)) - - fun providerDescription(providerDescription: JsonField) = apply { - this.providerDescription = providerDescription - } - - fun providerId(providerId: String) = providerId(JsonField.of(providerId)) - - fun providerId(providerId: JsonField) = apply { this.providerId = providerId } - - fun providerType(providerType: String) = providerType(JsonField.of(providerType)) - - fun providerType(providerType: JsonField) = apply { - this.providerType = providerType - } - - fun providerUserInfo(providerUserInfo: JsonValue) = apply { - this.providerUserInfo = providerUserInfo - } - - fun scopes(scopes: List) = scopes(JsonField.of(scopes)) - - fun scopes(scopes: JsonField>) = apply { - this.scopes = scopes.map { it.toMutableList() } - } - - fun addScope(scope: String) = apply { - scopes = - (scopes ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(scope) - } - } - - fun userId(userId: String) = userId(JsonField.of(userId)) - - fun userId(userId: JsonField) = apply { this.userId = userId } - - 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) - } - - fun build(): UserConnectionResponse = - UserConnectionResponse( - id, - connectionId, - connectionStatus, - providerDescription, - providerId, - providerType, - providerUserInfo, - (scopes ?: JsonMissing.of()).map { it.toImmutable() }, - userId, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is UserConnectionResponse && id == other.id && connectionId == other.connectionId && connectionStatus == other.connectionStatus && providerDescription == other.providerDescription && providerId == other.providerId && providerType == other.providerType && providerUserInfo == other.providerUserInfo && scopes == other.scopes && userId == other.userId && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(id, connectionId, connectionStatus, providerDescription, providerId, providerType, providerUserInfo, scopes, userId, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "UserConnectionResponse{id=$id, connectionId=$connectionId, connectionStatus=$connectionStatus, providerDescription=$providerDescription, providerId=$providerId, providerType=$providerType, providerUserInfo=$providerUserInfo, scopes=$scopes, userId=$userId, additionalProperties=$additionalProperties}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ValueSchema.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/ValueSchema.kt deleted file mode 100644 index a30b8eb..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ValueSchema.kt +++ /dev/null @@ -1,164 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.checkRequired -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import java.util.Objects -import java.util.Optional - -@NoAutoDetect -class ValueSchema -@JsonCreator -private constructor( - @JsonProperty("val_type") - @ExcludeMissing - private val valType: JsonField = JsonMissing.of(), - @JsonProperty("enum") - @ExcludeMissing - private val enum_: JsonField> = JsonMissing.of(), - @JsonProperty("inner_val_type") - @ExcludeMissing - private val innerValType: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), -) { - - fun valType(): String = valType.getRequired("val_type") - - fun enum_(): Optional> = Optional.ofNullable(enum_.getNullable("enum")) - - fun innerValType(): Optional = - Optional.ofNullable(innerValType.getNullable("inner_val_type")) - - @JsonProperty("val_type") @ExcludeMissing fun _valType(): JsonField = valType - - @JsonProperty("enum") @ExcludeMissing fun _enum_(): JsonField> = enum_ - - @JsonProperty("inner_val_type") - @ExcludeMissing - fun _innerValType(): JsonField = innerValType - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ValueSchema = apply { - if (validated) { - return@apply - } - - valType() - enum_() - innerValType() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ValueSchema]. */ - class Builder internal constructor() { - - private var valType: JsonField? = null - private var enum_: JsonField>? = null - private var innerValType: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(valueSchema: ValueSchema) = apply { - valType = valueSchema.valType - enum_ = valueSchema.enum_.map { it.toMutableList() } - innerValType = valueSchema.innerValType - additionalProperties = valueSchema.additionalProperties.toMutableMap() - } - - fun valType(valType: String) = valType(JsonField.of(valType)) - - fun valType(valType: JsonField) = apply { this.valType = valType } - - fun enum_(enum_: List) = enum_(JsonField.of(enum_)) - - fun enum_(enum_: JsonField>) = apply { - this.enum_ = enum_.map { it.toMutableList() } - } - - fun addEnum(enum_: String) = apply { - this.enum_ = - (this.enum_ ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(enum_) - } - } - - fun innerValType(innerValType: String) = innerValType(JsonField.of(innerValType)) - - fun innerValType(innerValType: JsonField) = apply { - this.innerValType = innerValType - } - - 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) - } - - fun build(): ValueSchema = - ValueSchema( - checkRequired("valType", valType), - (enum_ ?: JsonMissing.of()).map { it.toImmutable() }, - innerValType, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ValueSchema && valType == other.valType && enum_ == other.enum_ && innerValType == other.innerValType && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(valType, enum_, innerValType, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ValueSchema{valType=$valType, enum_=$enum_, innerValType=$innerValType, additionalProperties=$additionalProperties}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerHealthResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerHealthResponse.kt deleted file mode 100644 index aec2537..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerHealthResponse.kt +++ /dev/null @@ -1,150 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import java.util.Objects -import java.util.Optional - -@NoAutoDetect -class WorkerHealthResponse -@JsonCreator -private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("enabled") - @ExcludeMissing - private val enabled: JsonField = JsonMissing.of(), - @JsonProperty("healthy") - @ExcludeMissing - private val healthy: JsonField = JsonMissing.of(), - @JsonProperty("message") - @ExcludeMissing - private val message: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), -) { - - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - fun enabled(): Optional = Optional.ofNullable(enabled.getNullable("enabled")) - - fun healthy(): Optional = Optional.ofNullable(healthy.getNullable("healthy")) - - fun message(): Optional = Optional.ofNullable(message.getNullable("message")) - - @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - - @JsonProperty("enabled") @ExcludeMissing fun _enabled(): JsonField = enabled - - @JsonProperty("healthy") @ExcludeMissing fun _healthy(): JsonField = healthy - - @JsonProperty("message") @ExcludeMissing fun _message(): JsonField = message - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): WorkerHealthResponse = apply { - if (validated) { - return@apply - } - - id() - enabled() - healthy() - message() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [WorkerHealthResponse]. */ - class Builder internal constructor() { - - private var id: JsonField = JsonMissing.of() - private var enabled: JsonField = JsonMissing.of() - private var healthy: JsonField = JsonMissing.of() - private var message: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(workerHealthResponse: WorkerHealthResponse) = apply { - id = workerHealthResponse.id - enabled = workerHealthResponse.enabled - healthy = workerHealthResponse.healthy - message = workerHealthResponse.message - additionalProperties = workerHealthResponse.additionalProperties.toMutableMap() - } - - fun id(id: String) = id(JsonField.of(id)) - - fun id(id: JsonField) = apply { this.id = id } - - fun enabled(enabled: Boolean) = enabled(JsonField.of(enabled)) - - fun enabled(enabled: JsonField) = apply { this.enabled = enabled } - - fun healthy(healthy: Boolean) = healthy(JsonField.of(healthy)) - - fun healthy(healthy: JsonField) = apply { this.healthy = healthy } - - fun message(message: String) = message(JsonField.of(message)) - - fun message(message: JsonField) = apply { this.message = message } - - 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) - } - - fun build(): WorkerHealthResponse = - WorkerHealthResponse(id, enabled, healthy, message, additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is WorkerHealthResponse && id == other.id && enabled == other.enabled && healthy == other.healthy && message == other.message && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(id, enabled, healthy, message, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "WorkerHealthResponse{id=$id, enabled=$enabled, healthy=$healthy, message=$message, additionalProperties=$additionalProperties}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerListPage.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerListPage.kt deleted file mode 100644 index 6a9b148..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerListPage.kt +++ /dev/null @@ -1,203 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import dev.arcade.services.blocking.WorkerService -import java.util.Objects -import java.util.Optional -import java.util.stream.Stream -import java.util.stream.StreamSupport - -/** List all workers with their definitions */ -class WorkerListPage -private constructor( - private val workersService: WorkerService, - private val params: WorkerListParams, - private val response: Response, -) { - - fun response(): Response = response - - fun items(): List = response().items() - - fun totalCount(): Optional = response().totalCount() - - fun offset(): Optional = response().offset() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is WorkerListPage && workersService == other.workersService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(workersService, params, response) /* spotless:on */ - - override fun toString() = - "WorkerListPage{workersService=$workersService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - if (items().isEmpty()) { - return false - } - - return offset().orElse(0) + items().count() < totalCount().orElse(Long.MAX_VALUE) - } - - fun getNextPageParams(): Optional { - if (!hasNextPage()) { - return Optional.empty() - } - - return Optional.of( - WorkerListParams.builder() - .from(params) - .offset(offset().orElse(0) + items().count()) - .build() - ) - } - - fun getNextPage(): Optional { - return getNextPageParams().map { workersService.list(it) } - } - - fun autoPager(): AutoPager = AutoPager(this) - - companion object { - - @JvmStatic - fun of(workersService: WorkerService, params: WorkerListParams, response: Response) = - WorkerListPage(workersService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("items") - private val items: JsonField> = JsonMissing.of(), - @JsonProperty("total_count") private val totalCount: JsonField = JsonMissing.of(), - @JsonProperty("offset") private val offset: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun items(): List = items.getNullable("items") ?: listOf() - - fun totalCount(): Optional = - Optional.ofNullable(totalCount.getNullable("total_count")) - - fun offset(): Optional = Optional.ofNullable(offset.getNullable("offset")) - - @JsonProperty("items") - fun _items(): Optional>> = Optional.ofNullable(items) - - @JsonProperty("total_count") - fun _totalCount(): Optional> = Optional.ofNullable(totalCount) - - @JsonProperty("offset") - fun _offset(): Optional> = Optional.ofNullable(offset) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - items().map { it.validate() } - totalCount() - offset() - validated = true - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && items == other.items && totalCount == other.totalCount && offset == other.offset && additionalProperties == other.additionalProperties /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(items, totalCount, offset, additionalProperties) /* spotless:on */ - - override fun toString() = - "Response{items=$items, totalCount=$totalCount, offset=$offset, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var items: JsonField> = JsonMissing.of() - private var totalCount: JsonField = JsonMissing.of() - private var offset: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.items = page.items - this.totalCount = page.totalCount - this.offset = page.offset - this.additionalProperties.putAll(page.additionalProperties) - } - - fun items(items: List) = items(JsonField.of(items)) - - fun items(items: JsonField>) = apply { this.items = items } - - fun totalCount(totalCount: Long) = totalCount(JsonField.of(totalCount)) - - fun totalCount(totalCount: JsonField) = apply { this.totalCount = totalCount } - - fun offset(offset: Long) = offset(JsonField.of(offset)) - - fun offset(offset: JsonField) = apply { this.offset = offset } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun build() = Response(items, totalCount, offset, additionalProperties.toImmutable()) - } - } - - class AutoPager(private val firstPage: WorkerListPage) : Iterable { - - override fun iterator(): Iterator = iterator { - var page = firstPage - var index = 0 - while (true) { - while (index < page.items().size) { - yield(page.items()[index++]) - } - page = page.getNextPage().orElse(null) ?: break - index = 0 - } - } - - fun stream(): Stream { - return StreamSupport.stream(spliterator(), false) - } - } -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerListPageAsync.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerListPageAsync.kt deleted file mode 100644 index c8b26ef..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerListPageAsync.kt +++ /dev/null @@ -1,216 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import dev.arcade.services.async.WorkerServiceAsync -import java.util.Objects -import java.util.Optional -import java.util.concurrent.CompletableFuture -import java.util.concurrent.Executor -import java.util.function.Predicate - -/** List all workers with their definitions */ -class WorkerListPageAsync -private constructor( - private val workersService: WorkerServiceAsync, - private val params: WorkerListParams, - private val response: Response, -) { - - fun response(): Response = response - - fun items(): List = response().items() - - fun totalCount(): Optional = response().totalCount() - - fun offset(): Optional = response().offset() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is WorkerListPageAsync && workersService == other.workersService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(workersService, params, response) /* spotless:on */ - - override fun toString() = - "WorkerListPageAsync{workersService=$workersService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - if (items().isEmpty()) { - return false - } - - return offset().orElse(0) + items().count() < totalCount().orElse(Long.MAX_VALUE) - } - - fun getNextPageParams(): Optional { - if (!hasNextPage()) { - return Optional.empty() - } - - return Optional.of( - WorkerListParams.builder() - .from(params) - .offset(offset().orElse(0) + items().count()) - .build() - ) - } - - fun getNextPage(): CompletableFuture> { - return getNextPageParams() - .map { workersService.list(it).thenApply { Optional.of(it) } } - .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } - } - - fun autoPager(): AutoPager = AutoPager(this) - - companion object { - - @JvmStatic - fun of(workersService: WorkerServiceAsync, params: WorkerListParams, response: Response) = - WorkerListPageAsync(workersService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("items") - private val items: JsonField> = JsonMissing.of(), - @JsonProperty("total_count") private val totalCount: JsonField = JsonMissing.of(), - @JsonProperty("offset") private val offset: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun items(): List = items.getNullable("items") ?: listOf() - - fun totalCount(): Optional = - Optional.ofNullable(totalCount.getNullable("total_count")) - - fun offset(): Optional = Optional.ofNullable(offset.getNullable("offset")) - - @JsonProperty("items") - fun _items(): Optional>> = Optional.ofNullable(items) - - @JsonProperty("total_count") - fun _totalCount(): Optional> = Optional.ofNullable(totalCount) - - @JsonProperty("offset") - fun _offset(): Optional> = Optional.ofNullable(offset) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - items().map { it.validate() } - totalCount() - offset() - validated = true - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && items == other.items && totalCount == other.totalCount && offset == other.offset && additionalProperties == other.additionalProperties /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(items, totalCount, offset, additionalProperties) /* spotless:on */ - - override fun toString() = - "Response{items=$items, totalCount=$totalCount, offset=$offset, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var items: JsonField> = JsonMissing.of() - private var totalCount: JsonField = JsonMissing.of() - private var offset: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.items = page.items - this.totalCount = page.totalCount - this.offset = page.offset - this.additionalProperties.putAll(page.additionalProperties) - } - - fun items(items: List) = items(JsonField.of(items)) - - fun items(items: JsonField>) = apply { this.items = items } - - fun totalCount(totalCount: Long) = totalCount(JsonField.of(totalCount)) - - fun totalCount(totalCount: JsonField) = apply { this.totalCount = totalCount } - - fun offset(offset: Long) = offset(JsonField.of(offset)) - - fun offset(offset: JsonField) = apply { this.offset = offset } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun build() = Response(items, totalCount, offset, additionalProperties.toImmutable()) - } - } - - class AutoPager(private val firstPage: WorkerListPageAsync) { - - fun forEach( - action: Predicate, - executor: Executor, - ): CompletableFuture { - fun CompletableFuture>.forEach( - action: (WorkerResponse) -> Boolean, - executor: Executor, - ): CompletableFuture = - thenComposeAsync( - { page -> - page - .filter { it.items().all(action) } - .map { it.getNextPage().forEach(action, executor) } - .orElseGet { CompletableFuture.completedFuture(null) } - }, - executor, - ) - return CompletableFuture.completedFuture(Optional.of(firstPage)) - .forEach(action::test, executor) - } - - fun toList(executor: Executor): CompletableFuture> { - val values = mutableListOf() - return forEach(values::add, executor).thenApply { values } - } - } -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerResponse.kt deleted file mode 100644 index 0806721..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerResponse.kt +++ /dev/null @@ -1,2045 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.Enum -import dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import dev.arcade.errors.ArcadeInvalidDataException -import java.util.Objects -import java.util.Optional - -@NoAutoDetect -class WorkerResponse -@JsonCreator -private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("binding") - @ExcludeMissing - private val binding: JsonField = JsonMissing.of(), - @JsonProperty("enabled") - @ExcludeMissing - private val enabled: JsonField = JsonMissing.of(), - @JsonProperty("http") @ExcludeMissing private val http: JsonField = JsonMissing.of(), - @JsonProperty("managed") - @ExcludeMissing - private val managed: JsonField = JsonMissing.of(), - @JsonProperty("mcp") @ExcludeMissing private val mcp: JsonField = JsonMissing.of(), - @JsonProperty("requirements") - @ExcludeMissing - private val requirements: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), -) { - - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - fun binding(): Optional = Optional.ofNullable(binding.getNullable("binding")) - - fun enabled(): Optional = Optional.ofNullable(enabled.getNullable("enabled")) - - fun http(): Optional = Optional.ofNullable(http.getNullable("http")) - - fun managed(): Optional = Optional.ofNullable(managed.getNullable("managed")) - - fun mcp(): Optional = Optional.ofNullable(mcp.getNullable("mcp")) - - fun requirements(): Optional = - Optional.ofNullable(requirements.getNullable("requirements")) - - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - - @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - - @JsonProperty("binding") @ExcludeMissing fun _binding(): JsonField = binding - - @JsonProperty("enabled") @ExcludeMissing fun _enabled(): JsonField = enabled - - @JsonProperty("http") @ExcludeMissing fun _http(): JsonField = http - - @JsonProperty("managed") @ExcludeMissing fun _managed(): JsonField = managed - - @JsonProperty("mcp") @ExcludeMissing fun _mcp(): JsonField = mcp - - @JsonProperty("requirements") - @ExcludeMissing - fun _requirements(): JsonField = requirements - - @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): WorkerResponse = apply { - if (validated) { - return@apply - } - - id() - binding().ifPresent { it.validate() } - enabled() - http().ifPresent { it.validate() } - managed() - mcp().ifPresent { it.validate() } - requirements().ifPresent { it.validate() } - type() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [WorkerResponse]. */ - class Builder internal constructor() { - - private var id: JsonField = JsonMissing.of() - private var binding: JsonField = JsonMissing.of() - private var enabled: JsonField = JsonMissing.of() - private var http: JsonField = JsonMissing.of() - private var managed: JsonField = JsonMissing.of() - private var mcp: JsonField = JsonMissing.of() - private var requirements: JsonField = JsonMissing.of() - private var type: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(workerResponse: WorkerResponse) = apply { - id = workerResponse.id - binding = workerResponse.binding - enabled = workerResponse.enabled - http = workerResponse.http - managed = workerResponse.managed - mcp = workerResponse.mcp - requirements = workerResponse.requirements - type = workerResponse.type - additionalProperties = workerResponse.additionalProperties.toMutableMap() - } - - fun id(id: String) = id(JsonField.of(id)) - - fun id(id: JsonField) = apply { this.id = id } - - fun binding(binding: Binding) = binding(JsonField.of(binding)) - - fun binding(binding: JsonField) = apply { this.binding = binding } - - fun enabled(enabled: Boolean) = enabled(JsonField.of(enabled)) - - fun enabled(enabled: JsonField) = apply { this.enabled = enabled } - - fun http(http: Http) = http(JsonField.of(http)) - - fun http(http: JsonField) = apply { this.http = http } - - fun managed(managed: Boolean) = managed(JsonField.of(managed)) - - fun managed(managed: JsonField) = apply { this.managed = managed } - - fun mcp(mcp: Mcp) = mcp(JsonField.of(mcp)) - - fun mcp(mcp: JsonField) = apply { this.mcp = mcp } - - fun requirements(requirements: Requirements) = requirements(JsonField.of(requirements)) - - fun requirements(requirements: JsonField) = apply { - this.requirements = requirements - } - - fun type(type: Type) = type(JsonField.of(type)) - - 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) - } - - fun build(): WorkerResponse = - WorkerResponse( - id, - binding, - enabled, - http, - managed, - mcp, - requirements, - type, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class Binding - @JsonCreator - private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - - @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - - @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Binding = apply { - if (validated) { - return@apply - } - - id() - type() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Binding]. */ - class Builder internal constructor() { - - private var id: JsonField = JsonMissing.of() - private var type: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(binding: Binding) = apply { - id = binding.id - type = binding.type - additionalProperties = binding.additionalProperties.toMutableMap() - } - - fun id(id: String) = id(JsonField.of(id)) - - fun id(id: JsonField) = apply { this.id = id } - - fun type(type: Type) = type(JsonField.of(type)) - - 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) - } - - fun build(): Binding = Binding(id, type, additionalProperties.toImmutable()) - } - - 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 STATIC = of("static") - - @JvmField val TENANT = of("tenant") - - @JvmField val PROJECT = of("project") - - @JvmField val ACCOUNT = of("account") - - @JvmStatic fun of(value: String) = Type(JsonField.of(value)) - } - - /** An enum containing [Type]'s known values. */ - enum class Known { - STATIC, - TENANT, - PROJECT, - ACCOUNT, - } - - /** - * 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 { - STATIC, - TENANT, - PROJECT, - ACCOUNT, - /** 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) { - STATIC -> Value.STATIC - TENANT -> Value.TENANT - PROJECT -> Value.PROJECT - ACCOUNT -> Value.ACCOUNT - 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 ArcadeInvalidDataException if this class instance's value is a not a known - * member. - */ - fun known(): Known = - when (this) { - STATIC -> Known.STATIC - TENANT -> Known.TENANT - PROJECT -> Known.PROJECT - ACCOUNT -> Known.ACCOUNT - else -> throw ArcadeInvalidDataException("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 ArcadeInvalidDataException if this class instance's value does not have the - * expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - ArcadeInvalidDataException("Value is not a String") - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Type && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Binding && id == other.id && type == other.type && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(id, type, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Binding{id=$id, type=$type, additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class Http - @JsonCreator - private constructor( - @JsonProperty("retry") - @ExcludeMissing - private val retry: JsonField = JsonMissing.of(), - @JsonProperty("secret") - @ExcludeMissing - private val secret: JsonField = JsonMissing.of(), - @JsonProperty("timeout") - @ExcludeMissing - private val timeout: JsonField = JsonMissing.of(), - @JsonProperty("uri") @ExcludeMissing private val uri: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun retry(): Optional = Optional.ofNullable(retry.getNullable("retry")) - - fun secret(): Optional = Optional.ofNullable(secret.getNullable("secret")) - - fun timeout(): Optional = Optional.ofNullable(timeout.getNullable("timeout")) - - fun uri(): Optional = Optional.ofNullable(uri.getNullable("uri")) - - @JsonProperty("retry") @ExcludeMissing fun _retry(): JsonField = retry - - @JsonProperty("secret") @ExcludeMissing fun _secret(): JsonField = secret - - @JsonProperty("timeout") @ExcludeMissing fun _timeout(): JsonField = timeout - - @JsonProperty("uri") @ExcludeMissing fun _uri(): JsonField = uri - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Http = apply { - if (validated) { - return@apply - } - - retry() - secret().ifPresent { it.validate() } - timeout() - uri() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Http]. */ - class Builder internal constructor() { - - private var retry: JsonField = JsonMissing.of() - private var secret: JsonField = JsonMissing.of() - private var timeout: JsonField = JsonMissing.of() - private var uri: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(http: Http) = apply { - retry = http.retry - secret = http.secret - timeout = http.timeout - uri = http.uri - additionalProperties = http.additionalProperties.toMutableMap() - } - - fun retry(retry: Long) = retry(JsonField.of(retry)) - - fun retry(retry: JsonField) = apply { this.retry = retry } - - fun secret(secret: Secret) = secret(JsonField.of(secret)) - - fun secret(secret: JsonField) = apply { this.secret = secret } - - fun timeout(timeout: Long) = timeout(JsonField.of(timeout)) - - fun timeout(timeout: JsonField) = apply { this.timeout = timeout } - - fun uri(uri: String) = uri(JsonField.of(uri)) - - fun uri(uri: JsonField) = apply { this.uri = uri } - - 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) - } - - fun build(): Http = - Http(retry, secret, timeout, uri, additionalProperties.toImmutable()) - } - - @NoAutoDetect - class Secret - @JsonCreator - private constructor( - @JsonProperty("binding") - @ExcludeMissing - private val binding: JsonField = JsonMissing.of(), - @JsonProperty("editable") - @ExcludeMissing - private val editable: JsonField = JsonMissing.of(), - @JsonProperty("exists") - @ExcludeMissing - private val exists: JsonField = JsonMissing.of(), - @JsonProperty("hint") - @ExcludeMissing - private val hint: JsonField = JsonMissing.of(), - @JsonProperty("value") - @ExcludeMissing - private val value: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun binding(): Optional = Optional.ofNullable(binding.getNullable("binding")) - - fun editable(): Optional = - Optional.ofNullable(editable.getNullable("editable")) - - fun exists(): Optional = Optional.ofNullable(exists.getNullable("exists")) - - fun hint(): Optional = Optional.ofNullable(hint.getNullable("hint")) - - fun value(): Optional = Optional.ofNullable(value.getNullable("value")) - - @JsonProperty("binding") @ExcludeMissing fun _binding(): JsonField = binding - - @JsonProperty("editable") @ExcludeMissing fun _editable(): JsonField = editable - - @JsonProperty("exists") @ExcludeMissing fun _exists(): JsonField = exists - - @JsonProperty("hint") @ExcludeMissing fun _hint(): JsonField = hint - - @JsonProperty("value") @ExcludeMissing fun _value(): JsonField = value - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Secret = apply { - if (validated) { - return@apply - } - - binding() - editable() - exists() - hint() - value() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Secret]. */ - class Builder internal constructor() { - - private var binding: JsonField = JsonMissing.of() - private var editable: JsonField = JsonMissing.of() - private var exists: JsonField = JsonMissing.of() - private var hint: JsonField = JsonMissing.of() - private var value: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(secret: Secret) = apply { - binding = secret.binding - editable = secret.editable - exists = secret.exists - hint = secret.hint - value = secret.value - additionalProperties = secret.additionalProperties.toMutableMap() - } - - fun binding(binding: Binding) = binding(JsonField.of(binding)) - - fun binding(binding: JsonField) = apply { this.binding = binding } - - fun editable(editable: Boolean) = editable(JsonField.of(editable)) - - fun editable(editable: JsonField) = apply { this.editable = editable } - - fun exists(exists: Boolean) = exists(JsonField.of(exists)) - - fun exists(exists: JsonField) = apply { this.exists = exists } - - fun hint(hint: String) = hint(JsonField.of(hint)) - - fun hint(hint: JsonField) = apply { this.hint = hint } - - fun value(value: String) = value(JsonField.of(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) - } - - fun build(): Secret = - Secret( - binding, - editable, - exists, - hint, - value, - additionalProperties.toImmutable(), - ) - } - - class Binding @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 STATIC = of("static") - - @JvmField val TENANT = of("tenant") - - @JvmField val PROJECT = of("project") - - @JvmField val ACCOUNT = of("account") - - @JvmStatic fun of(value: String) = Binding(JsonField.of(value)) - } - - /** An enum containing [Binding]'s known values. */ - enum class Known { - STATIC, - TENANT, - PROJECT, - ACCOUNT, - } - - /** - * An enum containing [Binding]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [Binding] 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 { - STATIC, - TENANT, - PROJECT, - ACCOUNT, - /** - * An enum member indicating that [Binding] 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) { - STATIC -> Value.STATIC - TENANT -> Value.TENANT - PROJECT -> Value.PROJECT - ACCOUNT -> Value.ACCOUNT - 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 ArcadeInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - STATIC -> Known.STATIC - TENANT -> Known.TENANT - PROJECT -> Known.PROJECT - ACCOUNT -> Known.ACCOUNT - else -> throw ArcadeInvalidDataException("Unknown Binding: $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 ArcadeInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - ArcadeInvalidDataException("Value is not a String") - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Binding && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Secret && binding == other.binding && editable == other.editable && exists == other.exists && hint == other.hint && value == other.value && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(binding, editable, exists, hint, value, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Secret{binding=$binding, editable=$editable, exists=$exists, hint=$hint, value=$value, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Http && retry == other.retry && secret == other.secret && timeout == other.timeout && uri == other.uri && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(retry, secret, timeout, uri, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Http{retry=$retry, secret=$secret, timeout=$timeout, uri=$uri, additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class Mcp - @JsonCreator - private constructor( - @JsonProperty("headers") - @ExcludeMissing - private val headers: JsonField = JsonMissing.of(), - @JsonProperty("oauth2") - @ExcludeMissing - private val oauth2: JsonField = JsonMissing.of(), - @JsonProperty("retry") - @ExcludeMissing - private val retry: JsonField = JsonMissing.of(), - @JsonProperty("secrets") - @ExcludeMissing - private val secrets: JsonField = JsonMissing.of(), - @JsonProperty("timeout") - @ExcludeMissing - private val timeout: JsonField = JsonMissing.of(), - @JsonProperty("uri") @ExcludeMissing private val uri: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun headers(): Optional = Optional.ofNullable(headers.getNullable("headers")) - - fun oauth2(): Optional = Optional.ofNullable(oauth2.getNullable("oauth2")) - - fun retry(): Optional = Optional.ofNullable(retry.getNullable("retry")) - - fun secrets(): Optional = Optional.ofNullable(secrets.getNullable("secrets")) - - fun timeout(): Optional = Optional.ofNullable(timeout.getNullable("timeout")) - - fun uri(): Optional = Optional.ofNullable(uri.getNullable("uri")) - - @JsonProperty("headers") @ExcludeMissing fun _headers(): JsonField = headers - - @JsonProperty("oauth2") @ExcludeMissing fun _oauth2(): JsonField = oauth2 - - @JsonProperty("retry") @ExcludeMissing fun _retry(): JsonField = retry - - @JsonProperty("secrets") @ExcludeMissing fun _secrets(): JsonField = secrets - - @JsonProperty("timeout") @ExcludeMissing fun _timeout(): JsonField = timeout - - @JsonProperty("uri") @ExcludeMissing fun _uri(): JsonField = uri - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Mcp = apply { - if (validated) { - return@apply - } - - headers().ifPresent { it.validate() } - oauth2().ifPresent { it.validate() } - retry() - secrets().ifPresent { it.validate() } - timeout() - uri() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Mcp]. */ - class Builder internal constructor() { - - private var headers: JsonField = JsonMissing.of() - private var oauth2: JsonField = JsonMissing.of() - private var retry: JsonField = JsonMissing.of() - private var secrets: JsonField = JsonMissing.of() - private var timeout: JsonField = JsonMissing.of() - private var uri: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(mcp: Mcp) = apply { - headers = mcp.headers - oauth2 = mcp.oauth2 - retry = mcp.retry - secrets = mcp.secrets - timeout = mcp.timeout - uri = mcp.uri - additionalProperties = mcp.additionalProperties.toMutableMap() - } - - fun headers(headers: Headers) = headers(JsonField.of(headers)) - - fun headers(headers: JsonField) = apply { this.headers = headers } - - fun oauth2(oauth2: Oauth2) = oauth2(JsonField.of(oauth2)) - - fun oauth2(oauth2: JsonField) = apply { this.oauth2 = oauth2 } - - fun retry(retry: Long) = retry(JsonField.of(retry)) - - fun retry(retry: JsonField) = apply { this.retry = retry } - - fun secrets(secrets: Secrets) = secrets(JsonField.of(secrets)) - - fun secrets(secrets: JsonField) = apply { this.secrets = secrets } - - fun timeout(timeout: Long) = timeout(JsonField.of(timeout)) - - fun timeout(timeout: JsonField) = apply { this.timeout = timeout } - - fun uri(uri: String) = uri(JsonField.of(uri)) - - fun uri(uri: JsonField) = apply { this.uri = uri } - - 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) - } - - fun build(): Mcp = - Mcp( - headers, - oauth2, - retry, - secrets, - timeout, - uri, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class Headers - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Headers = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Headers]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(headers: Headers) = apply { - additionalProperties = headers.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) - } - - fun build(): Headers = Headers(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Headers && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "Headers{additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class Oauth2 - @JsonCreator - private constructor( - @JsonProperty("authorization_url") - @ExcludeMissing - private val authorizationUrl: JsonField = JsonMissing.of(), - @JsonProperty("client_id") - @ExcludeMissing - private val clientId: JsonField = JsonMissing.of(), - @JsonProperty("client_secret") - @ExcludeMissing - private val clientSecret: JsonField = JsonMissing.of(), - @JsonProperty("redirect_uri") - @ExcludeMissing - private val redirectUri: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun authorizationUrl(): Optional = - Optional.ofNullable(authorizationUrl.getNullable("authorization_url")) - - fun clientId(): Optional = - Optional.ofNullable(clientId.getNullable("client_id")) - - fun clientSecret(): Optional = - Optional.ofNullable(clientSecret.getNullable("client_secret")) - - fun redirectUri(): Optional = - Optional.ofNullable(redirectUri.getNullable("redirect_uri")) - - @JsonProperty("authorization_url") - @ExcludeMissing - fun _authorizationUrl(): JsonField = authorizationUrl - - @JsonProperty("client_id") @ExcludeMissing fun _clientId(): JsonField = clientId - - @JsonProperty("client_secret") - @ExcludeMissing - fun _clientSecret(): JsonField = clientSecret - - @JsonProperty("redirect_uri") - @ExcludeMissing - fun _redirectUri(): JsonField = redirectUri - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Oauth2 = apply { - if (validated) { - return@apply - } - - authorizationUrl() - clientId() - clientSecret().ifPresent { it.validate() } - redirectUri() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Oauth2]. */ - class Builder internal constructor() { - - private var authorizationUrl: JsonField = JsonMissing.of() - private var clientId: JsonField = JsonMissing.of() - private var clientSecret: JsonField = JsonMissing.of() - private var redirectUri: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(oauth2: Oauth2) = apply { - authorizationUrl = oauth2.authorizationUrl - clientId = oauth2.clientId - clientSecret = oauth2.clientSecret - redirectUri = oauth2.redirectUri - additionalProperties = oauth2.additionalProperties.toMutableMap() - } - - fun authorizationUrl(authorizationUrl: String) = - authorizationUrl(JsonField.of(authorizationUrl)) - - fun authorizationUrl(authorizationUrl: JsonField) = apply { - this.authorizationUrl = authorizationUrl - } - - fun clientId(clientId: String) = clientId(JsonField.of(clientId)) - - fun clientId(clientId: JsonField) = apply { this.clientId = clientId } - - fun clientSecret(clientSecret: ClientSecret) = - clientSecret(JsonField.of(clientSecret)) - - fun clientSecret(clientSecret: JsonField) = apply { - this.clientSecret = clientSecret - } - - fun redirectUri(redirectUri: String) = redirectUri(JsonField.of(redirectUri)) - - fun redirectUri(redirectUri: JsonField) = apply { - this.redirectUri = redirectUri - } - - 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) - } - - fun build(): Oauth2 = - Oauth2( - authorizationUrl, - clientId, - clientSecret, - redirectUri, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class ClientSecret - @JsonCreator - private constructor( - @JsonProperty("binding") - @ExcludeMissing - private val binding: JsonField = JsonMissing.of(), - @JsonProperty("editable") - @ExcludeMissing - private val editable: JsonField = JsonMissing.of(), - @JsonProperty("exists") - @ExcludeMissing - private val exists: JsonField = JsonMissing.of(), - @JsonProperty("hint") - @ExcludeMissing - private val hint: JsonField = JsonMissing.of(), - @JsonProperty("value") - @ExcludeMissing - private val value: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun binding(): Optional = - Optional.ofNullable(binding.getNullable("binding")) - - fun editable(): Optional = - Optional.ofNullable(editable.getNullable("editable")) - - fun exists(): Optional = Optional.ofNullable(exists.getNullable("exists")) - - fun hint(): Optional = Optional.ofNullable(hint.getNullable("hint")) - - fun value(): Optional = Optional.ofNullable(value.getNullable("value")) - - @JsonProperty("binding") - @ExcludeMissing - fun _binding(): JsonField = binding - - @JsonProperty("editable") - @ExcludeMissing - fun _editable(): JsonField = editable - - @JsonProperty("exists") @ExcludeMissing fun _exists(): JsonField = exists - - @JsonProperty("hint") @ExcludeMissing fun _hint(): JsonField = hint - - @JsonProperty("value") @ExcludeMissing fun _value(): JsonField = value - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ClientSecret = apply { - if (validated) { - return@apply - } - - binding() - editable() - exists() - hint() - value() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ClientSecret]. */ - class Builder internal constructor() { - - private var binding: JsonField = JsonMissing.of() - private var editable: JsonField = JsonMissing.of() - private var exists: JsonField = JsonMissing.of() - private var hint: JsonField = JsonMissing.of() - private var value: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(clientSecret: ClientSecret) = apply { - binding = clientSecret.binding - editable = clientSecret.editable - exists = clientSecret.exists - hint = clientSecret.hint - value = clientSecret.value - additionalProperties = clientSecret.additionalProperties.toMutableMap() - } - - fun binding(binding: Binding) = binding(JsonField.of(binding)) - - fun binding(binding: JsonField) = apply { this.binding = binding } - - fun editable(editable: Boolean) = editable(JsonField.of(editable)) - - fun editable(editable: JsonField) = apply { this.editable = editable } - - fun exists(exists: Boolean) = exists(JsonField.of(exists)) - - fun exists(exists: JsonField) = apply { this.exists = exists } - - fun hint(hint: String) = hint(JsonField.of(hint)) - - fun hint(hint: JsonField) = apply { this.hint = hint } - - fun value(value: String) = value(JsonField.of(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) - } - - fun build(): ClientSecret = - ClientSecret( - binding, - editable, - exists, - hint, - value, - additionalProperties.toImmutable(), - ) - } - - class Binding - @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 STATIC = of("static") - - @JvmField val TENANT = of("tenant") - - @JvmField val PROJECT = of("project") - - @JvmField val ACCOUNT = of("account") - - @JvmStatic fun of(value: String) = Binding(JsonField.of(value)) - } - - /** An enum containing [Binding]'s known values. */ - enum class Known { - STATIC, - TENANT, - PROJECT, - ACCOUNT, - } - - /** - * An enum containing [Binding]'s known values, as well as an [_UNKNOWN] member. - * - * An instance of [Binding] 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 { - STATIC, - TENANT, - PROJECT, - ACCOUNT, - /** - * An enum member indicating that [Binding] 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) { - STATIC -> Value.STATIC - TENANT -> Value.TENANT - PROJECT -> Value.PROJECT - ACCOUNT -> Value.ACCOUNT - 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 ArcadeInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - STATIC -> Known.STATIC - TENANT -> Known.TENANT - PROJECT -> Known.PROJECT - ACCOUNT -> Known.ACCOUNT - else -> throw ArcadeInvalidDataException("Unknown Binding: $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 ArcadeInvalidDataException if this class instance's value does not - * have the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - ArcadeInvalidDataException("Value is not a String") - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Binding && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ClientSecret && binding == other.binding && editable == other.editable && exists == other.exists && hint == other.hint && value == other.value && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(binding, editable, exists, hint, value, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "ClientSecret{binding=$binding, editable=$editable, exists=$exists, hint=$hint, value=$value, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Oauth2 && authorizationUrl == other.authorizationUrl && clientId == other.clientId && clientSecret == other.clientSecret && redirectUri == other.redirectUri && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(authorizationUrl, clientId, clientSecret, redirectUri, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Oauth2{authorizationUrl=$authorizationUrl, clientId=$clientId, clientSecret=$clientSecret, redirectUri=$redirectUri, additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class Secrets - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Secrets = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Secrets]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(secrets: Secrets) = apply { - additionalProperties = secrets.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) - } - - fun build(): Secrets = Secrets(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Secrets && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "Secrets{additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Mcp && headers == other.headers && oauth2 == other.oauth2 && retry == other.retry && secrets == other.secrets && timeout == other.timeout && uri == other.uri && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(headers, oauth2, retry, secrets, timeout, uri, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Mcp{headers=$headers, oauth2=$oauth2, retry=$retry, secrets=$secrets, timeout=$timeout, uri=$uri, additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class Requirements - @JsonCreator - private constructor( - @JsonProperty("authorization") - @ExcludeMissing - private val authorization: JsonField = JsonMissing.of(), - @JsonProperty("met") @ExcludeMissing private val met: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun authorization(): Optional = - Optional.ofNullable(authorization.getNullable("authorization")) - - fun met(): Optional = Optional.ofNullable(met.getNullable("met")) - - @JsonProperty("authorization") - @ExcludeMissing - fun _authorization(): JsonField = authorization - - @JsonProperty("met") @ExcludeMissing fun _met(): JsonField = met - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Requirements = apply { - if (validated) { - return@apply - } - - authorization().ifPresent { it.validate() } - met() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Requirements]. */ - class Builder internal constructor() { - - private var authorization: JsonField = JsonMissing.of() - private var met: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(requirements: Requirements) = apply { - authorization = requirements.authorization - met = requirements.met - additionalProperties = requirements.additionalProperties.toMutableMap() - } - - fun authorization(authorization: Authorization) = - authorization(JsonField.of(authorization)) - - fun authorization(authorization: JsonField) = apply { - this.authorization = authorization - } - - fun met(met: Boolean) = met(JsonField.of(met)) - - fun met(met: JsonField) = apply { this.met = met } - - 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) - } - - fun build(): Requirements = - Requirements(authorization, met, additionalProperties.toImmutable()) - } - - @NoAutoDetect - class Authorization - @JsonCreator - private constructor( - @JsonProperty("met") - @ExcludeMissing - private val met: JsonField = JsonMissing.of(), - @JsonProperty("oauth2") - @ExcludeMissing - private val oauth2: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun met(): Optional = Optional.ofNullable(met.getNullable("met")) - - fun oauth2(): Optional = Optional.ofNullable(oauth2.getNullable("oauth2")) - - @JsonProperty("met") @ExcludeMissing fun _met(): JsonField = met - - @JsonProperty("oauth2") @ExcludeMissing fun _oauth2(): JsonField = oauth2 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Authorization = apply { - if (validated) { - return@apply - } - - met() - oauth2().ifPresent { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Authorization]. */ - class Builder internal constructor() { - - private var met: JsonField = JsonMissing.of() - private var oauth2: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(authorization: Authorization) = apply { - met = authorization.met - oauth2 = authorization.oauth2 - additionalProperties = authorization.additionalProperties.toMutableMap() - } - - fun met(met: Boolean) = met(JsonField.of(met)) - - fun met(met: JsonField) = apply { this.met = met } - - fun oauth2(oauth2: Oauth2) = oauth2(JsonField.of(oauth2)) - - fun oauth2(oauth2: JsonField) = apply { this.oauth2 = oauth2 } - - 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) - } - - fun build(): Authorization = - Authorization(met, oauth2, additionalProperties.toImmutable()) - } - - @NoAutoDetect - class Oauth2 - @JsonCreator - private constructor( - @JsonProperty("met") - @ExcludeMissing - private val met: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun met(): Optional = Optional.ofNullable(met.getNullable("met")) - - @JsonProperty("met") @ExcludeMissing fun _met(): JsonField = met - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Oauth2 = apply { - if (validated) { - return@apply - } - - met() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Oauth2]. */ - class Builder internal constructor() { - - private var met: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(oauth2: Oauth2) = apply { - met = oauth2.met - additionalProperties = oauth2.additionalProperties.toMutableMap() - } - - fun met(met: Boolean) = met(JsonField.of(met)) - - fun met(met: JsonField) = apply { this.met = met } - - 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) - } - - fun build(): Oauth2 = Oauth2(met, additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Oauth2 && met == other.met && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(met, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Oauth2{met=$met, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Authorization && met == other.met && oauth2 == other.oauth2 && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(met, oauth2, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Authorization{met=$met, oauth2=$oauth2, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Requirements && authorization == other.authorization && met == other.met && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(authorization, met, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Requirements{authorization=$authorization, met=$met, additionalProperties=$additionalProperties}" - } - - 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 HTTP = of("http") - - @JvmField val MCP = of("mcp") - - @JvmField val UNKNOWN = of("unknown") - - @JvmStatic fun of(value: String) = Type(JsonField.of(value)) - } - - /** An enum containing [Type]'s known values. */ - enum class Known { - HTTP, - MCP, - UNKNOWN, - } - - /** - * 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 { - HTTP, - MCP, - UNKNOWN, - /** 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) { - HTTP -> Value.HTTP - MCP -> Value.MCP - UNKNOWN -> Value.UNKNOWN - 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 ArcadeInvalidDataException if this class instance's value is a not a known - * member. - */ - fun known(): Known = - when (this) { - HTTP -> Known.HTTP - MCP -> Known.MCP - UNKNOWN -> Known.UNKNOWN - else -> throw ArcadeInvalidDataException("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 ArcadeInvalidDataException if this class instance's value does not have the - * expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { ArcadeInvalidDataException("Value is not a String") } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Type && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is WorkerResponse && id == other.id && binding == other.binding && enabled == other.enabled && http == other.http && managed == other.managed && mcp == other.mcp && requirements == other.requirements && type == other.type && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(id, binding, enabled, http, managed, mcp, requirements, type, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "WorkerResponse{id=$id, binding=$binding, enabled=$enabled, http=$http, managed=$managed, mcp=$mcp, requirements=$requirements, type=$type, additionalProperties=$additionalProperties}" -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerToolsPage.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerToolsPage.kt deleted file mode 100644 index 3f200c6..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerToolsPage.kt +++ /dev/null @@ -1,203 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import dev.arcade.services.blocking.WorkerService -import java.util.Objects -import java.util.Optional -import java.util.stream.Stream -import java.util.stream.StreamSupport - -/** Returns a page of tools */ -class WorkerToolsPage -private constructor( - private val workersService: WorkerService, - private val params: WorkerToolsParams, - private val response: Response, -) { - - fun response(): Response = response - - fun items(): List = response().items() - - fun totalCount(): Optional = response().totalCount() - - fun offset(): Optional = response().offset() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is WorkerToolsPage && workersService == other.workersService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(workersService, params, response) /* spotless:on */ - - override fun toString() = - "WorkerToolsPage{workersService=$workersService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - if (items().isEmpty()) { - return false - } - - return offset().orElse(0) + items().count() < totalCount().orElse(Long.MAX_VALUE) - } - - fun getNextPageParams(): Optional { - if (!hasNextPage()) { - return Optional.empty() - } - - return Optional.of( - WorkerToolsParams.builder() - .from(params) - .offset(offset().orElse(0) + items().count()) - .build() - ) - } - - fun getNextPage(): Optional { - return getNextPageParams().map { workersService.tools(it) } - } - - fun autoPager(): AutoPager = AutoPager(this) - - companion object { - - @JvmStatic - fun of(workersService: WorkerService, params: WorkerToolsParams, response: Response) = - WorkerToolsPage(workersService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("items") - private val items: JsonField> = JsonMissing.of(), - @JsonProperty("total_count") private val totalCount: JsonField = JsonMissing.of(), - @JsonProperty("offset") private val offset: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun items(): List = items.getNullable("items") ?: listOf() - - fun totalCount(): Optional = - Optional.ofNullable(totalCount.getNullable("total_count")) - - fun offset(): Optional = Optional.ofNullable(offset.getNullable("offset")) - - @JsonProperty("items") - fun _items(): Optional>> = Optional.ofNullable(items) - - @JsonProperty("total_count") - fun _totalCount(): Optional> = Optional.ofNullable(totalCount) - - @JsonProperty("offset") - fun _offset(): Optional> = Optional.ofNullable(offset) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - items().map { it.validate() } - totalCount() - offset() - validated = true - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && items == other.items && totalCount == other.totalCount && offset == other.offset && additionalProperties == other.additionalProperties /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(items, totalCount, offset, additionalProperties) /* spotless:on */ - - override fun toString() = - "Response{items=$items, totalCount=$totalCount, offset=$offset, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var items: JsonField> = JsonMissing.of() - private var totalCount: JsonField = JsonMissing.of() - private var offset: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.items = page.items - this.totalCount = page.totalCount - this.offset = page.offset - this.additionalProperties.putAll(page.additionalProperties) - } - - fun items(items: List) = items(JsonField.of(items)) - - fun items(items: JsonField>) = apply { this.items = items } - - fun totalCount(totalCount: Long) = totalCount(JsonField.of(totalCount)) - - fun totalCount(totalCount: JsonField) = apply { this.totalCount = totalCount } - - fun offset(offset: Long) = offset(JsonField.of(offset)) - - fun offset(offset: JsonField) = apply { this.offset = offset } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun build() = Response(items, totalCount, offset, additionalProperties.toImmutable()) - } - } - - class AutoPager(private val firstPage: WorkerToolsPage) : Iterable { - - override fun iterator(): Iterator = iterator { - var page = firstPage - var index = 0 - while (true) { - while (index < page.items().size) { - yield(page.items()[index++]) - } - page = page.getNextPage().orElse(null) ?: break - index = 0 - } - } - - fun stream(): Stream { - return StreamSupport.stream(spliterator(), false) - } - } -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerToolsPageAsync.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerToolsPageAsync.kt deleted file mode 100644 index 573a6db..0000000 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerToolsPageAsync.kt +++ /dev/null @@ -1,216 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.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 dev.arcade.core.ExcludeMissing -import dev.arcade.core.JsonField -import dev.arcade.core.JsonMissing -import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable -import dev.arcade.services.async.WorkerServiceAsync -import java.util.Objects -import java.util.Optional -import java.util.concurrent.CompletableFuture -import java.util.concurrent.Executor -import java.util.function.Predicate - -/** Returns a page of tools */ -class WorkerToolsPageAsync -private constructor( - private val workersService: WorkerServiceAsync, - private val params: WorkerToolsParams, - private val response: Response, -) { - - fun response(): Response = response - - fun items(): List = response().items() - - fun totalCount(): Optional = response().totalCount() - - fun offset(): Optional = response().offset() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is WorkerToolsPageAsync && workersService == other.workersService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(workersService, params, response) /* spotless:on */ - - override fun toString() = - "WorkerToolsPageAsync{workersService=$workersService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - if (items().isEmpty()) { - return false - } - - return offset().orElse(0) + items().count() < totalCount().orElse(Long.MAX_VALUE) - } - - fun getNextPageParams(): Optional { - if (!hasNextPage()) { - return Optional.empty() - } - - return Optional.of( - WorkerToolsParams.builder() - .from(params) - .offset(offset().orElse(0) + items().count()) - .build() - ) - } - - fun getNextPage(): CompletableFuture> { - return getNextPageParams() - .map { workersService.tools(it).thenApply { Optional.of(it) } } - .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } - } - - fun autoPager(): AutoPager = AutoPager(this) - - companion object { - - @JvmStatic - fun of(workersService: WorkerServiceAsync, params: WorkerToolsParams, response: Response) = - WorkerToolsPageAsync(workersService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("items") - private val items: JsonField> = JsonMissing.of(), - @JsonProperty("total_count") private val totalCount: JsonField = JsonMissing.of(), - @JsonProperty("offset") private val offset: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun items(): List = items.getNullable("items") ?: listOf() - - fun totalCount(): Optional = - Optional.ofNullable(totalCount.getNullable("total_count")) - - fun offset(): Optional = Optional.ofNullable(offset.getNullable("offset")) - - @JsonProperty("items") - fun _items(): Optional>> = Optional.ofNullable(items) - - @JsonProperty("total_count") - fun _totalCount(): Optional> = Optional.ofNullable(totalCount) - - @JsonProperty("offset") - fun _offset(): Optional> = Optional.ofNullable(offset) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - items().map { it.validate() } - totalCount() - offset() - validated = true - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && items == other.items && totalCount == other.totalCount && offset == other.offset && additionalProperties == other.additionalProperties /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(items, totalCount, offset, additionalProperties) /* spotless:on */ - - override fun toString() = - "Response{items=$items, totalCount=$totalCount, offset=$offset, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var items: JsonField> = JsonMissing.of() - private var totalCount: JsonField = JsonMissing.of() - private var offset: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.items = page.items - this.totalCount = page.totalCount - this.offset = page.offset - this.additionalProperties.putAll(page.additionalProperties) - } - - fun items(items: List) = items(JsonField.of(items)) - - fun items(items: JsonField>) = apply { this.items = items } - - fun totalCount(totalCount: Long) = totalCount(JsonField.of(totalCount)) - - fun totalCount(totalCount: JsonField) = apply { this.totalCount = totalCount } - - fun offset(offset: Long) = offset(JsonField.of(offset)) - - fun offset(offset: JsonField) = apply { this.offset = offset } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun build() = Response(items, totalCount, offset, additionalProperties.toImmutable()) - } - } - - class AutoPager(private val firstPage: WorkerToolsPageAsync) { - - fun forEach( - action: Predicate, - executor: Executor, - ): CompletableFuture { - fun CompletableFuture>.forEach( - action: (ToolDefinition) -> Boolean, - executor: Executor, - ): CompletableFuture = - thenComposeAsync( - { page -> - page - .filter { it.items().all(action) } - .map { it.getNextPage().forEach(action, executor) } - .orElseGet { CompletableFuture.completedFuture(null) } - }, - executor, - ) - return CompletableFuture.completedFuture(Optional.of(firstPage)) - .forEach(action::test, executor) - } - - fun toList(executor: Executor): CompletableFuture> { - val values = mutableListOf() - return forEach(values::add, executor).thenApply { values } - } - } -} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminAuthProviderCreateParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/authproviders/AuthProviderCreateParams.kt similarity index 74% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/AdminAuthProviderCreateParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/admin/authproviders/AuthProviderCreateParams.kt index 446f46e..041934e 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminAuthProviderCreateParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/authproviders/AuthProviderCreateParams.kt @@ -1,9 +1,8 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.admin.authproviders import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params import dev.arcade.core.checkRequired import dev.arcade.core.http.Headers @@ -11,7 +10,7 @@ import dev.arcade.core.http.QueryParams import java.util.Objects /** Create a new auth provider */ -class AdminAuthProviderCreateParams +class AuthProviderCreateParams private constructor( private val authProviderCreateRequest: AuthProviderCreateRequest, private val additionalHeaders: Headers, @@ -23,25 +22,28 @@ private constructor( fun _additionalBodyProperties(): Map = authProviderCreateRequest._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): AuthProviderCreateRequest = authProviderCreateRequest - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [AuthProviderCreateParams]. + * + * The following fields are required: + * ```java + * .authProviderCreateRequest() + * ``` + */ @JvmStatic fun builder() = Builder() } - /** A builder for [AdminAuthProviderCreateParams]. */ - @NoAutoDetect + /** A builder for [AuthProviderCreateParams]. */ class Builder internal constructor() { private var authProviderCreateRequest: AuthProviderCreateRequest? = null @@ -49,10 +51,10 @@ private constructor( private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @JvmSynthetic - internal fun from(adminAuthProviderCreateParams: AdminAuthProviderCreateParams) = apply { - authProviderCreateRequest = adminAuthProviderCreateParams.authProviderCreateRequest - additionalHeaders = adminAuthProviderCreateParams.additionalHeaders.toBuilder() - additionalQueryParams = adminAuthProviderCreateParams.additionalQueryParams.toBuilder() + internal fun from(authProviderCreateParams: AuthProviderCreateParams) = apply { + authProviderCreateRequest = authProviderCreateParams.authProviderCreateRequest + additionalHeaders = authProviderCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = authProviderCreateParams.additionalQueryParams.toBuilder() } fun authProviderCreateRequest(authProviderCreateRequest: AuthProviderCreateRequest) = @@ -158,24 +160,46 @@ private constructor( additionalQueryParams.removeAll(keys) } - fun build(): AdminAuthProviderCreateParams = - AdminAuthProviderCreateParams( + /** + * Returns an immutable instance of [AuthProviderCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .authProviderCreateRequest() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AuthProviderCreateParams = + AuthProviderCreateParams( checkRequired("authProviderCreateRequest", authProviderCreateRequest), additionalHeaders.build(), additionalQueryParams.build(), ) } + fun _body(): AuthProviderCreateRequest = authProviderCreateRequest + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is AdminAuthProviderCreateParams && authProviderCreateRequest == other.authProviderCreateRequest && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is AuthProviderCreateParams && + authProviderCreateRequest == other.authProviderCreateRequest && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(authProviderCreateRequest, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(authProviderCreateRequest, additionalHeaders, additionalQueryParams) override fun toString() = - "AdminAuthProviderCreateParams{authProviderCreateRequest=$authProviderCreateRequest, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" + "AuthProviderCreateParams{authProviderCreateRequest=$authProviderCreateRequest, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/authproviders/AuthProviderCreateRequest.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/authproviders/AuthProviderCreateRequest.kt new file mode 100644 index 0000000..dbff3f9 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/authproviders/AuthProviderCreateRequest.kt @@ -0,0 +1,6370 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.admin.authproviders + +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 dev.arcade.core.Enum +import dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.core.checkRequired +import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class AuthProviderCreateRequest +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val id: JsonField, + private val description: JsonField, + private val externalId: JsonField, + private val oauth2: JsonField, + private val providerId: JsonField, + private val status: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("external_id") + @ExcludeMissing + externalId: JsonField = JsonMissing.of(), + @JsonProperty("oauth2") @ExcludeMissing oauth2: JsonField = JsonMissing.of(), + @JsonProperty("provider_id") + @ExcludeMissing + providerId: JsonField = JsonMissing.of(), + @JsonProperty("status") @ExcludeMissing status: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(id, description, externalId, oauth2, providerId, status, type, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException 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 ArcadeInvalidDataException 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 unique external ID for the auth provider + * + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun externalId(): Optional = externalId.getOptional("external_id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun oauth2(): Optional = oauth2.getOptional("oauth2") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun providerId(): Optional = providerId.getOptional("provider_id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun status(): Optional = status.getOptional("status") + + /** + * @throws ArcadeInvalidDataException 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 [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 [externalId]. + * + * Unlike [externalId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("external_id") @ExcludeMissing fun _externalId(): JsonField = externalId + + /** + * Returns the raw JSON value of [oauth2]. + * + * Unlike [oauth2], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("oauth2") @ExcludeMissing fun _oauth2(): JsonField = oauth2 + + /** + * Returns the raw JSON value of [providerId]. + * + * Unlike [providerId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("provider_id") @ExcludeMissing fun _providerId(): JsonField = providerId + + /** + * 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 [AuthProviderCreateRequest]. + * + * The following fields are required: + * ```java + * .id() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AuthProviderCreateRequest]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var description: JsonField = JsonMissing.of() + private var externalId: JsonField = JsonMissing.of() + private var oauth2: JsonField = JsonMissing.of() + private var providerId: JsonField = JsonMissing.of() + private var status: JsonField = JsonMissing.of() + private var type: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(authProviderCreateRequest: AuthProviderCreateRequest) = apply { + id = authProviderCreateRequest.id + description = authProviderCreateRequest.description + externalId = authProviderCreateRequest.externalId + oauth2 = authProviderCreateRequest.oauth2 + providerId = authProviderCreateRequest.providerId + status = authProviderCreateRequest.status + type = authProviderCreateRequest.type + additionalProperties = authProviderCreateRequest.additionalProperties.toMutableMap() + } + + 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 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 unique external ID for the auth provider */ + fun externalId(externalId: String) = externalId(JsonField.of(externalId)) + + /** + * Sets [Builder.externalId] to an arbitrary JSON value. + * + * You should usually call [Builder.externalId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun externalId(externalId: JsonField) = apply { this.externalId = externalId } + + fun oauth2(oauth2: Oauth2) = oauth2(JsonField.of(oauth2)) + + /** + * Sets [Builder.oauth2] to an arbitrary JSON value. + * + * You should usually call [Builder.oauth2] with a well-typed [Oauth2] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun oauth2(oauth2: JsonField) = apply { this.oauth2 = oauth2 } + + fun providerId(providerId: String) = providerId(JsonField.of(providerId)) + + /** + * Sets [Builder.providerId] to an arbitrary JSON value. + * + * You should usually call [Builder.providerId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun providerId(providerId: JsonField) = apply { this.providerId = providerId } + + fun status(status: String) = status(JsonField.of(status)) + + /** + * Sets [Builder.status] to an arbitrary JSON value. + * + * You should usually call [Builder.status] with a well-typed [String] 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 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 [AuthProviderCreateRequest]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AuthProviderCreateRequest = + AuthProviderCreateRequest( + checkRequired("id", id), + description, + externalId, + oauth2, + providerId, + status, + type, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): AuthProviderCreateRequest = apply { + if (validated) { + return@apply + } + + id() + description() + externalId() + oauth2().ifPresent { it.validate() } + providerId() + status() + type() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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) + + (if (externalId.asKnown().isPresent) 1 else 0) + + (oauth2.asKnown().getOrNull()?.validity() ?: 0) + + (if (providerId.asKnown().isPresent) 1 else 0) + + (if (status.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) + + class Oauth2 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val clientId: JsonField, + private val authorizeRequest: JsonField, + private val clientSecret: JsonField, + private val pkce: JsonField, + private val refreshRequest: JsonField, + private val scopeDelimiter: JsonField, + private val tokenIntrospectionRequest: JsonField, + private val tokenRequest: JsonField, + private val userInfoRequest: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("client_id") + @ExcludeMissing + clientId: JsonField = JsonMissing.of(), + @JsonProperty("authorize_request") + @ExcludeMissing + authorizeRequest: JsonField = JsonMissing.of(), + @JsonProperty("client_secret") + @ExcludeMissing + clientSecret: JsonField = JsonMissing.of(), + @JsonProperty("pkce") @ExcludeMissing pkce: JsonField = JsonMissing.of(), + @JsonProperty("refresh_request") + @ExcludeMissing + refreshRequest: JsonField = JsonMissing.of(), + @JsonProperty("scope_delimiter") + @ExcludeMissing + scopeDelimiter: JsonField = JsonMissing.of(), + @JsonProperty("token_introspection_request") + @ExcludeMissing + tokenIntrospectionRequest: JsonField = JsonMissing.of(), + @JsonProperty("token_request") + @ExcludeMissing + tokenRequest: JsonField = JsonMissing.of(), + @JsonProperty("user_info_request") + @ExcludeMissing + userInfoRequest: JsonField = JsonMissing.of(), + ) : this( + clientId, + authorizeRequest, + clientSecret, + pkce, + refreshRequest, + scopeDelimiter, + tokenIntrospectionRequest, + tokenRequest, + userInfoRequest, + mutableMapOf(), + ) + + /** + * @throws ArcadeInvalidDataException 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("client_id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun authorizeRequest(): Optional = + authorizeRequest.getOptional("authorize_request") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun clientSecret(): Optional = clientSecret.getOptional("client_secret") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun pkce(): Optional = pkce.getOptional("pkce") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun refreshRequest(): Optional = + refreshRequest.getOptional("refresh_request") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun scopeDelimiter(): Optional = + scopeDelimiter.getOptional("scope_delimiter") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun tokenIntrospectionRequest(): Optional = + tokenIntrospectionRequest.getOptional("token_introspection_request") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun tokenRequest(): Optional = tokenRequest.getOptional("token_request") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun userInfoRequest(): Optional = + userInfoRequest.getOptional("user_info_request") + + /** + * Returns the raw JSON value of [clientId]. + * + * Unlike [clientId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("client_id") @ExcludeMissing fun _clientId(): JsonField = clientId + + /** + * Returns the raw JSON value of [authorizeRequest]. + * + * Unlike [authorizeRequest], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("authorize_request") + @ExcludeMissing + fun _authorizeRequest(): JsonField = authorizeRequest + + /** + * Returns the raw JSON value of [clientSecret]. + * + * Unlike [clientSecret], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("client_secret") + @ExcludeMissing + fun _clientSecret(): JsonField = clientSecret + + /** + * Returns the raw JSON value of [pkce]. + * + * Unlike [pkce], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("pkce") @ExcludeMissing fun _pkce(): JsonField = pkce + + /** + * Returns the raw JSON value of [refreshRequest]. + * + * Unlike [refreshRequest], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("refresh_request") + @ExcludeMissing + fun _refreshRequest(): JsonField = refreshRequest + + /** + * Returns the raw JSON value of [scopeDelimiter]. + * + * Unlike [scopeDelimiter], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("scope_delimiter") + @ExcludeMissing + fun _scopeDelimiter(): JsonField = scopeDelimiter + + /** + * Returns the raw JSON value of [tokenIntrospectionRequest]. + * + * Unlike [tokenIntrospectionRequest], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("token_introspection_request") + @ExcludeMissing + fun _tokenIntrospectionRequest(): JsonField = + tokenIntrospectionRequest + + /** + * Returns the raw JSON value of [tokenRequest]. + * + * Unlike [tokenRequest], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("token_request") + @ExcludeMissing + fun _tokenRequest(): JsonField = tokenRequest + + /** + * Returns the raw JSON value of [userInfoRequest]. + * + * Unlike [userInfoRequest], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("user_info_request") + @ExcludeMissing + fun _userInfoRequest(): JsonField = userInfoRequest + + @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 [Oauth2]. + * + * The following fields are required: + * ```java + * .clientId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Oauth2]. */ + class Builder internal constructor() { + + private var clientId: JsonField? = null + private var authorizeRequest: JsonField = JsonMissing.of() + private var clientSecret: JsonField = JsonMissing.of() + private var pkce: JsonField = JsonMissing.of() + private var refreshRequest: JsonField = JsonMissing.of() + private var scopeDelimiter: JsonField = JsonMissing.of() + private var tokenIntrospectionRequest: JsonField = + JsonMissing.of() + private var tokenRequest: JsonField = JsonMissing.of() + private var userInfoRequest: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(oauth2: Oauth2) = apply { + clientId = oauth2.clientId + authorizeRequest = oauth2.authorizeRequest + clientSecret = oauth2.clientSecret + pkce = oauth2.pkce + refreshRequest = oauth2.refreshRequest + scopeDelimiter = oauth2.scopeDelimiter + tokenIntrospectionRequest = oauth2.tokenIntrospectionRequest + tokenRequest = oauth2.tokenRequest + userInfoRequest = oauth2.userInfoRequest + additionalProperties = oauth2.additionalProperties.toMutableMap() + } + + 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 } + + fun authorizeRequest(authorizeRequest: AuthorizeRequest) = + authorizeRequest(JsonField.of(authorizeRequest)) + + /** + * Sets [Builder.authorizeRequest] to an arbitrary JSON value. + * + * You should usually call [Builder.authorizeRequest] with a well-typed + * [AuthorizeRequest] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun authorizeRequest(authorizeRequest: JsonField) = apply { + this.authorizeRequest = authorizeRequest + } + + 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 + } + + fun pkce(pkce: Pkce) = pkce(JsonField.of(pkce)) + + /** + * Sets [Builder.pkce] to an arbitrary JSON value. + * + * You should usually call [Builder.pkce] with a well-typed [Pkce] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun pkce(pkce: JsonField) = apply { this.pkce = pkce } + + fun refreshRequest(refreshRequest: RefreshRequest) = + refreshRequest(JsonField.of(refreshRequest)) + + /** + * Sets [Builder.refreshRequest] to an arbitrary JSON value. + * + * You should usually call [Builder.refreshRequest] with a well-typed [RefreshRequest] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun refreshRequest(refreshRequest: JsonField) = apply { + this.refreshRequest = refreshRequest + } + + fun scopeDelimiter(scopeDelimiter: ScopeDelimiter) = + scopeDelimiter(JsonField.of(scopeDelimiter)) + + /** + * Sets [Builder.scopeDelimiter] to an arbitrary JSON value. + * + * You should usually call [Builder.scopeDelimiter] with a well-typed [ScopeDelimiter] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun scopeDelimiter(scopeDelimiter: JsonField) = apply { + this.scopeDelimiter = scopeDelimiter + } + + fun tokenIntrospectionRequest(tokenIntrospectionRequest: TokenIntrospectionRequest) = + tokenIntrospectionRequest(JsonField.of(tokenIntrospectionRequest)) + + /** + * Sets [Builder.tokenIntrospectionRequest] to an arbitrary JSON value. + * + * You should usually call [Builder.tokenIntrospectionRequest] with a well-typed + * [TokenIntrospectionRequest] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun tokenIntrospectionRequest( + tokenIntrospectionRequest: JsonField + ) = apply { this.tokenIntrospectionRequest = tokenIntrospectionRequest } + + fun tokenRequest(tokenRequest: TokenRequest) = tokenRequest(JsonField.of(tokenRequest)) + + /** + * Sets [Builder.tokenRequest] to an arbitrary JSON value. + * + * You should usually call [Builder.tokenRequest] with a well-typed [TokenRequest] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun tokenRequest(tokenRequest: JsonField) = apply { + this.tokenRequest = tokenRequest + } + + fun userInfoRequest(userInfoRequest: UserInfoRequest) = + userInfoRequest(JsonField.of(userInfoRequest)) + + /** + * Sets [Builder.userInfoRequest] to an arbitrary JSON value. + * + * You should usually call [Builder.userInfoRequest] with a well-typed [UserInfoRequest] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun userInfoRequest(userInfoRequest: JsonField) = apply { + this.userInfoRequest = userInfoRequest + } + + 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 [Oauth2]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .clientId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Oauth2 = + Oauth2( + checkRequired("clientId", clientId), + authorizeRequest, + clientSecret, + pkce, + refreshRequest, + scopeDelimiter, + tokenIntrospectionRequest, + tokenRequest, + userInfoRequest, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Oauth2 = apply { + if (validated) { + return@apply + } + + clientId() + authorizeRequest().ifPresent { it.validate() } + clientSecret() + pkce().ifPresent { it.validate() } + refreshRequest().ifPresent { it.validate() } + scopeDelimiter().ifPresent { it.validate() } + tokenIntrospectionRequest().ifPresent { it.validate() } + tokenRequest().ifPresent { it.validate() } + userInfoRequest().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (clientId.asKnown().isPresent) 1 else 0) + + (authorizeRequest.asKnown().getOrNull()?.validity() ?: 0) + + (if (clientSecret.asKnown().isPresent) 1 else 0) + + (pkce.asKnown().getOrNull()?.validity() ?: 0) + + (refreshRequest.asKnown().getOrNull()?.validity() ?: 0) + + (scopeDelimiter.asKnown().getOrNull()?.validity() ?: 0) + + (tokenIntrospectionRequest.asKnown().getOrNull()?.validity() ?: 0) + + (tokenRequest.asKnown().getOrNull()?.validity() ?: 0) + + (userInfoRequest.asKnown().getOrNull()?.validity() ?: 0) + + class AuthorizeRequest + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val endpoint: JsonField, + private val authHeaderValueFormat: JsonField, + private val authMethod: JsonField, + private val method: JsonField, + private val params: JsonField, + private val requestContentType: JsonField, + private val responseContentType: JsonField, + private val responseMap: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("endpoint") + @ExcludeMissing + endpoint: JsonField = JsonMissing.of(), + @JsonProperty("auth_header_value_format") + @ExcludeMissing + authHeaderValueFormat: JsonField = JsonMissing.of(), + @JsonProperty("auth_method") + @ExcludeMissing + authMethod: JsonField = JsonMissing.of(), + @JsonProperty("method") + @ExcludeMissing + method: JsonField = JsonMissing.of(), + @JsonProperty("params") + @ExcludeMissing + params: JsonField = JsonMissing.of(), + @JsonProperty("request_content_type") + @ExcludeMissing + requestContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_content_type") + @ExcludeMissing + responseContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_map") + @ExcludeMissing + responseMap: JsonField = JsonMissing.of(), + ) : this( + endpoint, + authHeaderValueFormat, + authMethod, + method, + params, + requestContentType, + responseContentType, + responseMap, + mutableMapOf(), + ) + + /** + * @throws ArcadeInvalidDataException 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") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authHeaderValueFormat(): Optional = + authHeaderValueFormat.getOptional("auth_header_value_format") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authMethod(): Optional = authMethod.getOptional("auth_method") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun method(): Optional = method.getOptional("method") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun params(): Optional = params.getOptional("params") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun requestContentType(): Optional = + requestContentType.getOptional("request_content_type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun responseContentType(): Optional = + responseContentType.getOptional("response_content_type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun responseMap(): Optional = responseMap.getOptional("response_map") + + /** + * 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 [authHeaderValueFormat]. + * + * Unlike [authHeaderValueFormat], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("auth_header_value_format") + @ExcludeMissing + fun _authHeaderValueFormat(): JsonField = authHeaderValueFormat + + /** + * Returns the raw JSON value of [authMethod]. + * + * Unlike [authMethod], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("auth_method") + @ExcludeMissing + fun _authMethod(): JsonField = authMethod + + /** + * Returns the raw JSON value of [method]. + * + * Unlike [method], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("method") @ExcludeMissing fun _method(): JsonField = method + + /** + * Returns the raw JSON value of [params]. + * + * Unlike [params], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("params") @ExcludeMissing fun _params(): JsonField = params + + /** + * Returns the raw JSON value of [requestContentType]. + * + * Unlike [requestContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("request_content_type") + @ExcludeMissing + fun _requestContentType(): JsonField = requestContentType + + /** + * Returns the raw JSON value of [responseContentType]. + * + * Unlike [responseContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("response_content_type") + @ExcludeMissing + fun _responseContentType(): JsonField = responseContentType + + /** + * Returns the raw JSON value of [responseMap]. + * + * Unlike [responseMap], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("response_map") + @ExcludeMissing + fun _responseMap(): JsonField = responseMap + + @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 [AuthorizeRequest]. + * + * The following fields are required: + * ```java + * .endpoint() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AuthorizeRequest]. */ + class Builder internal constructor() { + + private var endpoint: JsonField? = null + private var authHeaderValueFormat: JsonField = JsonMissing.of() + private var authMethod: JsonField = JsonMissing.of() + private var method: JsonField = JsonMissing.of() + private var params: JsonField = JsonMissing.of() + private var requestContentType: JsonField = JsonMissing.of() + private var responseContentType: JsonField = JsonMissing.of() + private var responseMap: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(authorizeRequest: AuthorizeRequest) = apply { + endpoint = authorizeRequest.endpoint + authHeaderValueFormat = authorizeRequest.authHeaderValueFormat + authMethod = authorizeRequest.authMethod + method = authorizeRequest.method + params = authorizeRequest.params + requestContentType = authorizeRequest.requestContentType + responseContentType = authorizeRequest.responseContentType + responseMap = authorizeRequest.responseMap + additionalProperties = authorizeRequest.additionalProperties.toMutableMap() + } + + 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 } + + fun authHeaderValueFormat(authHeaderValueFormat: String) = + authHeaderValueFormat(JsonField.of(authHeaderValueFormat)) + + /** + * Sets [Builder.authHeaderValueFormat] to an arbitrary JSON value. + * + * You should usually call [Builder.authHeaderValueFormat] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun authHeaderValueFormat(authHeaderValueFormat: JsonField) = apply { + this.authHeaderValueFormat = authHeaderValueFormat + } + + fun authMethod(authMethod: String) = authMethod(JsonField.of(authMethod)) + + /** + * Sets [Builder.authMethod] to an arbitrary JSON value. + * + * You should usually call [Builder.authMethod] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun authMethod(authMethod: JsonField) = apply { + this.authMethod = authMethod + } + + fun method(method: String) = method(JsonField.of(method)) + + /** + * Sets [Builder.method] to an arbitrary JSON value. + * + * You should usually call [Builder.method] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun method(method: JsonField) = apply { this.method = method } + + fun params(params: Params) = params(JsonField.of(params)) + + /** + * Sets [Builder.params] to an arbitrary JSON value. + * + * You should usually call [Builder.params] with a well-typed [Params] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun params(params: JsonField) = apply { this.params = params } + + fun requestContentType(requestContentType: RequestContentType) = + requestContentType(JsonField.of(requestContentType)) + + /** + * Sets [Builder.requestContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.requestContentType] with a well-typed + * [RequestContentType] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun requestContentType(requestContentType: JsonField) = apply { + this.requestContentType = requestContentType + } + + fun responseContentType(responseContentType: ResponseContentType) = + responseContentType(JsonField.of(responseContentType)) + + /** + * Sets [Builder.responseContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.responseContentType] with a well-typed + * [ResponseContentType] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun responseContentType(responseContentType: JsonField) = + apply { + this.responseContentType = responseContentType + } + + fun responseMap(responseMap: ResponseMap) = responseMap(JsonField.of(responseMap)) + + /** + * Sets [Builder.responseMap] to an arbitrary JSON value. + * + * You should usually call [Builder.responseMap] with a well-typed [ResponseMap] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun responseMap(responseMap: JsonField) = apply { + this.responseMap = responseMap + } + + 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 [AuthorizeRequest]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .endpoint() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AuthorizeRequest = + AuthorizeRequest( + checkRequired("endpoint", endpoint), + authHeaderValueFormat, + authMethod, + method, + params, + requestContentType, + responseContentType, + responseMap, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): AuthorizeRequest = apply { + if (validated) { + return@apply + } + + endpoint() + authHeaderValueFormat() + authMethod() + method() + params().ifPresent { it.validate() } + requestContentType().ifPresent { it.validate() } + responseContentType().ifPresent { it.validate() } + responseMap().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (endpoint.asKnown().isPresent) 1 else 0) + + (if (authHeaderValueFormat.asKnown().isPresent) 1 else 0) + + (if (authMethod.asKnown().isPresent) 1 else 0) + + (if (method.asKnown().isPresent) 1 else 0) + + (params.asKnown().getOrNull()?.validity() ?: 0) + + (requestContentType.asKnown().getOrNull()?.validity() ?: 0) + + (responseContentType.asKnown().getOrNull()?.validity() ?: 0) + + (responseMap.asKnown().getOrNull()?.validity() ?: 0) + + class Params + @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 [Params]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Params]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(params: Params) = apply { + additionalProperties = params.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 [Params]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Params = Params(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Params = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 Params && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Params{additionalProperties=$additionalProperties}" + } + + class RequestContentType + @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 APPLICATION_X_WWW_FORM_URLENCODED = of("application/x-www-form-urlencoded") + + @JvmField val APPLICATION_JSON = of("application/json") + + @JvmStatic fun of(value: String) = RequestContentType(JsonField.of(value)) + } + + /** An enum containing [RequestContentType]'s known values. */ + enum class Known { + APPLICATION_X_WWW_FORM_URLENCODED, + APPLICATION_JSON, + } + + /** + * An enum containing [RequestContentType]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [RequestContentType] 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 { + APPLICATION_X_WWW_FORM_URLENCODED, + APPLICATION_JSON, + /** + * An enum member indicating that [RequestContentType] 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) { + APPLICATION_X_WWW_FORM_URLENCODED -> Value.APPLICATION_X_WWW_FORM_URLENCODED + APPLICATION_JSON -> Value.APPLICATION_JSON + 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 ArcadeInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + APPLICATION_X_WWW_FORM_URLENCODED -> Known.APPLICATION_X_WWW_FORM_URLENCODED + APPLICATION_JSON -> Known.APPLICATION_JSON + else -> + throw ArcadeInvalidDataException("Unknown RequestContentType: $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 ArcadeInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ArcadeInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): RequestContentType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 RequestContentType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class ResponseContentType + @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 APPLICATION_X_WWW_FORM_URLENCODED = of("application/x-www-form-urlencoded") + + @JvmField val APPLICATION_JSON = of("application/json") + + @JvmStatic fun of(value: String) = ResponseContentType(JsonField.of(value)) + } + + /** An enum containing [ResponseContentType]'s known values. */ + enum class Known { + APPLICATION_X_WWW_FORM_URLENCODED, + APPLICATION_JSON, + } + + /** + * An enum containing [ResponseContentType]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [ResponseContentType] 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 { + APPLICATION_X_WWW_FORM_URLENCODED, + APPLICATION_JSON, + /** + * An enum member indicating that [ResponseContentType] 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) { + APPLICATION_X_WWW_FORM_URLENCODED -> Value.APPLICATION_X_WWW_FORM_URLENCODED + APPLICATION_JSON -> Value.APPLICATION_JSON + 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 ArcadeInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + APPLICATION_X_WWW_FORM_URLENCODED -> Known.APPLICATION_X_WWW_FORM_URLENCODED + APPLICATION_JSON -> Known.APPLICATION_JSON + else -> + throw ArcadeInvalidDataException("Unknown ResponseContentType: $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 ArcadeInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ArcadeInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): ResponseContentType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 ResponseContentType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class ResponseMap + @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 [ResponseMap]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ResponseMap]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(responseMap: ResponseMap) = apply { + additionalProperties = responseMap.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 [ResponseMap]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ResponseMap = ResponseMap(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ResponseMap = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 ResponseMap && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ResponseMap{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AuthorizeRequest && + endpoint == other.endpoint && + authHeaderValueFormat == other.authHeaderValueFormat && + authMethod == other.authMethod && + method == other.method && + params == other.params && + requestContentType == other.requestContentType && + responseContentType == other.responseContentType && + responseMap == other.responseMap && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + endpoint, + authHeaderValueFormat, + authMethod, + method, + params, + requestContentType, + responseContentType, + responseMap, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AuthorizeRequest{endpoint=$endpoint, authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, additionalProperties=$additionalProperties}" + } + + class Pkce + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val codeChallengeMethod: JsonField, + private val enabled: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("code_challenge_method") + @ExcludeMissing + codeChallengeMethod: JsonField = JsonMissing.of(), + @JsonProperty("enabled") + @ExcludeMissing + enabled: JsonField = JsonMissing.of(), + ) : this(codeChallengeMethod, enabled, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun codeChallengeMethod(): Optional = + codeChallengeMethod.getOptional("code_challenge_method") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun enabled(): Optional = enabled.getOptional("enabled") + + /** + * Returns the raw JSON value of [codeChallengeMethod]. + * + * Unlike [codeChallengeMethod], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("code_challenge_method") + @ExcludeMissing + fun _codeChallengeMethod(): JsonField = codeChallengeMethod + + /** + * Returns the raw JSON value of [enabled]. + * + * Unlike [enabled], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("enabled") @ExcludeMissing fun _enabled(): JsonField = enabled + + @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 [Pkce]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Pkce]. */ + class Builder internal constructor() { + + private var codeChallengeMethod: JsonField = JsonMissing.of() + private var enabled: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(pkce: Pkce) = apply { + codeChallengeMethod = pkce.codeChallengeMethod + enabled = pkce.enabled + additionalProperties = pkce.additionalProperties.toMutableMap() + } + + fun codeChallengeMethod(codeChallengeMethod: String) = + codeChallengeMethod(JsonField.of(codeChallengeMethod)) + + /** + * Sets [Builder.codeChallengeMethod] to an arbitrary JSON value. + * + * You should usually call [Builder.codeChallengeMethod] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun codeChallengeMethod(codeChallengeMethod: JsonField) = apply { + this.codeChallengeMethod = codeChallengeMethod + } + + fun enabled(enabled: Boolean) = enabled(JsonField.of(enabled)) + + /** + * Sets [Builder.enabled] to an arbitrary JSON value. + * + * You should usually call [Builder.enabled] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun enabled(enabled: JsonField) = apply { this.enabled = enabled } + + 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 [Pkce]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Pkce = + Pkce(codeChallengeMethod, enabled, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Pkce = apply { + if (validated) { + return@apply + } + + codeChallengeMethod() + enabled() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (codeChallengeMethod.asKnown().isPresent) 1 else 0) + + (if (enabled.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Pkce && + codeChallengeMethod == other.codeChallengeMethod && + enabled == other.enabled && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(codeChallengeMethod, enabled, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Pkce{codeChallengeMethod=$codeChallengeMethod, enabled=$enabled, additionalProperties=$additionalProperties}" + } + + class RefreshRequest + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val endpoint: JsonField, + private val authHeaderValueFormat: JsonField, + private val authMethod: JsonField, + private val method: JsonField, + private val params: JsonField, + private val requestContentType: JsonField, + private val responseContentType: JsonField, + private val responseMap: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("endpoint") + @ExcludeMissing + endpoint: JsonField = JsonMissing.of(), + @JsonProperty("auth_header_value_format") + @ExcludeMissing + authHeaderValueFormat: JsonField = JsonMissing.of(), + @JsonProperty("auth_method") + @ExcludeMissing + authMethod: JsonField = JsonMissing.of(), + @JsonProperty("method") + @ExcludeMissing + method: JsonField = JsonMissing.of(), + @JsonProperty("params") + @ExcludeMissing + params: JsonField = JsonMissing.of(), + @JsonProperty("request_content_type") + @ExcludeMissing + requestContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_content_type") + @ExcludeMissing + responseContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_map") + @ExcludeMissing + responseMap: JsonField = JsonMissing.of(), + ) : this( + endpoint, + authHeaderValueFormat, + authMethod, + method, + params, + requestContentType, + responseContentType, + responseMap, + mutableMapOf(), + ) + + /** + * @throws ArcadeInvalidDataException 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") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authHeaderValueFormat(): Optional = + authHeaderValueFormat.getOptional("auth_header_value_format") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authMethod(): Optional = authMethod.getOptional("auth_method") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun method(): Optional = method.getOptional("method") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun params(): Optional = params.getOptional("params") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun requestContentType(): Optional = + requestContentType.getOptional("request_content_type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun responseContentType(): Optional = + responseContentType.getOptional("response_content_type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun responseMap(): Optional = responseMap.getOptional("response_map") + + /** + * 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 [authHeaderValueFormat]. + * + * Unlike [authHeaderValueFormat], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("auth_header_value_format") + @ExcludeMissing + fun _authHeaderValueFormat(): JsonField = authHeaderValueFormat + + /** + * Returns the raw JSON value of [authMethod]. + * + * Unlike [authMethod], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("auth_method") + @ExcludeMissing + fun _authMethod(): JsonField = authMethod + + /** + * Returns the raw JSON value of [method]. + * + * Unlike [method], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("method") @ExcludeMissing fun _method(): JsonField = method + + /** + * Returns the raw JSON value of [params]. + * + * Unlike [params], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("params") @ExcludeMissing fun _params(): JsonField = params + + /** + * Returns the raw JSON value of [requestContentType]. + * + * Unlike [requestContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("request_content_type") + @ExcludeMissing + fun _requestContentType(): JsonField = requestContentType + + /** + * Returns the raw JSON value of [responseContentType]. + * + * Unlike [responseContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("response_content_type") + @ExcludeMissing + fun _responseContentType(): JsonField = responseContentType + + /** + * Returns the raw JSON value of [responseMap]. + * + * Unlike [responseMap], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("response_map") + @ExcludeMissing + fun _responseMap(): JsonField = responseMap + + @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 [RefreshRequest]. + * + * The following fields are required: + * ```java + * .endpoint() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RefreshRequest]. */ + class Builder internal constructor() { + + private var endpoint: JsonField? = null + private var authHeaderValueFormat: JsonField = JsonMissing.of() + private var authMethod: JsonField = JsonMissing.of() + private var method: JsonField = JsonMissing.of() + private var params: JsonField = JsonMissing.of() + private var requestContentType: JsonField = JsonMissing.of() + private var responseContentType: JsonField = JsonMissing.of() + private var responseMap: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(refreshRequest: RefreshRequest) = apply { + endpoint = refreshRequest.endpoint + authHeaderValueFormat = refreshRequest.authHeaderValueFormat + authMethod = refreshRequest.authMethod + method = refreshRequest.method + params = refreshRequest.params + requestContentType = refreshRequest.requestContentType + responseContentType = refreshRequest.responseContentType + responseMap = refreshRequest.responseMap + additionalProperties = refreshRequest.additionalProperties.toMutableMap() + } + + 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 } + + fun authHeaderValueFormat(authHeaderValueFormat: String) = + authHeaderValueFormat(JsonField.of(authHeaderValueFormat)) + + /** + * Sets [Builder.authHeaderValueFormat] to an arbitrary JSON value. + * + * You should usually call [Builder.authHeaderValueFormat] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun authHeaderValueFormat(authHeaderValueFormat: JsonField) = apply { + this.authHeaderValueFormat = authHeaderValueFormat + } + + fun authMethod(authMethod: String) = authMethod(JsonField.of(authMethod)) + + /** + * Sets [Builder.authMethod] to an arbitrary JSON value. + * + * You should usually call [Builder.authMethod] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun authMethod(authMethod: JsonField) = apply { + this.authMethod = authMethod + } + + fun method(method: String) = method(JsonField.of(method)) + + /** + * Sets [Builder.method] to an arbitrary JSON value. + * + * You should usually call [Builder.method] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun method(method: JsonField) = apply { this.method = method } + + fun params(params: Params) = params(JsonField.of(params)) + + /** + * Sets [Builder.params] to an arbitrary JSON value. + * + * You should usually call [Builder.params] with a well-typed [Params] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun params(params: JsonField) = apply { this.params = params } + + fun requestContentType(requestContentType: RequestContentType) = + requestContentType(JsonField.of(requestContentType)) + + /** + * Sets [Builder.requestContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.requestContentType] with a well-typed + * [RequestContentType] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun requestContentType(requestContentType: JsonField) = apply { + this.requestContentType = requestContentType + } + + fun responseContentType(responseContentType: ResponseContentType) = + responseContentType(JsonField.of(responseContentType)) + + /** + * Sets [Builder.responseContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.responseContentType] with a well-typed + * [ResponseContentType] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun responseContentType(responseContentType: JsonField) = + apply { + this.responseContentType = responseContentType + } + + fun responseMap(responseMap: ResponseMap) = responseMap(JsonField.of(responseMap)) + + /** + * Sets [Builder.responseMap] to an arbitrary JSON value. + * + * You should usually call [Builder.responseMap] with a well-typed [ResponseMap] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun responseMap(responseMap: JsonField) = apply { + this.responseMap = responseMap + } + + 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 [RefreshRequest]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .endpoint() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): RefreshRequest = + RefreshRequest( + checkRequired("endpoint", endpoint), + authHeaderValueFormat, + authMethod, + method, + params, + requestContentType, + responseContentType, + responseMap, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): RefreshRequest = apply { + if (validated) { + return@apply + } + + endpoint() + authHeaderValueFormat() + authMethod() + method() + params().ifPresent { it.validate() } + requestContentType().ifPresent { it.validate() } + responseContentType().ifPresent { it.validate() } + responseMap().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (endpoint.asKnown().isPresent) 1 else 0) + + (if (authHeaderValueFormat.asKnown().isPresent) 1 else 0) + + (if (authMethod.asKnown().isPresent) 1 else 0) + + (if (method.asKnown().isPresent) 1 else 0) + + (params.asKnown().getOrNull()?.validity() ?: 0) + + (requestContentType.asKnown().getOrNull()?.validity() ?: 0) + + (responseContentType.asKnown().getOrNull()?.validity() ?: 0) + + (responseMap.asKnown().getOrNull()?.validity() ?: 0) + + class Params + @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 [Params]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Params]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(params: Params) = apply { + additionalProperties = params.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 [Params]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Params = Params(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Params = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 Params && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Params{additionalProperties=$additionalProperties}" + } + + class RequestContentType + @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 APPLICATION_X_WWW_FORM_URLENCODED = of("application/x-www-form-urlencoded") + + @JvmField val APPLICATION_JSON = of("application/json") + + @JvmStatic fun of(value: String) = RequestContentType(JsonField.of(value)) + } + + /** An enum containing [RequestContentType]'s known values. */ + enum class Known { + APPLICATION_X_WWW_FORM_URLENCODED, + APPLICATION_JSON, + } + + /** + * An enum containing [RequestContentType]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [RequestContentType] 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 { + APPLICATION_X_WWW_FORM_URLENCODED, + APPLICATION_JSON, + /** + * An enum member indicating that [RequestContentType] 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) { + APPLICATION_X_WWW_FORM_URLENCODED -> Value.APPLICATION_X_WWW_FORM_URLENCODED + APPLICATION_JSON -> Value.APPLICATION_JSON + 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 ArcadeInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + APPLICATION_X_WWW_FORM_URLENCODED -> Known.APPLICATION_X_WWW_FORM_URLENCODED + APPLICATION_JSON -> Known.APPLICATION_JSON + else -> + throw ArcadeInvalidDataException("Unknown RequestContentType: $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 ArcadeInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ArcadeInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): RequestContentType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 RequestContentType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class ResponseContentType + @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 APPLICATION_X_WWW_FORM_URLENCODED = of("application/x-www-form-urlencoded") + + @JvmField val APPLICATION_JSON = of("application/json") + + @JvmStatic fun of(value: String) = ResponseContentType(JsonField.of(value)) + } + + /** An enum containing [ResponseContentType]'s known values. */ + enum class Known { + APPLICATION_X_WWW_FORM_URLENCODED, + APPLICATION_JSON, + } + + /** + * An enum containing [ResponseContentType]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [ResponseContentType] 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 { + APPLICATION_X_WWW_FORM_URLENCODED, + APPLICATION_JSON, + /** + * An enum member indicating that [ResponseContentType] 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) { + APPLICATION_X_WWW_FORM_URLENCODED -> Value.APPLICATION_X_WWW_FORM_URLENCODED + APPLICATION_JSON -> Value.APPLICATION_JSON + 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 ArcadeInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + APPLICATION_X_WWW_FORM_URLENCODED -> Known.APPLICATION_X_WWW_FORM_URLENCODED + APPLICATION_JSON -> Known.APPLICATION_JSON + else -> + throw ArcadeInvalidDataException("Unknown ResponseContentType: $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 ArcadeInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ArcadeInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): ResponseContentType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 ResponseContentType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class ResponseMap + @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 [ResponseMap]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ResponseMap]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(responseMap: ResponseMap) = apply { + additionalProperties = responseMap.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 [ResponseMap]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ResponseMap = ResponseMap(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ResponseMap = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 ResponseMap && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ResponseMap{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RefreshRequest && + endpoint == other.endpoint && + authHeaderValueFormat == other.authHeaderValueFormat && + authMethod == other.authMethod && + method == other.method && + params == other.params && + requestContentType == other.requestContentType && + responseContentType == other.responseContentType && + responseMap == other.responseMap && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + endpoint, + authHeaderValueFormat, + authMethod, + method, + params, + requestContentType, + responseContentType, + responseMap, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RefreshRequest{endpoint=$endpoint, authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, additionalProperties=$additionalProperties}" + } + + class ScopeDelimiter + @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 Unknown0 = of(",") + + @JvmField val Unknown1 = of(" ") + + @JvmStatic fun of(value: String) = ScopeDelimiter(JsonField.of(value)) + } + + /** An enum containing [ScopeDelimiter]'s known values. */ + enum class Known { + Unknown0, + Unknown1, + } + + /** + * An enum containing [ScopeDelimiter]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [ScopeDelimiter] 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 { + Unknown0, + Unknown1, + /** + * An enum member indicating that [ScopeDelimiter] 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) { + Unknown0 -> Value.Unknown0 + Unknown1 -> Value.Unknown1 + 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 ArcadeInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + Unknown0 -> Known.Unknown0 + Unknown1 -> Known.Unknown1 + else -> throw ArcadeInvalidDataException("Unknown ScopeDelimiter: $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 ArcadeInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ArcadeInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): ScopeDelimiter = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 ScopeDelimiter && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class TokenIntrospectionRequest + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val endpoint: JsonField, + private val triggers: JsonField, + private val authHeaderValueFormat: JsonField, + private val authMethod: JsonField, + private val method: JsonField, + private val params: JsonField, + private val requestContentType: JsonField, + private val responseContentType: JsonField, + private val responseMap: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("endpoint") + @ExcludeMissing + endpoint: JsonField = JsonMissing.of(), + @JsonProperty("triggers") + @ExcludeMissing + triggers: JsonField = JsonMissing.of(), + @JsonProperty("auth_header_value_format") + @ExcludeMissing + authHeaderValueFormat: JsonField = JsonMissing.of(), + @JsonProperty("auth_method") + @ExcludeMissing + authMethod: JsonField = JsonMissing.of(), + @JsonProperty("method") + @ExcludeMissing + method: JsonField = JsonMissing.of(), + @JsonProperty("params") + @ExcludeMissing + params: JsonField = JsonMissing.of(), + @JsonProperty("request_content_type") + @ExcludeMissing + requestContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_content_type") + @ExcludeMissing + responseContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_map") + @ExcludeMissing + responseMap: JsonField = JsonMissing.of(), + ) : this( + endpoint, + triggers, + authHeaderValueFormat, + authMethod, + method, + params, + requestContentType, + responseContentType, + responseMap, + mutableMapOf(), + ) + + /** + * @throws ArcadeInvalidDataException 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") + + /** + * @throws ArcadeInvalidDataException 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 triggers(): Triggers = triggers.getRequired("triggers") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authHeaderValueFormat(): Optional = + authHeaderValueFormat.getOptional("auth_header_value_format") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authMethod(): Optional = authMethod.getOptional("auth_method") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun method(): Optional = method.getOptional("method") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun params(): Optional = params.getOptional("params") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun requestContentType(): Optional = + requestContentType.getOptional("request_content_type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun responseContentType(): Optional = + responseContentType.getOptional("response_content_type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun responseMap(): Optional = responseMap.getOptional("response_map") + + /** + * 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 [triggers]. + * + * Unlike [triggers], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("triggers") + @ExcludeMissing + fun _triggers(): JsonField = triggers + + /** + * Returns the raw JSON value of [authHeaderValueFormat]. + * + * Unlike [authHeaderValueFormat], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("auth_header_value_format") + @ExcludeMissing + fun _authHeaderValueFormat(): JsonField = authHeaderValueFormat + + /** + * Returns the raw JSON value of [authMethod]. + * + * Unlike [authMethod], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("auth_method") + @ExcludeMissing + fun _authMethod(): JsonField = authMethod + + /** + * Returns the raw JSON value of [method]. + * + * Unlike [method], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("method") @ExcludeMissing fun _method(): JsonField = method + + /** + * Returns the raw JSON value of [params]. + * + * Unlike [params], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("params") @ExcludeMissing fun _params(): JsonField = params + + /** + * Returns the raw JSON value of [requestContentType]. + * + * Unlike [requestContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("request_content_type") + @ExcludeMissing + fun _requestContentType(): JsonField = requestContentType + + /** + * Returns the raw JSON value of [responseContentType]. + * + * Unlike [responseContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("response_content_type") + @ExcludeMissing + fun _responseContentType(): JsonField = responseContentType + + /** + * Returns the raw JSON value of [responseMap]. + * + * Unlike [responseMap], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("response_map") + @ExcludeMissing + fun _responseMap(): JsonField = responseMap + + @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 + * [TokenIntrospectionRequest]. + * + * The following fields are required: + * ```java + * .endpoint() + * .triggers() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [TokenIntrospectionRequest]. */ + class Builder internal constructor() { + + private var endpoint: JsonField? = null + private var triggers: JsonField? = null + private var authHeaderValueFormat: JsonField = JsonMissing.of() + private var authMethod: JsonField = JsonMissing.of() + private var method: JsonField = JsonMissing.of() + private var params: JsonField = JsonMissing.of() + private var requestContentType: JsonField = JsonMissing.of() + private var responseContentType: JsonField = JsonMissing.of() + private var responseMap: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(tokenIntrospectionRequest: TokenIntrospectionRequest) = apply { + endpoint = tokenIntrospectionRequest.endpoint + triggers = tokenIntrospectionRequest.triggers + authHeaderValueFormat = tokenIntrospectionRequest.authHeaderValueFormat + authMethod = tokenIntrospectionRequest.authMethod + method = tokenIntrospectionRequest.method + params = tokenIntrospectionRequest.params + requestContentType = tokenIntrospectionRequest.requestContentType + responseContentType = tokenIntrospectionRequest.responseContentType + responseMap = tokenIntrospectionRequest.responseMap + additionalProperties = + tokenIntrospectionRequest.additionalProperties.toMutableMap() + } + + 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 } + + fun triggers(triggers: Triggers) = triggers(JsonField.of(triggers)) + + /** + * Sets [Builder.triggers] to an arbitrary JSON value. + * + * You should usually call [Builder.triggers] with a well-typed [Triggers] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun triggers(triggers: JsonField) = apply { this.triggers = triggers } + + fun authHeaderValueFormat(authHeaderValueFormat: String) = + authHeaderValueFormat(JsonField.of(authHeaderValueFormat)) + + /** + * Sets [Builder.authHeaderValueFormat] to an arbitrary JSON value. + * + * You should usually call [Builder.authHeaderValueFormat] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun authHeaderValueFormat(authHeaderValueFormat: JsonField) = apply { + this.authHeaderValueFormat = authHeaderValueFormat + } + + fun authMethod(authMethod: String) = authMethod(JsonField.of(authMethod)) + + /** + * Sets [Builder.authMethod] to an arbitrary JSON value. + * + * You should usually call [Builder.authMethod] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun authMethod(authMethod: JsonField) = apply { + this.authMethod = authMethod + } + + fun method(method: String) = method(JsonField.of(method)) + + /** + * Sets [Builder.method] to an arbitrary JSON value. + * + * You should usually call [Builder.method] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun method(method: JsonField) = apply { this.method = method } + + fun params(params: Params) = params(JsonField.of(params)) + + /** + * Sets [Builder.params] to an arbitrary JSON value. + * + * You should usually call [Builder.params] with a well-typed [Params] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun params(params: JsonField) = apply { this.params = params } + + fun requestContentType(requestContentType: RequestContentType) = + requestContentType(JsonField.of(requestContentType)) + + /** + * Sets [Builder.requestContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.requestContentType] with a well-typed + * [RequestContentType] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun requestContentType(requestContentType: JsonField) = apply { + this.requestContentType = requestContentType + } + + fun responseContentType(responseContentType: ResponseContentType) = + responseContentType(JsonField.of(responseContentType)) + + /** + * Sets [Builder.responseContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.responseContentType] with a well-typed + * [ResponseContentType] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun responseContentType(responseContentType: JsonField) = + apply { + this.responseContentType = responseContentType + } + + fun responseMap(responseMap: ResponseMap) = responseMap(JsonField.of(responseMap)) + + /** + * Sets [Builder.responseMap] to an arbitrary JSON value. + * + * You should usually call [Builder.responseMap] with a well-typed [ResponseMap] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun responseMap(responseMap: JsonField) = apply { + this.responseMap = responseMap + } + + 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 [TokenIntrospectionRequest]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .endpoint() + * .triggers() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): TokenIntrospectionRequest = + TokenIntrospectionRequest( + checkRequired("endpoint", endpoint), + checkRequired("triggers", triggers), + authHeaderValueFormat, + authMethod, + method, + params, + requestContentType, + responseContentType, + responseMap, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): TokenIntrospectionRequest = apply { + if (validated) { + return@apply + } + + endpoint() + triggers().validate() + authHeaderValueFormat() + authMethod() + method() + params().ifPresent { it.validate() } + requestContentType().ifPresent { it.validate() } + responseContentType().ifPresent { it.validate() } + responseMap().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (endpoint.asKnown().isPresent) 1 else 0) + + (triggers.asKnown().getOrNull()?.validity() ?: 0) + + (if (authHeaderValueFormat.asKnown().isPresent) 1 else 0) + + (if (authMethod.asKnown().isPresent) 1 else 0) + + (if (method.asKnown().isPresent) 1 else 0) + + (params.asKnown().getOrNull()?.validity() ?: 0) + + (requestContentType.asKnown().getOrNull()?.validity() ?: 0) + + (responseContentType.asKnown().getOrNull()?.validity() ?: 0) + + (responseMap.asKnown().getOrNull()?.validity() ?: 0) + + class Triggers + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val onTokenGrant: JsonField, + private val onTokenRefresh: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("on_token_grant") + @ExcludeMissing + onTokenGrant: JsonField = JsonMissing.of(), + @JsonProperty("on_token_refresh") + @ExcludeMissing + onTokenRefresh: JsonField = JsonMissing.of(), + ) : this(onTokenGrant, onTokenRefresh, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun onTokenGrant(): Optional = onTokenGrant.getOptional("on_token_grant") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun onTokenRefresh(): Optional = + onTokenRefresh.getOptional("on_token_refresh") + + /** + * Returns the raw JSON value of [onTokenGrant]. + * + * Unlike [onTokenGrant], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("on_token_grant") + @ExcludeMissing + fun _onTokenGrant(): JsonField = onTokenGrant + + /** + * Returns the raw JSON value of [onTokenRefresh]. + * + * Unlike [onTokenRefresh], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("on_token_refresh") + @ExcludeMissing + fun _onTokenRefresh(): JsonField = onTokenRefresh + + @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 [Triggers]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Triggers]. */ + class Builder internal constructor() { + + private var onTokenGrant: JsonField = JsonMissing.of() + private var onTokenRefresh: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(triggers: Triggers) = apply { + onTokenGrant = triggers.onTokenGrant + onTokenRefresh = triggers.onTokenRefresh + additionalProperties = triggers.additionalProperties.toMutableMap() + } + + fun onTokenGrant(onTokenGrant: Boolean) = + onTokenGrant(JsonField.of(onTokenGrant)) + + /** + * Sets [Builder.onTokenGrant] to an arbitrary JSON value. + * + * You should usually call [Builder.onTokenGrant] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun onTokenGrant(onTokenGrant: JsonField) = apply { + this.onTokenGrant = onTokenGrant + } + + fun onTokenRefresh(onTokenRefresh: Boolean) = + onTokenRefresh(JsonField.of(onTokenRefresh)) + + /** + * Sets [Builder.onTokenRefresh] to an arbitrary JSON value. + * + * You should usually call [Builder.onTokenRefresh] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun onTokenRefresh(onTokenRefresh: JsonField) = apply { + this.onTokenRefresh = onTokenRefresh + } + + 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 [Triggers]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Triggers = + Triggers(onTokenGrant, onTokenRefresh, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Triggers = apply { + if (validated) { + return@apply + } + + onTokenGrant() + onTokenRefresh() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (onTokenGrant.asKnown().isPresent) 1 else 0) + + (if (onTokenRefresh.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Triggers && + onTokenGrant == other.onTokenGrant && + onTokenRefresh == other.onTokenRefresh && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(onTokenGrant, onTokenRefresh, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Triggers{onTokenGrant=$onTokenGrant, onTokenRefresh=$onTokenRefresh, additionalProperties=$additionalProperties}" + } + + class Params + @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 [Params]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Params]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(params: Params) = apply { + additionalProperties = params.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 [Params]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Params = Params(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Params = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 Params && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Params{additionalProperties=$additionalProperties}" + } + + class RequestContentType + @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 APPLICATION_X_WWW_FORM_URLENCODED = of("application/x-www-form-urlencoded") + + @JvmField val APPLICATION_JSON = of("application/json") + + @JvmStatic fun of(value: String) = RequestContentType(JsonField.of(value)) + } + + /** An enum containing [RequestContentType]'s known values. */ + enum class Known { + APPLICATION_X_WWW_FORM_URLENCODED, + APPLICATION_JSON, + } + + /** + * An enum containing [RequestContentType]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [RequestContentType] 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 { + APPLICATION_X_WWW_FORM_URLENCODED, + APPLICATION_JSON, + /** + * An enum member indicating that [RequestContentType] 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) { + APPLICATION_X_WWW_FORM_URLENCODED -> Value.APPLICATION_X_WWW_FORM_URLENCODED + APPLICATION_JSON -> Value.APPLICATION_JSON + 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 ArcadeInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + APPLICATION_X_WWW_FORM_URLENCODED -> Known.APPLICATION_X_WWW_FORM_URLENCODED + APPLICATION_JSON -> Known.APPLICATION_JSON + else -> + throw ArcadeInvalidDataException("Unknown RequestContentType: $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 ArcadeInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ArcadeInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): RequestContentType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 RequestContentType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class ResponseContentType + @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 APPLICATION_X_WWW_FORM_URLENCODED = of("application/x-www-form-urlencoded") + + @JvmField val APPLICATION_JSON = of("application/json") + + @JvmStatic fun of(value: String) = ResponseContentType(JsonField.of(value)) + } + + /** An enum containing [ResponseContentType]'s known values. */ + enum class Known { + APPLICATION_X_WWW_FORM_URLENCODED, + APPLICATION_JSON, + } + + /** + * An enum containing [ResponseContentType]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [ResponseContentType] 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 { + APPLICATION_X_WWW_FORM_URLENCODED, + APPLICATION_JSON, + /** + * An enum member indicating that [ResponseContentType] 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) { + APPLICATION_X_WWW_FORM_URLENCODED -> Value.APPLICATION_X_WWW_FORM_URLENCODED + APPLICATION_JSON -> Value.APPLICATION_JSON + 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 ArcadeInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + APPLICATION_X_WWW_FORM_URLENCODED -> Known.APPLICATION_X_WWW_FORM_URLENCODED + APPLICATION_JSON -> Known.APPLICATION_JSON + else -> + throw ArcadeInvalidDataException("Unknown ResponseContentType: $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 ArcadeInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ArcadeInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): ResponseContentType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 ResponseContentType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class ResponseMap + @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 [ResponseMap]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ResponseMap]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(responseMap: ResponseMap) = apply { + additionalProperties = responseMap.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 [ResponseMap]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ResponseMap = ResponseMap(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ResponseMap = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 ResponseMap && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ResponseMap{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is TokenIntrospectionRequest && + endpoint == other.endpoint && + triggers == other.triggers && + authHeaderValueFormat == other.authHeaderValueFormat && + authMethod == other.authMethod && + method == other.method && + params == other.params && + requestContentType == other.requestContentType && + responseContentType == other.responseContentType && + responseMap == other.responseMap && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + endpoint, + triggers, + authHeaderValueFormat, + authMethod, + method, + params, + requestContentType, + responseContentType, + responseMap, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "TokenIntrospectionRequest{endpoint=$endpoint, triggers=$triggers, authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, additionalProperties=$additionalProperties}" + } + + class TokenRequest + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val endpoint: JsonField, + private val authHeaderValueFormat: JsonField, + private val authMethod: JsonField, + private val method: JsonField, + private val params: JsonField, + private val requestContentType: JsonField, + private val responseContentType: JsonField, + private val responseMap: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("endpoint") + @ExcludeMissing + endpoint: JsonField = JsonMissing.of(), + @JsonProperty("auth_header_value_format") + @ExcludeMissing + authHeaderValueFormat: JsonField = JsonMissing.of(), + @JsonProperty("auth_method") + @ExcludeMissing + authMethod: JsonField = JsonMissing.of(), + @JsonProperty("method") + @ExcludeMissing + method: JsonField = JsonMissing.of(), + @JsonProperty("params") + @ExcludeMissing + params: JsonField = JsonMissing.of(), + @JsonProperty("request_content_type") + @ExcludeMissing + requestContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_content_type") + @ExcludeMissing + responseContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_map") + @ExcludeMissing + responseMap: JsonField = JsonMissing.of(), + ) : this( + endpoint, + authHeaderValueFormat, + authMethod, + method, + params, + requestContentType, + responseContentType, + responseMap, + mutableMapOf(), + ) + + /** + * @throws ArcadeInvalidDataException 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") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authHeaderValueFormat(): Optional = + authHeaderValueFormat.getOptional("auth_header_value_format") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authMethod(): Optional = authMethod.getOptional("auth_method") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun method(): Optional = method.getOptional("method") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun params(): Optional = params.getOptional("params") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun requestContentType(): Optional = + requestContentType.getOptional("request_content_type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun responseContentType(): Optional = + responseContentType.getOptional("response_content_type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun responseMap(): Optional = responseMap.getOptional("response_map") + + /** + * 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 [authHeaderValueFormat]. + * + * Unlike [authHeaderValueFormat], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("auth_header_value_format") + @ExcludeMissing + fun _authHeaderValueFormat(): JsonField = authHeaderValueFormat + + /** + * Returns the raw JSON value of [authMethod]. + * + * Unlike [authMethod], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("auth_method") + @ExcludeMissing + fun _authMethod(): JsonField = authMethod + + /** + * Returns the raw JSON value of [method]. + * + * Unlike [method], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("method") @ExcludeMissing fun _method(): JsonField = method + + /** + * Returns the raw JSON value of [params]. + * + * Unlike [params], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("params") @ExcludeMissing fun _params(): JsonField = params + + /** + * Returns the raw JSON value of [requestContentType]. + * + * Unlike [requestContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("request_content_type") + @ExcludeMissing + fun _requestContentType(): JsonField = requestContentType + + /** + * Returns the raw JSON value of [responseContentType]. + * + * Unlike [responseContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("response_content_type") + @ExcludeMissing + fun _responseContentType(): JsonField = responseContentType + + /** + * Returns the raw JSON value of [responseMap]. + * + * Unlike [responseMap], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("response_map") + @ExcludeMissing + fun _responseMap(): JsonField = responseMap + + @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 [TokenRequest]. + * + * The following fields are required: + * ```java + * .endpoint() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [TokenRequest]. */ + class Builder internal constructor() { + + private var endpoint: JsonField? = null + private var authHeaderValueFormat: JsonField = JsonMissing.of() + private var authMethod: JsonField = JsonMissing.of() + private var method: JsonField = JsonMissing.of() + private var params: JsonField = JsonMissing.of() + private var requestContentType: JsonField = JsonMissing.of() + private var responseContentType: JsonField = JsonMissing.of() + private var responseMap: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(tokenRequest: TokenRequest) = apply { + endpoint = tokenRequest.endpoint + authHeaderValueFormat = tokenRequest.authHeaderValueFormat + authMethod = tokenRequest.authMethod + method = tokenRequest.method + params = tokenRequest.params + requestContentType = tokenRequest.requestContentType + responseContentType = tokenRequest.responseContentType + responseMap = tokenRequest.responseMap + additionalProperties = tokenRequest.additionalProperties.toMutableMap() + } + + 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 } + + fun authHeaderValueFormat(authHeaderValueFormat: String) = + authHeaderValueFormat(JsonField.of(authHeaderValueFormat)) + + /** + * Sets [Builder.authHeaderValueFormat] to an arbitrary JSON value. + * + * You should usually call [Builder.authHeaderValueFormat] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun authHeaderValueFormat(authHeaderValueFormat: JsonField) = apply { + this.authHeaderValueFormat = authHeaderValueFormat + } + + fun authMethod(authMethod: String) = authMethod(JsonField.of(authMethod)) + + /** + * Sets [Builder.authMethod] to an arbitrary JSON value. + * + * You should usually call [Builder.authMethod] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun authMethod(authMethod: JsonField) = apply { + this.authMethod = authMethod + } + + fun method(method: String) = method(JsonField.of(method)) + + /** + * Sets [Builder.method] to an arbitrary JSON value. + * + * You should usually call [Builder.method] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun method(method: JsonField) = apply { this.method = method } + + fun params(params: Params) = params(JsonField.of(params)) + + /** + * Sets [Builder.params] to an arbitrary JSON value. + * + * You should usually call [Builder.params] with a well-typed [Params] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun params(params: JsonField) = apply { this.params = params } + + fun requestContentType(requestContentType: RequestContentType) = + requestContentType(JsonField.of(requestContentType)) + + /** + * Sets [Builder.requestContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.requestContentType] with a well-typed + * [RequestContentType] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun requestContentType(requestContentType: JsonField) = apply { + this.requestContentType = requestContentType + } + + fun responseContentType(responseContentType: ResponseContentType) = + responseContentType(JsonField.of(responseContentType)) + + /** + * Sets [Builder.responseContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.responseContentType] with a well-typed + * [ResponseContentType] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun responseContentType(responseContentType: JsonField) = + apply { + this.responseContentType = responseContentType + } + + fun responseMap(responseMap: ResponseMap) = responseMap(JsonField.of(responseMap)) + + /** + * Sets [Builder.responseMap] to an arbitrary JSON value. + * + * You should usually call [Builder.responseMap] with a well-typed [ResponseMap] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun responseMap(responseMap: JsonField) = apply { + this.responseMap = responseMap + } + + 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 [TokenRequest]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .endpoint() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): TokenRequest = + TokenRequest( + checkRequired("endpoint", endpoint), + authHeaderValueFormat, + authMethod, + method, + params, + requestContentType, + responseContentType, + responseMap, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): TokenRequest = apply { + if (validated) { + return@apply + } + + endpoint() + authHeaderValueFormat() + authMethod() + method() + params().ifPresent { it.validate() } + requestContentType().ifPresent { it.validate() } + responseContentType().ifPresent { it.validate() } + responseMap().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (endpoint.asKnown().isPresent) 1 else 0) + + (if (authHeaderValueFormat.asKnown().isPresent) 1 else 0) + + (if (authMethod.asKnown().isPresent) 1 else 0) + + (if (method.asKnown().isPresent) 1 else 0) + + (params.asKnown().getOrNull()?.validity() ?: 0) + + (requestContentType.asKnown().getOrNull()?.validity() ?: 0) + + (responseContentType.asKnown().getOrNull()?.validity() ?: 0) + + (responseMap.asKnown().getOrNull()?.validity() ?: 0) + + class Params + @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 [Params]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Params]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(params: Params) = apply { + additionalProperties = params.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 [Params]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Params = Params(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Params = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 Params && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Params{additionalProperties=$additionalProperties}" + } + + class RequestContentType + @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 APPLICATION_X_WWW_FORM_URLENCODED = of("application/x-www-form-urlencoded") + + @JvmField val APPLICATION_JSON = of("application/json") + + @JvmStatic fun of(value: String) = RequestContentType(JsonField.of(value)) + } + + /** An enum containing [RequestContentType]'s known values. */ + enum class Known { + APPLICATION_X_WWW_FORM_URLENCODED, + APPLICATION_JSON, + } + + /** + * An enum containing [RequestContentType]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [RequestContentType] 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 { + APPLICATION_X_WWW_FORM_URLENCODED, + APPLICATION_JSON, + /** + * An enum member indicating that [RequestContentType] 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) { + APPLICATION_X_WWW_FORM_URLENCODED -> Value.APPLICATION_X_WWW_FORM_URLENCODED + APPLICATION_JSON -> Value.APPLICATION_JSON + 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 ArcadeInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + APPLICATION_X_WWW_FORM_URLENCODED -> Known.APPLICATION_X_WWW_FORM_URLENCODED + APPLICATION_JSON -> Known.APPLICATION_JSON + else -> + throw ArcadeInvalidDataException("Unknown RequestContentType: $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 ArcadeInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ArcadeInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): RequestContentType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 RequestContentType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class ResponseContentType + @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 APPLICATION_X_WWW_FORM_URLENCODED = of("application/x-www-form-urlencoded") + + @JvmField val APPLICATION_JSON = of("application/json") + + @JvmStatic fun of(value: String) = ResponseContentType(JsonField.of(value)) + } + + /** An enum containing [ResponseContentType]'s known values. */ + enum class Known { + APPLICATION_X_WWW_FORM_URLENCODED, + APPLICATION_JSON, + } + + /** + * An enum containing [ResponseContentType]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [ResponseContentType] 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 { + APPLICATION_X_WWW_FORM_URLENCODED, + APPLICATION_JSON, + /** + * An enum member indicating that [ResponseContentType] 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) { + APPLICATION_X_WWW_FORM_URLENCODED -> Value.APPLICATION_X_WWW_FORM_URLENCODED + APPLICATION_JSON -> Value.APPLICATION_JSON + 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 ArcadeInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + APPLICATION_X_WWW_FORM_URLENCODED -> Known.APPLICATION_X_WWW_FORM_URLENCODED + APPLICATION_JSON -> Known.APPLICATION_JSON + else -> + throw ArcadeInvalidDataException("Unknown ResponseContentType: $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 ArcadeInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ArcadeInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): ResponseContentType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 ResponseContentType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class ResponseMap + @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 [ResponseMap]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ResponseMap]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(responseMap: ResponseMap) = apply { + additionalProperties = responseMap.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 [ResponseMap]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ResponseMap = ResponseMap(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ResponseMap = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 ResponseMap && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ResponseMap{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is TokenRequest && + endpoint == other.endpoint && + authHeaderValueFormat == other.authHeaderValueFormat && + authMethod == other.authMethod && + method == other.method && + params == other.params && + requestContentType == other.requestContentType && + responseContentType == other.responseContentType && + responseMap == other.responseMap && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + endpoint, + authHeaderValueFormat, + authMethod, + method, + params, + requestContentType, + responseContentType, + responseMap, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "TokenRequest{endpoint=$endpoint, authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, additionalProperties=$additionalProperties}" + } + + class UserInfoRequest + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val endpoint: JsonField, + private val triggers: JsonField, + private val authHeaderValueFormat: JsonField, + private val authMethod: JsonField, + private val method: JsonField, + private val params: JsonField, + private val requestContentType: JsonField, + private val responseContentType: JsonField, + private val responseMap: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("endpoint") + @ExcludeMissing + endpoint: JsonField = JsonMissing.of(), + @JsonProperty("triggers") + @ExcludeMissing + triggers: JsonField = JsonMissing.of(), + @JsonProperty("auth_header_value_format") + @ExcludeMissing + authHeaderValueFormat: JsonField = JsonMissing.of(), + @JsonProperty("auth_method") + @ExcludeMissing + authMethod: JsonField = JsonMissing.of(), + @JsonProperty("method") + @ExcludeMissing + method: JsonField = JsonMissing.of(), + @JsonProperty("params") + @ExcludeMissing + params: JsonField = JsonMissing.of(), + @JsonProperty("request_content_type") + @ExcludeMissing + requestContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_content_type") + @ExcludeMissing + responseContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_map") + @ExcludeMissing + responseMap: JsonField = JsonMissing.of(), + ) : this( + endpoint, + triggers, + authHeaderValueFormat, + authMethod, + method, + params, + requestContentType, + responseContentType, + responseMap, + mutableMapOf(), + ) + + /** + * @throws ArcadeInvalidDataException 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") + + /** + * @throws ArcadeInvalidDataException 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 triggers(): Triggers = triggers.getRequired("triggers") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authHeaderValueFormat(): Optional = + authHeaderValueFormat.getOptional("auth_header_value_format") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authMethod(): Optional = authMethod.getOptional("auth_method") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun method(): Optional = method.getOptional("method") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun params(): Optional = params.getOptional("params") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun requestContentType(): Optional = + requestContentType.getOptional("request_content_type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun responseContentType(): Optional = + responseContentType.getOptional("response_content_type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun responseMap(): Optional = responseMap.getOptional("response_map") + + /** + * 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 [triggers]. + * + * Unlike [triggers], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("triggers") + @ExcludeMissing + fun _triggers(): JsonField = triggers + + /** + * Returns the raw JSON value of [authHeaderValueFormat]. + * + * Unlike [authHeaderValueFormat], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("auth_header_value_format") + @ExcludeMissing + fun _authHeaderValueFormat(): JsonField = authHeaderValueFormat + + /** + * Returns the raw JSON value of [authMethod]. + * + * Unlike [authMethod], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("auth_method") + @ExcludeMissing + fun _authMethod(): JsonField = authMethod + + /** + * Returns the raw JSON value of [method]. + * + * Unlike [method], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("method") @ExcludeMissing fun _method(): JsonField = method + + /** + * Returns the raw JSON value of [params]. + * + * Unlike [params], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("params") @ExcludeMissing fun _params(): JsonField = params + + /** + * Returns the raw JSON value of [requestContentType]. + * + * Unlike [requestContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("request_content_type") + @ExcludeMissing + fun _requestContentType(): JsonField = requestContentType + + /** + * Returns the raw JSON value of [responseContentType]. + * + * Unlike [responseContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("response_content_type") + @ExcludeMissing + fun _responseContentType(): JsonField = responseContentType + + /** + * Returns the raw JSON value of [responseMap]. + * + * Unlike [responseMap], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("response_map") + @ExcludeMissing + fun _responseMap(): JsonField = responseMap + + @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 [UserInfoRequest]. + * + * The following fields are required: + * ```java + * .endpoint() + * .triggers() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UserInfoRequest]. */ + class Builder internal constructor() { + + private var endpoint: JsonField? = null + private var triggers: JsonField? = null + private var authHeaderValueFormat: JsonField = JsonMissing.of() + private var authMethod: JsonField = JsonMissing.of() + private var method: JsonField = JsonMissing.of() + private var params: JsonField = JsonMissing.of() + private var requestContentType: JsonField = JsonMissing.of() + private var responseContentType: JsonField = JsonMissing.of() + private var responseMap: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(userInfoRequest: UserInfoRequest) = apply { + endpoint = userInfoRequest.endpoint + triggers = userInfoRequest.triggers + authHeaderValueFormat = userInfoRequest.authHeaderValueFormat + authMethod = userInfoRequest.authMethod + method = userInfoRequest.method + params = userInfoRequest.params + requestContentType = userInfoRequest.requestContentType + responseContentType = userInfoRequest.responseContentType + responseMap = userInfoRequest.responseMap + additionalProperties = userInfoRequest.additionalProperties.toMutableMap() + } + + 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 } + + fun triggers(triggers: Triggers) = triggers(JsonField.of(triggers)) + + /** + * Sets [Builder.triggers] to an arbitrary JSON value. + * + * You should usually call [Builder.triggers] with a well-typed [Triggers] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun triggers(triggers: JsonField) = apply { this.triggers = triggers } + + fun authHeaderValueFormat(authHeaderValueFormat: String) = + authHeaderValueFormat(JsonField.of(authHeaderValueFormat)) + + /** + * Sets [Builder.authHeaderValueFormat] to an arbitrary JSON value. + * + * You should usually call [Builder.authHeaderValueFormat] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun authHeaderValueFormat(authHeaderValueFormat: JsonField) = apply { + this.authHeaderValueFormat = authHeaderValueFormat + } + + fun authMethod(authMethod: String) = authMethod(JsonField.of(authMethod)) + + /** + * Sets [Builder.authMethod] to an arbitrary JSON value. + * + * You should usually call [Builder.authMethod] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun authMethod(authMethod: JsonField) = apply { + this.authMethod = authMethod + } + + fun method(method: String) = method(JsonField.of(method)) + + /** + * Sets [Builder.method] to an arbitrary JSON value. + * + * You should usually call [Builder.method] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun method(method: JsonField) = apply { this.method = method } + + fun params(params: Params) = params(JsonField.of(params)) + + /** + * Sets [Builder.params] to an arbitrary JSON value. + * + * You should usually call [Builder.params] with a well-typed [Params] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun params(params: JsonField) = apply { this.params = params } + + fun requestContentType(requestContentType: RequestContentType) = + requestContentType(JsonField.of(requestContentType)) + + /** + * Sets [Builder.requestContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.requestContentType] with a well-typed + * [RequestContentType] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun requestContentType(requestContentType: JsonField) = apply { + this.requestContentType = requestContentType + } + + fun responseContentType(responseContentType: ResponseContentType) = + responseContentType(JsonField.of(responseContentType)) + + /** + * Sets [Builder.responseContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.responseContentType] with a well-typed + * [ResponseContentType] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun responseContentType(responseContentType: JsonField) = + apply { + this.responseContentType = responseContentType + } + + fun responseMap(responseMap: ResponseMap) = responseMap(JsonField.of(responseMap)) + + /** + * Sets [Builder.responseMap] to an arbitrary JSON value. + * + * You should usually call [Builder.responseMap] with a well-typed [ResponseMap] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun responseMap(responseMap: JsonField) = apply { + this.responseMap = responseMap + } + + 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 [UserInfoRequest]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .endpoint() + * .triggers() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UserInfoRequest = + UserInfoRequest( + checkRequired("endpoint", endpoint), + checkRequired("triggers", triggers), + authHeaderValueFormat, + authMethod, + method, + params, + requestContentType, + responseContentType, + responseMap, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): UserInfoRequest = apply { + if (validated) { + return@apply + } + + endpoint() + triggers().validate() + authHeaderValueFormat() + authMethod() + method() + params().ifPresent { it.validate() } + requestContentType().ifPresent { it.validate() } + responseContentType().ifPresent { it.validate() } + responseMap().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (endpoint.asKnown().isPresent) 1 else 0) + + (triggers.asKnown().getOrNull()?.validity() ?: 0) + + (if (authHeaderValueFormat.asKnown().isPresent) 1 else 0) + + (if (authMethod.asKnown().isPresent) 1 else 0) + + (if (method.asKnown().isPresent) 1 else 0) + + (params.asKnown().getOrNull()?.validity() ?: 0) + + (requestContentType.asKnown().getOrNull()?.validity() ?: 0) + + (responseContentType.asKnown().getOrNull()?.validity() ?: 0) + + (responseMap.asKnown().getOrNull()?.validity() ?: 0) + + class Triggers + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val onTokenGrant: JsonField, + private val onTokenRefresh: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("on_token_grant") + @ExcludeMissing + onTokenGrant: JsonField = JsonMissing.of(), + @JsonProperty("on_token_refresh") + @ExcludeMissing + onTokenRefresh: JsonField = JsonMissing.of(), + ) : this(onTokenGrant, onTokenRefresh, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun onTokenGrant(): Optional = onTokenGrant.getOptional("on_token_grant") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun onTokenRefresh(): Optional = + onTokenRefresh.getOptional("on_token_refresh") + + /** + * Returns the raw JSON value of [onTokenGrant]. + * + * Unlike [onTokenGrant], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("on_token_grant") + @ExcludeMissing + fun _onTokenGrant(): JsonField = onTokenGrant + + /** + * Returns the raw JSON value of [onTokenRefresh]. + * + * Unlike [onTokenRefresh], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("on_token_refresh") + @ExcludeMissing + fun _onTokenRefresh(): JsonField = onTokenRefresh + + @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 [Triggers]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Triggers]. */ + class Builder internal constructor() { + + private var onTokenGrant: JsonField = JsonMissing.of() + private var onTokenRefresh: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(triggers: Triggers) = apply { + onTokenGrant = triggers.onTokenGrant + onTokenRefresh = triggers.onTokenRefresh + additionalProperties = triggers.additionalProperties.toMutableMap() + } + + fun onTokenGrant(onTokenGrant: Boolean) = + onTokenGrant(JsonField.of(onTokenGrant)) + + /** + * Sets [Builder.onTokenGrant] to an arbitrary JSON value. + * + * You should usually call [Builder.onTokenGrant] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun onTokenGrant(onTokenGrant: JsonField) = apply { + this.onTokenGrant = onTokenGrant + } + + fun onTokenRefresh(onTokenRefresh: Boolean) = + onTokenRefresh(JsonField.of(onTokenRefresh)) + + /** + * Sets [Builder.onTokenRefresh] to an arbitrary JSON value. + * + * You should usually call [Builder.onTokenRefresh] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun onTokenRefresh(onTokenRefresh: JsonField) = apply { + this.onTokenRefresh = onTokenRefresh + } + + 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 [Triggers]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Triggers = + Triggers(onTokenGrant, onTokenRefresh, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Triggers = apply { + if (validated) { + return@apply + } + + onTokenGrant() + onTokenRefresh() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (onTokenGrant.asKnown().isPresent) 1 else 0) + + (if (onTokenRefresh.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Triggers && + onTokenGrant == other.onTokenGrant && + onTokenRefresh == other.onTokenRefresh && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(onTokenGrant, onTokenRefresh, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Triggers{onTokenGrant=$onTokenGrant, onTokenRefresh=$onTokenRefresh, additionalProperties=$additionalProperties}" + } + + class Params + @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 [Params]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Params]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(params: Params) = apply { + additionalProperties = params.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 [Params]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Params = Params(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Params = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 Params && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Params{additionalProperties=$additionalProperties}" + } + + class RequestContentType + @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 APPLICATION_X_WWW_FORM_URLENCODED = of("application/x-www-form-urlencoded") + + @JvmField val APPLICATION_JSON = of("application/json") + + @JvmStatic fun of(value: String) = RequestContentType(JsonField.of(value)) + } + + /** An enum containing [RequestContentType]'s known values. */ + enum class Known { + APPLICATION_X_WWW_FORM_URLENCODED, + APPLICATION_JSON, + } + + /** + * An enum containing [RequestContentType]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [RequestContentType] 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 { + APPLICATION_X_WWW_FORM_URLENCODED, + APPLICATION_JSON, + /** + * An enum member indicating that [RequestContentType] 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) { + APPLICATION_X_WWW_FORM_URLENCODED -> Value.APPLICATION_X_WWW_FORM_URLENCODED + APPLICATION_JSON -> Value.APPLICATION_JSON + 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 ArcadeInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + APPLICATION_X_WWW_FORM_URLENCODED -> Known.APPLICATION_X_WWW_FORM_URLENCODED + APPLICATION_JSON -> Known.APPLICATION_JSON + else -> + throw ArcadeInvalidDataException("Unknown RequestContentType: $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 ArcadeInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ArcadeInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): RequestContentType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 RequestContentType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class ResponseContentType + @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 APPLICATION_X_WWW_FORM_URLENCODED = of("application/x-www-form-urlencoded") + + @JvmField val APPLICATION_JSON = of("application/json") + + @JvmStatic fun of(value: String) = ResponseContentType(JsonField.of(value)) + } + + /** An enum containing [ResponseContentType]'s known values. */ + enum class Known { + APPLICATION_X_WWW_FORM_URLENCODED, + APPLICATION_JSON, + } + + /** + * An enum containing [ResponseContentType]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [ResponseContentType] 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 { + APPLICATION_X_WWW_FORM_URLENCODED, + APPLICATION_JSON, + /** + * An enum member indicating that [ResponseContentType] 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) { + APPLICATION_X_WWW_FORM_URLENCODED -> Value.APPLICATION_X_WWW_FORM_URLENCODED + APPLICATION_JSON -> Value.APPLICATION_JSON + 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 ArcadeInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + APPLICATION_X_WWW_FORM_URLENCODED -> Known.APPLICATION_X_WWW_FORM_URLENCODED + APPLICATION_JSON -> Known.APPLICATION_JSON + else -> + throw ArcadeInvalidDataException("Unknown ResponseContentType: $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 ArcadeInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ArcadeInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): ResponseContentType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 ResponseContentType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class ResponseMap + @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 [ResponseMap]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ResponseMap]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(responseMap: ResponseMap) = apply { + additionalProperties = responseMap.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 [ResponseMap]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ResponseMap = ResponseMap(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ResponseMap = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 ResponseMap && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ResponseMap{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UserInfoRequest && + endpoint == other.endpoint && + triggers == other.triggers && + authHeaderValueFormat == other.authHeaderValueFormat && + authMethod == other.authMethod && + method == other.method && + params == other.params && + requestContentType == other.requestContentType && + responseContentType == other.responseContentType && + responseMap == other.responseMap && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + endpoint, + triggers, + authHeaderValueFormat, + authMethod, + method, + params, + requestContentType, + responseContentType, + responseMap, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "UserInfoRequest{endpoint=$endpoint, triggers=$triggers, authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Oauth2 && + clientId == other.clientId && + authorizeRequest == other.authorizeRequest && + clientSecret == other.clientSecret && + pkce == other.pkce && + refreshRequest == other.refreshRequest && + scopeDelimiter == other.scopeDelimiter && + tokenIntrospectionRequest == other.tokenIntrospectionRequest && + tokenRequest == other.tokenRequest && + userInfoRequest == other.userInfoRequest && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + clientId, + authorizeRequest, + clientSecret, + pkce, + refreshRequest, + scopeDelimiter, + tokenIntrospectionRequest, + tokenRequest, + userInfoRequest, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Oauth2{clientId=$clientId, authorizeRequest=$authorizeRequest, clientSecret=$clientSecret, pkce=$pkce, refreshRequest=$refreshRequest, scopeDelimiter=$scopeDelimiter, tokenIntrospectionRequest=$tokenIntrospectionRequest, tokenRequest=$tokenRequest, userInfoRequest=$userInfoRequest, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AuthProviderCreateRequest && + id == other.id && + description == other.description && + externalId == other.externalId && + oauth2 == other.oauth2 && + providerId == other.providerId && + status == other.status && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + description, + externalId, + oauth2, + providerId, + status, + type, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AuthProviderCreateRequest{id=$id, description=$description, externalId=$externalId, oauth2=$oauth2, providerId=$providerId, status=$status, type=$type, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminAuthProviderDeleteParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/authproviders/AuthProviderDeleteParams.kt similarity index 74% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/AdminAuthProviderDeleteParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/admin/authproviders/AuthProviderDeleteParams.kt index 5d92b30..f7561c7 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminAuthProviderDeleteParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/authproviders/AuthProviderDeleteParams.kt @@ -1,58 +1,47 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.admin.authproviders import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params -import dev.arcade.core.checkRequired import dev.arcade.core.http.Headers import dev.arcade.core.http.QueryParams import dev.arcade.core.toImmutable import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Delete a specific auth provider */ -class AdminAuthProviderDeleteParams +class AuthProviderDeleteParams private constructor( - private val id: String, + private val id: String?, private val additionalHeaders: Headers, private val additionalQueryParams: QueryParams, private val additionalBodyProperties: Map, ) : Params { - fun id(): String = id - - fun _additionalHeaders(): Headers = additionalHeaders - - fun _additionalQueryParams(): QueryParams = additionalQueryParams + fun id(): Optional = Optional.ofNullable(id) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties - @JvmSynthetic - internal fun _body(): Optional> = - Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders - fun getPathParam(index: Int): String { - return when (index) { - 0 -> id - else -> "" - } - } + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): AuthProviderDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [AuthProviderDeleteParams]. */ @JvmStatic fun builder() = Builder() } - /** A builder for [AdminAuthProviderDeleteParams]. */ - @NoAutoDetect + /** A builder for [AuthProviderDeleteParams]. */ class Builder internal constructor() { private var id: String? = null @@ -61,15 +50,18 @@ private constructor( private var additionalBodyProperties: MutableMap = mutableMapOf() @JvmSynthetic - internal fun from(adminAuthProviderDeleteParams: AdminAuthProviderDeleteParams) = apply { - id = adminAuthProviderDeleteParams.id - additionalHeaders = adminAuthProviderDeleteParams.additionalHeaders.toBuilder() - additionalQueryParams = adminAuthProviderDeleteParams.additionalQueryParams.toBuilder() + internal fun from(authProviderDeleteParams: AuthProviderDeleteParams) = apply { + id = authProviderDeleteParams.id + additionalHeaders = authProviderDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = authProviderDeleteParams.additionalQueryParams.toBuilder() additionalBodyProperties = - adminAuthProviderDeleteParams.additionalBodyProperties.toMutableMap() + authProviderDeleteParams.additionalBodyProperties.toMutableMap() } - fun id(id: String) = apply { this.id = id } + 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() @@ -191,25 +183,48 @@ private constructor( keys.forEach(::removeAdditionalBodyProperty) } - fun build(): AdminAuthProviderDeleteParams = - AdminAuthProviderDeleteParams( - checkRequired("id", id), + /** + * Returns an immutable instance of [AuthProviderDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): AuthProviderDeleteParams = + AuthProviderDeleteParams( + 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 /* spotless:off */ other is AdminAuthProviderDeleteParams && id == other.id && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is AuthProviderDeleteParams && + id == other.id && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(id, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(id, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = - "AdminAuthProviderDeleteParams{id=$id, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" + "AuthProviderDeleteParams{id=$id, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminAuthProviderGetParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/authproviders/AuthProviderGetParams.kt similarity index 72% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/AdminAuthProviderGetParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/admin/authproviders/AuthProviderGetParams.kt index 1d078d6..05f841b 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminAuthProviderGetParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/authproviders/AuthProviderGetParams.kt @@ -1,48 +1,41 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.admin.authproviders -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params -import dev.arcade.core.checkRequired import dev.arcade.core.http.Headers import dev.arcade.core.http.QueryParams import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Get the details of a specific auth provider */ -class AdminAuthProviderGetParams +class AuthProviderGetParams private constructor( - private val id: String, + private val id: String?, private val additionalHeaders: Headers, private val additionalQueryParams: QueryParams, ) : Params { - fun id(): String = id + 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 - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> id - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): AuthProviderGetParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [AuthProviderGetParams]. */ @JvmStatic fun builder() = Builder() } - /** A builder for [AdminAuthProviderGetParams]. */ - @NoAutoDetect + /** A builder for [AuthProviderGetParams]. */ class Builder internal constructor() { private var id: String? = null @@ -50,13 +43,16 @@ private constructor( private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @JvmSynthetic - internal fun from(adminAuthProviderGetParams: AdminAuthProviderGetParams) = apply { - id = adminAuthProviderGetParams.id - additionalHeaders = adminAuthProviderGetParams.additionalHeaders.toBuilder() - additionalQueryParams = adminAuthProviderGetParams.additionalQueryParams.toBuilder() + internal fun from(authProviderGetParams: AuthProviderGetParams) = apply { + id = authProviderGetParams.id + additionalHeaders = authProviderGetParams.additionalHeaders.toBuilder() + additionalQueryParams = authProviderGetParams.additionalQueryParams.toBuilder() } - fun id(id: String) = apply { this.id = id } + 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() @@ -156,24 +152,38 @@ private constructor( additionalQueryParams.removeAll(keys) } - fun build(): AdminAuthProviderGetParams = - AdminAuthProviderGetParams( - checkRequired("id", id), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + /** + * Returns an immutable instance of [AuthProviderGetParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): AuthProviderGetParams = + AuthProviderGetParams(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 /* spotless:off */ other is AdminAuthProviderGetParams && id == other.id && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is AuthProviderGetParams && + id == other.id && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(id, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(id, additionalHeaders, additionalQueryParams) override fun toString() = - "AdminAuthProviderGetParams{id=$id, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" + "AuthProviderGetParams{id=$id, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminAuthProviderListParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/authproviders/AuthProviderListParams.kt similarity index 78% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/AdminAuthProviderListParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/admin/authproviders/AuthProviderListParams.kt index 6a810ec..576b400 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminAuthProviderListParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/authproviders/AuthProviderListParams.kt @@ -1,46 +1,45 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.admin.authproviders -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params import dev.arcade.core.http.Headers import dev.arcade.core.http.QueryParams import java.util.Objects /** List a page of auth providers that are available to the caller */ -class AdminAuthProviderListParams +class AuthProviderListParams 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 - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): AuthProviderListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [AuthProviderListParams]. */ @JvmStatic fun builder() = Builder() } - /** A builder for [AdminAuthProviderListParams]. */ - @NoAutoDetect + /** A builder for [AuthProviderListParams]. */ class Builder internal constructor() { private var additionalHeaders: Headers.Builder = Headers.builder() private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @JvmSynthetic - internal fun from(adminAuthProviderListParams: AdminAuthProviderListParams) = apply { - additionalHeaders = adminAuthProviderListParams.additionalHeaders.toBuilder() - additionalQueryParams = adminAuthProviderListParams.additionalQueryParams.toBuilder() + internal fun from(authProviderListParams: AuthProviderListParams) = apply { + additionalHeaders = authProviderListParams.additionalHeaders.toBuilder() + additionalQueryParams = authProviderListParams.additionalQueryParams.toBuilder() } fun additionalHeaders(additionalHeaders: Headers) = apply { @@ -141,20 +140,31 @@ private constructor( additionalQueryParams.removeAll(keys) } - fun build(): AdminAuthProviderListParams = - AdminAuthProviderListParams(additionalHeaders.build(), additionalQueryParams.build()) + /** + * Returns an immutable instance of [AuthProviderListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): AuthProviderListParams = + AuthProviderListParams(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 /* spotless:off */ other is AdminAuthProviderListParams && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is AuthProviderListParams && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(additionalHeaders, additionalQueryParams) override fun toString() = - "AdminAuthProviderListParams{additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" + "AuthProviderListParams{additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/authproviders/AuthProviderListResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/authproviders/AuthProviderListResponse.kt new file mode 100644 index 0000000..d6bc9c0 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/authproviders/AuthProviderListResponse.kt @@ -0,0 +1,304 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.admin.authproviders + +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 dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.core.checkKnown +import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class AuthProviderListResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val items: JsonField>, + private val limit: JsonField, + private val offset: JsonField, + private val pageCount: JsonField, + private val totalCount: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("items") + @ExcludeMissing + items: JsonField> = JsonMissing.of(), + @JsonProperty("limit") @ExcludeMissing limit: JsonField = JsonMissing.of(), + @JsonProperty("offset") @ExcludeMissing offset: JsonField = JsonMissing.of(), + @JsonProperty("page_count") @ExcludeMissing pageCount: JsonField = JsonMissing.of(), + @JsonProperty("total_count") @ExcludeMissing totalCount: JsonField = JsonMissing.of(), + ) : this(items, limit, offset, pageCount, totalCount, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun items(): Optional> = items.getOptional("items") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun limit(): Optional = limit.getOptional("limit") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun offset(): Optional = offset.getOptional("offset") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun pageCount(): Optional = pageCount.getOptional("page_count") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun totalCount(): Optional = totalCount.getOptional("total_count") + + /** + * Returns the raw JSON value of [items]. + * + * Unlike [items], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("items") + @ExcludeMissing + fun _items(): JsonField> = items + + /** + * Returns the raw JSON value of [limit]. + * + * Unlike [limit], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("limit") @ExcludeMissing fun _limit(): JsonField = limit + + /** + * Returns the raw JSON value of [offset]. + * + * Unlike [offset], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("offset") @ExcludeMissing fun _offset(): JsonField = offset + + /** + * Returns the raw JSON value of [pageCount]. + * + * Unlike [pageCount], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("page_count") @ExcludeMissing fun _pageCount(): JsonField = pageCount + + /** + * Returns the raw JSON value of [totalCount]. + * + * Unlike [totalCount], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("total_count") @ExcludeMissing fun _totalCount(): JsonField = totalCount + + @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 [AuthProviderListResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AuthProviderListResponse]. */ + class Builder internal constructor() { + + private var items: JsonField>? = null + private var limit: JsonField = JsonMissing.of() + private var offset: JsonField = JsonMissing.of() + private var pageCount: JsonField = JsonMissing.of() + private var totalCount: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(authProviderListResponse: AuthProviderListResponse) = apply { + items = authProviderListResponse.items.map { it.toMutableList() } + limit = authProviderListResponse.limit + offset = authProviderListResponse.offset + pageCount = authProviderListResponse.pageCount + totalCount = authProviderListResponse.totalCount + additionalProperties = authProviderListResponse.additionalProperties.toMutableMap() + } + + fun items(items: List) = items(JsonField.of(items)) + + /** + * Sets [Builder.items] to an arbitrary JSON value. + * + * You should usually call [Builder.items] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun items(items: JsonField>) = apply { + this.items = items.map { it.toMutableList() } + } + + /** + * Adds a single [AuthProviderResponse] to [items]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addItem(item: AuthProviderResponse) = apply { + items = + (items ?: JsonField.of(mutableListOf())).also { checkKnown("items", it).add(item) } + } + + fun limit(limit: Long) = limit(JsonField.of(limit)) + + /** + * Sets [Builder.limit] to an arbitrary JSON value. + * + * You should usually call [Builder.limit] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun limit(limit: JsonField) = apply { this.limit = limit } + + fun offset(offset: Long) = offset(JsonField.of(offset)) + + /** + * Sets [Builder.offset] to an arbitrary JSON value. + * + * You should usually call [Builder.offset] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun offset(offset: JsonField) = apply { this.offset = offset } + + fun pageCount(pageCount: Long) = pageCount(JsonField.of(pageCount)) + + /** + * Sets [Builder.pageCount] to an arbitrary JSON value. + * + * You should usually call [Builder.pageCount] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun pageCount(pageCount: JsonField) = apply { this.pageCount = pageCount } + + fun totalCount(totalCount: Long) = totalCount(JsonField.of(totalCount)) + + /** + * Sets [Builder.totalCount] to an arbitrary JSON value. + * + * You should usually call [Builder.totalCount] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun totalCount(totalCount: JsonField) = apply { this.totalCount = totalCount } + + 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 [AuthProviderListResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): AuthProviderListResponse = + AuthProviderListResponse( + (items ?: JsonMissing.of()).map { it.toImmutable() }, + limit, + offset, + pageCount, + totalCount, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): AuthProviderListResponse = apply { + if (validated) { + return@apply + } + + items().ifPresent { it.forEach { it.validate() } } + limit() + offset() + pageCount() + totalCount() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (items.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (limit.asKnown().isPresent) 1 else 0) + + (if (offset.asKnown().isPresent) 1 else 0) + + (if (pageCount.asKnown().isPresent) 1 else 0) + + (if (totalCount.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AuthProviderListResponse && + items == other.items && + limit == other.limit && + offset == other.offset && + pageCount == other.pageCount && + totalCount == other.totalCount && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(items, limit, offset, pageCount, totalCount, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AuthProviderListResponse{items=$items, limit=$limit, offset=$offset, pageCount=$pageCount, totalCount=$totalCount, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminAuthProviderPatchParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/authproviders/AuthProviderPatchParams.kt similarity index 68% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/AdminAuthProviderPatchParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/admin/authproviders/AuthProviderPatchParams.kt index 4f003e3..e02a076 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminAuthProviderPatchParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/authproviders/AuthProviderPatchParams.kt @@ -1,73 +1,73 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.admin.authproviders import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params import dev.arcade.core.checkRequired import dev.arcade.core.http.Headers import dev.arcade.core.http.QueryParams import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Patch an existing auth provider */ -class AdminAuthProviderPatchParams +class AuthProviderPatchParams private constructor( - private val id: String, + private val pathId: String?, private val authProviderUpdateRequest: AuthProviderUpdateRequest, private val additionalHeaders: Headers, private val additionalQueryParams: QueryParams, ) : Params { - fun id(): String = id + fun pathId(): Optional = Optional.ofNullable(pathId) fun authProviderUpdateRequest(): AuthProviderUpdateRequest = authProviderUpdateRequest fun _additionalBodyProperties(): Map = authProviderUpdateRequest._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): AuthProviderUpdateRequest = authProviderUpdateRequest - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> id - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [AuthProviderPatchParams]. + * + * The following fields are required: + * ```java + * .authProviderUpdateRequest() + * ``` + */ @JvmStatic fun builder() = Builder() } - /** A builder for [AdminAuthProviderPatchParams]. */ - @NoAutoDetect + /** A builder for [AuthProviderPatchParams]. */ class Builder internal constructor() { - private var id: String? = null + private var pathId: String? = null private var authProviderUpdateRequest: AuthProviderUpdateRequest? = null private var additionalHeaders: Headers.Builder = Headers.builder() private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @JvmSynthetic - internal fun from(adminAuthProviderPatchParams: AdminAuthProviderPatchParams) = apply { - id = adminAuthProviderPatchParams.id - authProviderUpdateRequest = adminAuthProviderPatchParams.authProviderUpdateRequest - additionalHeaders = adminAuthProviderPatchParams.additionalHeaders.toBuilder() - additionalQueryParams = adminAuthProviderPatchParams.additionalQueryParams.toBuilder() + internal fun from(authProviderPatchParams: AuthProviderPatchParams) = apply { + pathId = authProviderPatchParams.pathId + authProviderUpdateRequest = authProviderPatchParams.authProviderUpdateRequest + additionalHeaders = authProviderPatchParams.additionalHeaders.toBuilder() + additionalQueryParams = authProviderPatchParams.additionalQueryParams.toBuilder() } - fun id(id: String) = apply { this.id = id } + fun pathId(pathId: String?) = apply { this.pathId = pathId } + + /** Alias for calling [Builder.pathId] with `pathId.orElse(null)`. */ + fun pathId(pathId: Optional) = pathId(pathId.getOrNull()) fun authProviderUpdateRequest(authProviderUpdateRequest: AuthProviderUpdateRequest) = apply { @@ -172,25 +172,54 @@ private constructor( additionalQueryParams.removeAll(keys) } - fun build(): AdminAuthProviderPatchParams = - AdminAuthProviderPatchParams( - checkRequired("id", id), + /** + * Returns an immutable instance of [AuthProviderPatchParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .authProviderUpdateRequest() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AuthProviderPatchParams = + AuthProviderPatchParams( + pathId, checkRequired("authProviderUpdateRequest", authProviderUpdateRequest), additionalHeaders.build(), additionalQueryParams.build(), ) } + fun _body(): AuthProviderUpdateRequest = authProviderUpdateRequest + + fun _pathParam(index: Int): String = + when (index) { + 0 -> pathId ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is AdminAuthProviderPatchParams && id == other.id && authProviderUpdateRequest == other.authProviderUpdateRequest && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is AuthProviderPatchParams && + pathId == other.pathId && + authProviderUpdateRequest == other.authProviderUpdateRequest && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(id, authProviderUpdateRequest, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(pathId, authProviderUpdateRequest, additionalHeaders, additionalQueryParams) override fun toString() = - "AdminAuthProviderPatchParams{id=$id, authProviderUpdateRequest=$authProviderUpdateRequest, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" + "AuthProviderPatchParams{pathId=$pathId, authProviderUpdateRequest=$authProviderUpdateRequest, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/authproviders/AuthProviderResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/authproviders/AuthProviderResponse.kt new file mode 100644 index 0000000..c00cfb8 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/authproviders/AuthProviderResponse.kt @@ -0,0 +1,5833 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.admin.authproviders + +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 dev.arcade.core.Enum +import dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class AuthProviderResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val id: JsonField, + private val binding: JsonField, + private val createdAt: JsonField, + private val description: JsonField, + private val oauth2: JsonField, + private val providerId: JsonField, + private val status: JsonField, + private val type: JsonField, + private val updatedAt: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("binding") @ExcludeMissing binding: JsonField = JsonMissing.of(), + @JsonProperty("created_at") @ExcludeMissing createdAt: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("oauth2") @ExcludeMissing oauth2: JsonField = JsonMissing.of(), + @JsonProperty("provider_id") + @ExcludeMissing + providerId: JsonField = JsonMissing.of(), + @JsonProperty("status") @ExcludeMissing status: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + @JsonProperty("updated_at") @ExcludeMissing updatedAt: JsonField = JsonMissing.of(), + ) : this( + id, + binding, + createdAt, + description, + oauth2, + providerId, + status, + type, + updatedAt, + mutableMapOf(), + ) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun binding(): Optional = binding.getOptional("binding") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun createdAt(): Optional = createdAt.getOptional("created_at") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun oauth2(): Optional = oauth2.getOptional("oauth2") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun providerId(): Optional = providerId.getOptional("provider_id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun status(): Optional = status.getOptional("status") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun updatedAt(): Optional = updatedAt.getOptional("updated_at") + + /** + * 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 [binding]. + * + * Unlike [binding], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("binding") @ExcludeMissing fun _binding(): JsonField = binding + + /** + * 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 [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 [oauth2]. + * + * Unlike [oauth2], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("oauth2") @ExcludeMissing fun _oauth2(): JsonField = oauth2 + + /** + * Returns the raw JSON value of [providerId]. + * + * Unlike [providerId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("provider_id") @ExcludeMissing fun _providerId(): JsonField = providerId + + /** + * 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 + + /** + * Returns the raw JSON value of [updatedAt]. + * + * Unlike [updatedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("updated_at") @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 [AuthProviderResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AuthProviderResponse]. */ + class Builder internal constructor() { + + private var id: JsonField = JsonMissing.of() + private var binding: JsonField = JsonMissing.of() + private var createdAt: JsonField = JsonMissing.of() + private var description: JsonField = JsonMissing.of() + private var oauth2: JsonField = JsonMissing.of() + private var providerId: JsonField = JsonMissing.of() + private var status: JsonField = JsonMissing.of() + private var type: JsonField = JsonMissing.of() + private var updatedAt: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(authProviderResponse: AuthProviderResponse) = apply { + id = authProviderResponse.id + binding = authProviderResponse.binding + createdAt = authProviderResponse.createdAt + description = authProviderResponse.description + oauth2 = authProviderResponse.oauth2 + providerId = authProviderResponse.providerId + status = authProviderResponse.status + type = authProviderResponse.type + updatedAt = authProviderResponse.updatedAt + additionalProperties = authProviderResponse.additionalProperties.toMutableMap() + } + + 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 binding(binding: Binding) = binding(JsonField.of(binding)) + + /** + * Sets [Builder.binding] to an arbitrary JSON value. + * + * You should usually call [Builder.binding] with a well-typed [Binding] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun binding(binding: JsonField) = apply { this.binding = binding } + + fun createdAt(createdAt: String) = createdAt(JsonField.of(createdAt)) + + /** + * Sets [Builder.createdAt] to an arbitrary JSON value. + * + * You should usually call [Builder.createdAt] with a well-typed [String] 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 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 } + + fun oauth2(oauth2: Oauth2) = oauth2(JsonField.of(oauth2)) + + /** + * Sets [Builder.oauth2] to an arbitrary JSON value. + * + * You should usually call [Builder.oauth2] with a well-typed [Oauth2] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun oauth2(oauth2: JsonField) = apply { this.oauth2 = oauth2 } + + fun providerId(providerId: String) = providerId(JsonField.of(providerId)) + + /** + * Sets [Builder.providerId] to an arbitrary JSON value. + * + * You should usually call [Builder.providerId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun providerId(providerId: JsonField) = apply { this.providerId = providerId } + + fun status(status: String) = status(JsonField.of(status)) + + /** + * Sets [Builder.status] to an arbitrary JSON value. + * + * You should usually call [Builder.status] with a well-typed [String] 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 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 updatedAt(updatedAt: String) = updatedAt(JsonField.of(updatedAt)) + + /** + * Sets [Builder.updatedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.updatedAt] with a well-typed [String] 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 [AuthProviderResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): AuthProviderResponse = + AuthProviderResponse( + id, + binding, + createdAt, + description, + oauth2, + providerId, + status, + type, + updatedAt, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): AuthProviderResponse = apply { + if (validated) { + return@apply + } + + id() + binding().ifPresent { it.validate() } + createdAt() + description() + oauth2().ifPresent { it.validate() } + providerId() + status() + type() + updatedAt() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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) + + (binding.asKnown().getOrNull()?.validity() ?: 0) + + (if (createdAt.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (oauth2.asKnown().getOrNull()?.validity() ?: 0) + + (if (providerId.asKnown().isPresent) 1 else 0) + + (if (status.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) + + (if (updatedAt.asKnown().isPresent) 1 else 0) + + class Binding + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws ArcadeInvalidDataException 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 [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 [Binding]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Binding]. */ + class Builder internal constructor() { + + private var id: JsonField = JsonMissing.of() + private var type: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(binding: Binding) = apply { + id = binding.id + type = binding.type + additionalProperties = binding.additionalProperties.toMutableMap() + } + + 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 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 [Binding]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Binding = Binding(id, type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Binding = apply { + if (validated) { + return@apply + } + + id() + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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) + (type.asKnown().getOrNull()?.validity() ?: 0) + + 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 STATIC = of("static") + + @JvmField val TENANT = of("tenant") + + @JvmField val PROJECT = of("project") + + @JvmField val ACCOUNT = of("account") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + STATIC, + TENANT, + PROJECT, + ACCOUNT, + } + + /** + * 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 { + STATIC, + TENANT, + PROJECT, + ACCOUNT, + /** 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) { + STATIC -> Value.STATIC + TENANT -> Value.TENANT + PROJECT -> Value.PROJECT + ACCOUNT -> Value.ACCOUNT + 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 ArcadeInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + STATIC -> Known.STATIC + TENANT -> Known.TENANT + PROJECT -> Known.PROJECT + ACCOUNT -> Known.ACCOUNT + else -> throw ArcadeInvalidDataException("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 ArcadeInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ArcadeInvalidDataException("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: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 Binding && + 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() = + "Binding{id=$id, type=$type, additionalProperties=$additionalProperties}" + } + + class Oauth2 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val authorizeRequest: JsonField, + private val clientId: JsonField, + private val clientSecret: JsonField, + private val pkce: JsonField, + private val redirectUri: JsonField, + private val refreshRequest: JsonField, + private val scopeDelimiter: JsonField, + private val tokenIntrospectionRequest: JsonField, + private val tokenRequest: JsonField, + private val userInfoRequest: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("authorize_request") + @ExcludeMissing + authorizeRequest: JsonField = JsonMissing.of(), + @JsonProperty("client_id") + @ExcludeMissing + clientId: JsonField = JsonMissing.of(), + @JsonProperty("client_secret") + @ExcludeMissing + clientSecret: JsonField = JsonMissing.of(), + @JsonProperty("pkce") @ExcludeMissing pkce: JsonField = JsonMissing.of(), + @JsonProperty("redirect_uri") + @ExcludeMissing + redirectUri: JsonField = JsonMissing.of(), + @JsonProperty("refresh_request") + @ExcludeMissing + refreshRequest: JsonField = JsonMissing.of(), + @JsonProperty("scope_delimiter") + @ExcludeMissing + scopeDelimiter: JsonField = JsonMissing.of(), + @JsonProperty("token_introspection_request") + @ExcludeMissing + tokenIntrospectionRequest: JsonField = JsonMissing.of(), + @JsonProperty("token_request") + @ExcludeMissing + tokenRequest: JsonField = JsonMissing.of(), + @JsonProperty("user_info_request") + @ExcludeMissing + userInfoRequest: JsonField = JsonMissing.of(), + ) : this( + authorizeRequest, + clientId, + clientSecret, + pkce, + redirectUri, + refreshRequest, + scopeDelimiter, + tokenIntrospectionRequest, + tokenRequest, + userInfoRequest, + mutableMapOf(), + ) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun authorizeRequest(): Optional = + authorizeRequest.getOptional("authorize_request") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun clientId(): Optional = clientId.getOptional("client_id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun clientSecret(): Optional = clientSecret.getOptional("client_secret") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun pkce(): Optional = pkce.getOptional("pkce") + + /** + * The redirect URI required for this provider. + * + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun redirectUri(): Optional = redirectUri.getOptional("redirect_uri") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun refreshRequest(): Optional = + refreshRequest.getOptional("refresh_request") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun scopeDelimiter(): Optional = scopeDelimiter.getOptional("scope_delimiter") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun tokenIntrospectionRequest(): Optional = + tokenIntrospectionRequest.getOptional("token_introspection_request") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun tokenRequest(): Optional = tokenRequest.getOptional("token_request") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun userInfoRequest(): Optional = + userInfoRequest.getOptional("user_info_request") + + /** + * Returns the raw JSON value of [authorizeRequest]. + * + * Unlike [authorizeRequest], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("authorize_request") + @ExcludeMissing + fun _authorizeRequest(): JsonField = authorizeRequest + + /** + * Returns the raw JSON value of [clientId]. + * + * Unlike [clientId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("client_id") @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("client_secret") + @ExcludeMissing + fun _clientSecret(): JsonField = clientSecret + + /** + * Returns the raw JSON value of [pkce]. + * + * Unlike [pkce], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("pkce") @ExcludeMissing fun _pkce(): JsonField = pkce + + /** + * Returns the raw JSON value of [redirectUri]. + * + * Unlike [redirectUri], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("redirect_uri") + @ExcludeMissing + fun _redirectUri(): JsonField = redirectUri + + /** + * Returns the raw JSON value of [refreshRequest]. + * + * Unlike [refreshRequest], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("refresh_request") + @ExcludeMissing + fun _refreshRequest(): JsonField = refreshRequest + + /** + * Returns the raw JSON value of [scopeDelimiter]. + * + * Unlike [scopeDelimiter], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("scope_delimiter") + @ExcludeMissing + fun _scopeDelimiter(): JsonField = scopeDelimiter + + /** + * Returns the raw JSON value of [tokenIntrospectionRequest]. + * + * Unlike [tokenIntrospectionRequest], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("token_introspection_request") + @ExcludeMissing + fun _tokenIntrospectionRequest(): JsonField = + tokenIntrospectionRequest + + /** + * Returns the raw JSON value of [tokenRequest]. + * + * Unlike [tokenRequest], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("token_request") + @ExcludeMissing + fun _tokenRequest(): JsonField = tokenRequest + + /** + * Returns the raw JSON value of [userInfoRequest]. + * + * Unlike [userInfoRequest], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("user_info_request") + @ExcludeMissing + fun _userInfoRequest(): JsonField = userInfoRequest + + @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 [Oauth2]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Oauth2]. */ + class Builder internal constructor() { + + private var authorizeRequest: JsonField = JsonMissing.of() + private var clientId: JsonField = JsonMissing.of() + private var clientSecret: JsonField = JsonMissing.of() + private var pkce: JsonField = JsonMissing.of() + private var redirectUri: JsonField = JsonMissing.of() + private var refreshRequest: JsonField = JsonMissing.of() + private var scopeDelimiter: JsonField = JsonMissing.of() + private var tokenIntrospectionRequest: JsonField = + JsonMissing.of() + private var tokenRequest: JsonField = JsonMissing.of() + private var userInfoRequest: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(oauth2: Oauth2) = apply { + authorizeRequest = oauth2.authorizeRequest + clientId = oauth2.clientId + clientSecret = oauth2.clientSecret + pkce = oauth2.pkce + redirectUri = oauth2.redirectUri + refreshRequest = oauth2.refreshRequest + scopeDelimiter = oauth2.scopeDelimiter + tokenIntrospectionRequest = oauth2.tokenIntrospectionRequest + tokenRequest = oauth2.tokenRequest + userInfoRequest = oauth2.userInfoRequest + additionalProperties = oauth2.additionalProperties.toMutableMap() + } + + fun authorizeRequest(authorizeRequest: AuthorizeRequest) = + authorizeRequest(JsonField.of(authorizeRequest)) + + /** + * Sets [Builder.authorizeRequest] to an arbitrary JSON value. + * + * You should usually call [Builder.authorizeRequest] with a well-typed + * [AuthorizeRequest] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun authorizeRequest(authorizeRequest: JsonField) = apply { + this.authorizeRequest = authorizeRequest + } + + 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 } + + fun clientSecret(clientSecret: ClientSecret) = clientSecret(JsonField.of(clientSecret)) + + /** + * Sets [Builder.clientSecret] to an arbitrary JSON value. + * + * You should usually call [Builder.clientSecret] with a well-typed [ClientSecret] 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 + } + + fun pkce(pkce: Pkce) = pkce(JsonField.of(pkce)) + + /** + * Sets [Builder.pkce] to an arbitrary JSON value. + * + * You should usually call [Builder.pkce] with a well-typed [Pkce] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun pkce(pkce: JsonField) = apply { this.pkce = pkce } + + /** The redirect URI required for this provider. */ + fun redirectUri(redirectUri: String) = redirectUri(JsonField.of(redirectUri)) + + /** + * Sets [Builder.redirectUri] to an arbitrary JSON value. + * + * You should usually call [Builder.redirectUri] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun redirectUri(redirectUri: JsonField) = apply { + this.redirectUri = redirectUri + } + + fun refreshRequest(refreshRequest: RefreshRequest) = + refreshRequest(JsonField.of(refreshRequest)) + + /** + * Sets [Builder.refreshRequest] to an arbitrary JSON value. + * + * You should usually call [Builder.refreshRequest] with a well-typed [RefreshRequest] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun refreshRequest(refreshRequest: JsonField) = apply { + this.refreshRequest = refreshRequest + } + + fun scopeDelimiter(scopeDelimiter: String) = + scopeDelimiter(JsonField.of(scopeDelimiter)) + + /** + * Sets [Builder.scopeDelimiter] to an arbitrary JSON value. + * + * You should usually call [Builder.scopeDelimiter] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun scopeDelimiter(scopeDelimiter: JsonField) = apply { + this.scopeDelimiter = scopeDelimiter + } + + fun tokenIntrospectionRequest(tokenIntrospectionRequest: TokenIntrospectionRequest) = + tokenIntrospectionRequest(JsonField.of(tokenIntrospectionRequest)) + + /** + * Sets [Builder.tokenIntrospectionRequest] to an arbitrary JSON value. + * + * You should usually call [Builder.tokenIntrospectionRequest] with a well-typed + * [TokenIntrospectionRequest] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun tokenIntrospectionRequest( + tokenIntrospectionRequest: JsonField + ) = apply { this.tokenIntrospectionRequest = tokenIntrospectionRequest } + + fun tokenRequest(tokenRequest: TokenRequest) = tokenRequest(JsonField.of(tokenRequest)) + + /** + * Sets [Builder.tokenRequest] to an arbitrary JSON value. + * + * You should usually call [Builder.tokenRequest] with a well-typed [TokenRequest] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun tokenRequest(tokenRequest: JsonField) = apply { + this.tokenRequest = tokenRequest + } + + fun userInfoRequest(userInfoRequest: UserInfoRequest) = + userInfoRequest(JsonField.of(userInfoRequest)) + + /** + * Sets [Builder.userInfoRequest] to an arbitrary JSON value. + * + * You should usually call [Builder.userInfoRequest] with a well-typed [UserInfoRequest] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun userInfoRequest(userInfoRequest: JsonField) = apply { + this.userInfoRequest = userInfoRequest + } + + 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 [Oauth2]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Oauth2 = + Oauth2( + authorizeRequest, + clientId, + clientSecret, + pkce, + redirectUri, + refreshRequest, + scopeDelimiter, + tokenIntrospectionRequest, + tokenRequest, + userInfoRequest, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Oauth2 = apply { + if (validated) { + return@apply + } + + authorizeRequest().ifPresent { it.validate() } + clientId() + clientSecret().ifPresent { it.validate() } + pkce().ifPresent { it.validate() } + redirectUri() + refreshRequest().ifPresent { it.validate() } + scopeDelimiter() + tokenIntrospectionRequest().ifPresent { it.validate() } + tokenRequest().ifPresent { it.validate() } + userInfoRequest().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (authorizeRequest.asKnown().getOrNull()?.validity() ?: 0) + + (if (clientId.asKnown().isPresent) 1 else 0) + + (clientSecret.asKnown().getOrNull()?.validity() ?: 0) + + (pkce.asKnown().getOrNull()?.validity() ?: 0) + + (if (redirectUri.asKnown().isPresent) 1 else 0) + + (refreshRequest.asKnown().getOrNull()?.validity() ?: 0) + + (if (scopeDelimiter.asKnown().isPresent) 1 else 0) + + (tokenIntrospectionRequest.asKnown().getOrNull()?.validity() ?: 0) + + (tokenRequest.asKnown().getOrNull()?.validity() ?: 0) + + (userInfoRequest.asKnown().getOrNull()?.validity() ?: 0) + + class AuthorizeRequest + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val authHeaderValueFormat: JsonField, + private val authMethod: JsonField, + private val endpoint: JsonField, + private val expirationFormat: JsonField, + private val method: JsonField, + private val params: JsonField, + private val requestContentType: JsonField, + private val responseContentType: JsonField, + private val responseMap: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("auth_header_value_format") + @ExcludeMissing + authHeaderValueFormat: JsonField = JsonMissing.of(), + @JsonProperty("auth_method") + @ExcludeMissing + authMethod: JsonField = JsonMissing.of(), + @JsonProperty("endpoint") + @ExcludeMissing + endpoint: JsonField = JsonMissing.of(), + @JsonProperty("expiration_format") + @ExcludeMissing + expirationFormat: JsonField = JsonMissing.of(), + @JsonProperty("method") + @ExcludeMissing + method: JsonField = JsonMissing.of(), + @JsonProperty("params") + @ExcludeMissing + params: JsonField = JsonMissing.of(), + @JsonProperty("request_content_type") + @ExcludeMissing + requestContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_content_type") + @ExcludeMissing + responseContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_map") + @ExcludeMissing + responseMap: JsonField = JsonMissing.of(), + ) : this( + authHeaderValueFormat, + authMethod, + endpoint, + expirationFormat, + method, + params, + requestContentType, + responseContentType, + responseMap, + mutableMapOf(), + ) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authHeaderValueFormat(): Optional = + authHeaderValueFormat.getOptional("auth_header_value_format") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authMethod(): Optional = authMethod.getOptional("auth_method") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun endpoint(): Optional = endpoint.getOptional("endpoint") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun expirationFormat(): Optional = + expirationFormat.getOptional("expiration_format") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun method(): Optional = method.getOptional("method") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun params(): Optional = params.getOptional("params") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun requestContentType(): Optional = + requestContentType.getOptional("request_content_type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun responseContentType(): Optional = + responseContentType.getOptional("response_content_type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun responseMap(): Optional = responseMap.getOptional("response_map") + + /** + * Returns the raw JSON value of [authHeaderValueFormat]. + * + * Unlike [authHeaderValueFormat], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("auth_header_value_format") + @ExcludeMissing + fun _authHeaderValueFormat(): JsonField = authHeaderValueFormat + + /** + * Returns the raw JSON value of [authMethod]. + * + * Unlike [authMethod], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("auth_method") + @ExcludeMissing + fun _authMethod(): JsonField = authMethod + + /** + * 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 [expirationFormat]. + * + * Unlike [expirationFormat], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("expiration_format") + @ExcludeMissing + fun _expirationFormat(): JsonField = expirationFormat + + /** + * Returns the raw JSON value of [method]. + * + * Unlike [method], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("method") @ExcludeMissing fun _method(): JsonField = method + + /** + * Returns the raw JSON value of [params]. + * + * Unlike [params], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("params") @ExcludeMissing fun _params(): JsonField = params + + /** + * Returns the raw JSON value of [requestContentType]. + * + * Unlike [requestContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("request_content_type") + @ExcludeMissing + fun _requestContentType(): JsonField = requestContentType + + /** + * Returns the raw JSON value of [responseContentType]. + * + * Unlike [responseContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("response_content_type") + @ExcludeMissing + fun _responseContentType(): JsonField = responseContentType + + /** + * Returns the raw JSON value of [responseMap]. + * + * Unlike [responseMap], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("response_map") + @ExcludeMissing + fun _responseMap(): JsonField = responseMap + + @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 [AuthorizeRequest]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AuthorizeRequest]. */ + class Builder internal constructor() { + + private var authHeaderValueFormat: JsonField = JsonMissing.of() + private var authMethod: JsonField = JsonMissing.of() + private var endpoint: JsonField = JsonMissing.of() + private var expirationFormat: JsonField = JsonMissing.of() + private var method: JsonField = JsonMissing.of() + private var params: JsonField = JsonMissing.of() + private var requestContentType: JsonField = JsonMissing.of() + private var responseContentType: JsonField = JsonMissing.of() + private var responseMap: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(authorizeRequest: AuthorizeRequest) = apply { + authHeaderValueFormat = authorizeRequest.authHeaderValueFormat + authMethod = authorizeRequest.authMethod + endpoint = authorizeRequest.endpoint + expirationFormat = authorizeRequest.expirationFormat + method = authorizeRequest.method + params = authorizeRequest.params + requestContentType = authorizeRequest.requestContentType + responseContentType = authorizeRequest.responseContentType + responseMap = authorizeRequest.responseMap + additionalProperties = authorizeRequest.additionalProperties.toMutableMap() + } + + fun authHeaderValueFormat(authHeaderValueFormat: String) = + authHeaderValueFormat(JsonField.of(authHeaderValueFormat)) + + /** + * Sets [Builder.authHeaderValueFormat] to an arbitrary JSON value. + * + * You should usually call [Builder.authHeaderValueFormat] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun authHeaderValueFormat(authHeaderValueFormat: JsonField) = apply { + this.authHeaderValueFormat = authHeaderValueFormat + } + + fun authMethod(authMethod: String) = authMethod(JsonField.of(authMethod)) + + /** + * Sets [Builder.authMethod] to an arbitrary JSON value. + * + * You should usually call [Builder.authMethod] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun authMethod(authMethod: JsonField) = apply { + this.authMethod = authMethod + } + + 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 } + + fun expirationFormat(expirationFormat: String) = + expirationFormat(JsonField.of(expirationFormat)) + + /** + * Sets [Builder.expirationFormat] to an arbitrary JSON value. + * + * You should usually call [Builder.expirationFormat] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun expirationFormat(expirationFormat: JsonField) = apply { + this.expirationFormat = expirationFormat + } + + fun method(method: String) = method(JsonField.of(method)) + + /** + * Sets [Builder.method] to an arbitrary JSON value. + * + * You should usually call [Builder.method] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun method(method: JsonField) = apply { this.method = method } + + fun params(params: Params) = params(JsonField.of(params)) + + /** + * Sets [Builder.params] to an arbitrary JSON value. + * + * You should usually call [Builder.params] with a well-typed [Params] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun params(params: JsonField) = apply { this.params = params } + + fun requestContentType(requestContentType: String) = + requestContentType(JsonField.of(requestContentType)) + + /** + * Sets [Builder.requestContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.requestContentType] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun requestContentType(requestContentType: JsonField) = apply { + this.requestContentType = requestContentType + } + + fun responseContentType(responseContentType: String) = + responseContentType(JsonField.of(responseContentType)) + + /** + * Sets [Builder.responseContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.responseContentType] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun responseContentType(responseContentType: JsonField) = apply { + this.responseContentType = responseContentType + } + + fun responseMap(responseMap: ResponseMap) = responseMap(JsonField.of(responseMap)) + + /** + * Sets [Builder.responseMap] to an arbitrary JSON value. + * + * You should usually call [Builder.responseMap] with a well-typed [ResponseMap] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun responseMap(responseMap: JsonField) = apply { + this.responseMap = responseMap + } + + 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 [AuthorizeRequest]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): AuthorizeRequest = + AuthorizeRequest( + authHeaderValueFormat, + authMethod, + endpoint, + expirationFormat, + method, + params, + requestContentType, + responseContentType, + responseMap, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): AuthorizeRequest = apply { + if (validated) { + return@apply + } + + authHeaderValueFormat() + authMethod() + endpoint() + expirationFormat() + method() + params().ifPresent { it.validate() } + requestContentType() + responseContentType() + responseMap().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (authHeaderValueFormat.asKnown().isPresent) 1 else 0) + + (if (authMethod.asKnown().isPresent) 1 else 0) + + (if (endpoint.asKnown().isPresent) 1 else 0) + + (if (expirationFormat.asKnown().isPresent) 1 else 0) + + (if (method.asKnown().isPresent) 1 else 0) + + (params.asKnown().getOrNull()?.validity() ?: 0) + + (if (requestContentType.asKnown().isPresent) 1 else 0) + + (if (responseContentType.asKnown().isPresent) 1 else 0) + + (responseMap.asKnown().getOrNull()?.validity() ?: 0) + + class Params + @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 [Params]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Params]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(params: Params) = apply { + additionalProperties = params.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 [Params]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Params = Params(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Params = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 Params && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Params{additionalProperties=$additionalProperties}" + } + + class ResponseMap + @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 [ResponseMap]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ResponseMap]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(responseMap: ResponseMap) = apply { + additionalProperties = responseMap.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 [ResponseMap]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ResponseMap = ResponseMap(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ResponseMap = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 ResponseMap && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ResponseMap{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AuthorizeRequest && + authHeaderValueFormat == other.authHeaderValueFormat && + authMethod == other.authMethod && + endpoint == other.endpoint && + expirationFormat == other.expirationFormat && + method == other.method && + params == other.params && + requestContentType == other.requestContentType && + responseContentType == other.responseContentType && + responseMap == other.responseMap && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + authHeaderValueFormat, + authMethod, + endpoint, + expirationFormat, + method, + params, + requestContentType, + responseContentType, + responseMap, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AuthorizeRequest{authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, endpoint=$endpoint, expirationFormat=$expirationFormat, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, additionalProperties=$additionalProperties}" + } + + class ClientSecret + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val binding: JsonField, + private val editable: JsonField, + private val exists: JsonField, + private val value: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("binding") + @ExcludeMissing + binding: JsonField = JsonMissing.of(), + @JsonProperty("editable") + @ExcludeMissing + editable: JsonField = JsonMissing.of(), + @JsonProperty("exists") + @ExcludeMissing + exists: JsonField = JsonMissing.of(), + @JsonProperty("value") @ExcludeMissing value: JsonField = JsonMissing.of(), + ) : this(binding, editable, exists, value, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun binding(): Optional = binding.getOptional("binding") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun editable(): Optional = editable.getOptional("editable") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun exists(): Optional = exists.getOptional("exists") + + /** + * @throws ArcadeInvalidDataException 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 [binding]. + * + * Unlike [binding], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("binding") @ExcludeMissing fun _binding(): JsonField = binding + + /** + * Returns the raw JSON value of [editable]. + * + * Unlike [editable], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("editable") @ExcludeMissing fun _editable(): JsonField = editable + + /** + * Returns the raw JSON value of [exists]. + * + * Unlike [exists], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("exists") @ExcludeMissing fun _exists(): JsonField = exists + + /** + * 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 [ClientSecret]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ClientSecret]. */ + class Builder internal constructor() { + + private var binding: JsonField = JsonMissing.of() + private var editable: JsonField = JsonMissing.of() + private var exists: JsonField = JsonMissing.of() + private var value: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(clientSecret: ClientSecret) = apply { + binding = clientSecret.binding + editable = clientSecret.editable + exists = clientSecret.exists + value = clientSecret.value + additionalProperties = clientSecret.additionalProperties.toMutableMap() + } + + fun binding(binding: Binding) = binding(JsonField.of(binding)) + + /** + * Sets [Builder.binding] to an arbitrary JSON value. + * + * You should usually call [Builder.binding] with a well-typed [Binding] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun binding(binding: JsonField) = apply { this.binding = binding } + + fun editable(editable: Boolean) = editable(JsonField.of(editable)) + + /** + * Sets [Builder.editable] to an arbitrary JSON value. + * + * You should usually call [Builder.editable] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun editable(editable: JsonField) = apply { this.editable = editable } + + fun exists(exists: Boolean) = exists(JsonField.of(exists)) + + /** + * Sets [Builder.exists] to an arbitrary JSON value. + * + * You should usually call [Builder.exists] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun exists(exists: JsonField) = apply { this.exists = exists } + + 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 [ClientSecret]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ClientSecret = + ClientSecret( + binding, + editable, + exists, + value, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ClientSecret = apply { + if (validated) { + return@apply + } + + binding().ifPresent { it.validate() } + editable() + exists() + value() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (binding.asKnown().getOrNull()?.validity() ?: 0) + + (if (editable.asKnown().isPresent) 1 else 0) + + (if (exists.asKnown().isPresent) 1 else 0) + + (if (value.asKnown().isPresent) 1 else 0) + + class Binding @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 STATIC = of("static") + + @JvmField val TENANT = of("tenant") + + @JvmField val PROJECT = of("project") + + @JvmField val ACCOUNT = of("account") + + @JvmStatic fun of(value: String) = Binding(JsonField.of(value)) + } + + /** An enum containing [Binding]'s known values. */ + enum class Known { + STATIC, + TENANT, + PROJECT, + ACCOUNT, + } + + /** + * An enum containing [Binding]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Binding] 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 { + STATIC, + TENANT, + PROJECT, + ACCOUNT, + /** + * An enum member indicating that [Binding] 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) { + STATIC -> Value.STATIC + TENANT -> Value.TENANT + PROJECT -> Value.PROJECT + ACCOUNT -> Value.ACCOUNT + 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 ArcadeInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + STATIC -> Known.STATIC + TENANT -> Known.TENANT + PROJECT -> Known.PROJECT + ACCOUNT -> Known.ACCOUNT + else -> throw ArcadeInvalidDataException("Unknown Binding: $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 ArcadeInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ArcadeInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Binding = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 Binding && 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 ClientSecret && + binding == other.binding && + editable == other.editable && + exists == other.exists && + value == other.value && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(binding, editable, exists, value, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ClientSecret{binding=$binding, editable=$editable, exists=$exists, value=$value, additionalProperties=$additionalProperties}" + } + + class Pkce + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val codeChallengeMethod: JsonField, + private val enabled: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("code_challenge_method") + @ExcludeMissing + codeChallengeMethod: JsonField = JsonMissing.of(), + @JsonProperty("enabled") + @ExcludeMissing + enabled: JsonField = JsonMissing.of(), + ) : this(codeChallengeMethod, enabled, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun codeChallengeMethod(): Optional = + codeChallengeMethod.getOptional("code_challenge_method") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun enabled(): Optional = enabled.getOptional("enabled") + + /** + * Returns the raw JSON value of [codeChallengeMethod]. + * + * Unlike [codeChallengeMethod], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("code_challenge_method") + @ExcludeMissing + fun _codeChallengeMethod(): JsonField = codeChallengeMethod + + /** + * Returns the raw JSON value of [enabled]. + * + * Unlike [enabled], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("enabled") @ExcludeMissing fun _enabled(): JsonField = enabled + + @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 [Pkce]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Pkce]. */ + class Builder internal constructor() { + + private var codeChallengeMethod: JsonField = JsonMissing.of() + private var enabled: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(pkce: Pkce) = apply { + codeChallengeMethod = pkce.codeChallengeMethod + enabled = pkce.enabled + additionalProperties = pkce.additionalProperties.toMutableMap() + } + + fun codeChallengeMethod(codeChallengeMethod: String) = + codeChallengeMethod(JsonField.of(codeChallengeMethod)) + + /** + * Sets [Builder.codeChallengeMethod] to an arbitrary JSON value. + * + * You should usually call [Builder.codeChallengeMethod] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun codeChallengeMethod(codeChallengeMethod: JsonField) = apply { + this.codeChallengeMethod = codeChallengeMethod + } + + fun enabled(enabled: Boolean) = enabled(JsonField.of(enabled)) + + /** + * Sets [Builder.enabled] to an arbitrary JSON value. + * + * You should usually call [Builder.enabled] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun enabled(enabled: JsonField) = apply { this.enabled = enabled } + + 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 [Pkce]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Pkce = + Pkce(codeChallengeMethod, enabled, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Pkce = apply { + if (validated) { + return@apply + } + + codeChallengeMethod() + enabled() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (codeChallengeMethod.asKnown().isPresent) 1 else 0) + + (if (enabled.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Pkce && + codeChallengeMethod == other.codeChallengeMethod && + enabled == other.enabled && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(codeChallengeMethod, enabled, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Pkce{codeChallengeMethod=$codeChallengeMethod, enabled=$enabled, additionalProperties=$additionalProperties}" + } + + class RefreshRequest + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val authHeaderValueFormat: JsonField, + private val authMethod: JsonField, + private val endpoint: JsonField, + private val expirationFormat: JsonField, + private val method: JsonField, + private val params: JsonField, + private val requestContentType: JsonField, + private val responseContentType: JsonField, + private val responseMap: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("auth_header_value_format") + @ExcludeMissing + authHeaderValueFormat: JsonField = JsonMissing.of(), + @JsonProperty("auth_method") + @ExcludeMissing + authMethod: JsonField = JsonMissing.of(), + @JsonProperty("endpoint") + @ExcludeMissing + endpoint: JsonField = JsonMissing.of(), + @JsonProperty("expiration_format") + @ExcludeMissing + expirationFormat: JsonField = JsonMissing.of(), + @JsonProperty("method") + @ExcludeMissing + method: JsonField = JsonMissing.of(), + @JsonProperty("params") + @ExcludeMissing + params: JsonField = JsonMissing.of(), + @JsonProperty("request_content_type") + @ExcludeMissing + requestContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_content_type") + @ExcludeMissing + responseContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_map") + @ExcludeMissing + responseMap: JsonField = JsonMissing.of(), + ) : this( + authHeaderValueFormat, + authMethod, + endpoint, + expirationFormat, + method, + params, + requestContentType, + responseContentType, + responseMap, + mutableMapOf(), + ) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authHeaderValueFormat(): Optional = + authHeaderValueFormat.getOptional("auth_header_value_format") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authMethod(): Optional = authMethod.getOptional("auth_method") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun endpoint(): Optional = endpoint.getOptional("endpoint") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun expirationFormat(): Optional = + expirationFormat.getOptional("expiration_format") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun method(): Optional = method.getOptional("method") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun params(): Optional = params.getOptional("params") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun requestContentType(): Optional = + requestContentType.getOptional("request_content_type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun responseContentType(): Optional = + responseContentType.getOptional("response_content_type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun responseMap(): Optional = responseMap.getOptional("response_map") + + /** + * Returns the raw JSON value of [authHeaderValueFormat]. + * + * Unlike [authHeaderValueFormat], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("auth_header_value_format") + @ExcludeMissing + fun _authHeaderValueFormat(): JsonField = authHeaderValueFormat + + /** + * Returns the raw JSON value of [authMethod]. + * + * Unlike [authMethod], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("auth_method") + @ExcludeMissing + fun _authMethod(): JsonField = authMethod + + /** + * 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 [expirationFormat]. + * + * Unlike [expirationFormat], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("expiration_format") + @ExcludeMissing + fun _expirationFormat(): JsonField = expirationFormat + + /** + * Returns the raw JSON value of [method]. + * + * Unlike [method], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("method") @ExcludeMissing fun _method(): JsonField = method + + /** + * Returns the raw JSON value of [params]. + * + * Unlike [params], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("params") @ExcludeMissing fun _params(): JsonField = params + + /** + * Returns the raw JSON value of [requestContentType]. + * + * Unlike [requestContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("request_content_type") + @ExcludeMissing + fun _requestContentType(): JsonField = requestContentType + + /** + * Returns the raw JSON value of [responseContentType]. + * + * Unlike [responseContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("response_content_type") + @ExcludeMissing + fun _responseContentType(): JsonField = responseContentType + + /** + * Returns the raw JSON value of [responseMap]. + * + * Unlike [responseMap], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("response_map") + @ExcludeMissing + fun _responseMap(): JsonField = responseMap + + @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 [RefreshRequest]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RefreshRequest]. */ + class Builder internal constructor() { + + private var authHeaderValueFormat: JsonField = JsonMissing.of() + private var authMethod: JsonField = JsonMissing.of() + private var endpoint: JsonField = JsonMissing.of() + private var expirationFormat: JsonField = JsonMissing.of() + private var method: JsonField = JsonMissing.of() + private var params: JsonField = JsonMissing.of() + private var requestContentType: JsonField = JsonMissing.of() + private var responseContentType: JsonField = JsonMissing.of() + private var responseMap: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(refreshRequest: RefreshRequest) = apply { + authHeaderValueFormat = refreshRequest.authHeaderValueFormat + authMethod = refreshRequest.authMethod + endpoint = refreshRequest.endpoint + expirationFormat = refreshRequest.expirationFormat + method = refreshRequest.method + params = refreshRequest.params + requestContentType = refreshRequest.requestContentType + responseContentType = refreshRequest.responseContentType + responseMap = refreshRequest.responseMap + additionalProperties = refreshRequest.additionalProperties.toMutableMap() + } + + fun authHeaderValueFormat(authHeaderValueFormat: String) = + authHeaderValueFormat(JsonField.of(authHeaderValueFormat)) + + /** + * Sets [Builder.authHeaderValueFormat] to an arbitrary JSON value. + * + * You should usually call [Builder.authHeaderValueFormat] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun authHeaderValueFormat(authHeaderValueFormat: JsonField) = apply { + this.authHeaderValueFormat = authHeaderValueFormat + } + + fun authMethod(authMethod: String) = authMethod(JsonField.of(authMethod)) + + /** + * Sets [Builder.authMethod] to an arbitrary JSON value. + * + * You should usually call [Builder.authMethod] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun authMethod(authMethod: JsonField) = apply { + this.authMethod = authMethod + } + + 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 } + + fun expirationFormat(expirationFormat: String) = + expirationFormat(JsonField.of(expirationFormat)) + + /** + * Sets [Builder.expirationFormat] to an arbitrary JSON value. + * + * You should usually call [Builder.expirationFormat] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun expirationFormat(expirationFormat: JsonField) = apply { + this.expirationFormat = expirationFormat + } + + fun method(method: String) = method(JsonField.of(method)) + + /** + * Sets [Builder.method] to an arbitrary JSON value. + * + * You should usually call [Builder.method] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun method(method: JsonField) = apply { this.method = method } + + fun params(params: Params) = params(JsonField.of(params)) + + /** + * Sets [Builder.params] to an arbitrary JSON value. + * + * You should usually call [Builder.params] with a well-typed [Params] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun params(params: JsonField) = apply { this.params = params } + + fun requestContentType(requestContentType: String) = + requestContentType(JsonField.of(requestContentType)) + + /** + * Sets [Builder.requestContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.requestContentType] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun requestContentType(requestContentType: JsonField) = apply { + this.requestContentType = requestContentType + } + + fun responseContentType(responseContentType: String) = + responseContentType(JsonField.of(responseContentType)) + + /** + * Sets [Builder.responseContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.responseContentType] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun responseContentType(responseContentType: JsonField) = apply { + this.responseContentType = responseContentType + } + + fun responseMap(responseMap: ResponseMap) = responseMap(JsonField.of(responseMap)) + + /** + * Sets [Builder.responseMap] to an arbitrary JSON value. + * + * You should usually call [Builder.responseMap] with a well-typed [ResponseMap] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun responseMap(responseMap: JsonField) = apply { + this.responseMap = responseMap + } + + 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 [RefreshRequest]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): RefreshRequest = + RefreshRequest( + authHeaderValueFormat, + authMethod, + endpoint, + expirationFormat, + method, + params, + requestContentType, + responseContentType, + responseMap, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): RefreshRequest = apply { + if (validated) { + return@apply + } + + authHeaderValueFormat() + authMethod() + endpoint() + expirationFormat() + method() + params().ifPresent { it.validate() } + requestContentType() + responseContentType() + responseMap().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (authHeaderValueFormat.asKnown().isPresent) 1 else 0) + + (if (authMethod.asKnown().isPresent) 1 else 0) + + (if (endpoint.asKnown().isPresent) 1 else 0) + + (if (expirationFormat.asKnown().isPresent) 1 else 0) + + (if (method.asKnown().isPresent) 1 else 0) + + (params.asKnown().getOrNull()?.validity() ?: 0) + + (if (requestContentType.asKnown().isPresent) 1 else 0) + + (if (responseContentType.asKnown().isPresent) 1 else 0) + + (responseMap.asKnown().getOrNull()?.validity() ?: 0) + + class Params + @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 [Params]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Params]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(params: Params) = apply { + additionalProperties = params.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 [Params]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Params = Params(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Params = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 Params && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Params{additionalProperties=$additionalProperties}" + } + + class ResponseMap + @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 [ResponseMap]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ResponseMap]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(responseMap: ResponseMap) = apply { + additionalProperties = responseMap.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 [ResponseMap]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ResponseMap = ResponseMap(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ResponseMap = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 ResponseMap && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ResponseMap{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RefreshRequest && + authHeaderValueFormat == other.authHeaderValueFormat && + authMethod == other.authMethod && + endpoint == other.endpoint && + expirationFormat == other.expirationFormat && + method == other.method && + params == other.params && + requestContentType == other.requestContentType && + responseContentType == other.responseContentType && + responseMap == other.responseMap && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + authHeaderValueFormat, + authMethod, + endpoint, + expirationFormat, + method, + params, + requestContentType, + responseContentType, + responseMap, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RefreshRequest{authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, endpoint=$endpoint, expirationFormat=$expirationFormat, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, additionalProperties=$additionalProperties}" + } + + class TokenIntrospectionRequest + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val authHeaderValueFormat: JsonField, + private val authMethod: JsonField, + private val enabled: JsonField, + private val endpoint: JsonField, + private val expirationFormat: JsonField, + private val method: JsonField, + private val params: JsonField, + private val requestContentType: JsonField, + private val responseContentType: JsonField, + private val responseMap: JsonField, + private val triggers: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("auth_header_value_format") + @ExcludeMissing + authHeaderValueFormat: JsonField = JsonMissing.of(), + @JsonProperty("auth_method") + @ExcludeMissing + authMethod: JsonField = JsonMissing.of(), + @JsonProperty("enabled") + @ExcludeMissing + enabled: JsonField = JsonMissing.of(), + @JsonProperty("endpoint") + @ExcludeMissing + endpoint: JsonField = JsonMissing.of(), + @JsonProperty("expiration_format") + @ExcludeMissing + expirationFormat: JsonField = JsonMissing.of(), + @JsonProperty("method") + @ExcludeMissing + method: JsonField = JsonMissing.of(), + @JsonProperty("params") + @ExcludeMissing + params: JsonField = JsonMissing.of(), + @JsonProperty("request_content_type") + @ExcludeMissing + requestContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_content_type") + @ExcludeMissing + responseContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_map") + @ExcludeMissing + responseMap: JsonField = JsonMissing.of(), + @JsonProperty("triggers") + @ExcludeMissing + triggers: JsonField = JsonMissing.of(), + ) : this( + authHeaderValueFormat, + authMethod, + enabled, + endpoint, + expirationFormat, + method, + params, + requestContentType, + responseContentType, + responseMap, + triggers, + mutableMapOf(), + ) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authHeaderValueFormat(): Optional = + authHeaderValueFormat.getOptional("auth_header_value_format") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authMethod(): Optional = authMethod.getOptional("auth_method") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun enabled(): Optional = enabled.getOptional("enabled") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun endpoint(): Optional = endpoint.getOptional("endpoint") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun expirationFormat(): Optional = + expirationFormat.getOptional("expiration_format") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun method(): Optional = method.getOptional("method") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun params(): Optional = params.getOptional("params") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun requestContentType(): Optional = + requestContentType.getOptional("request_content_type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun responseContentType(): Optional = + responseContentType.getOptional("response_content_type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun responseMap(): Optional = responseMap.getOptional("response_map") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun triggers(): Optional = triggers.getOptional("triggers") + + /** + * Returns the raw JSON value of [authHeaderValueFormat]. + * + * Unlike [authHeaderValueFormat], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("auth_header_value_format") + @ExcludeMissing + fun _authHeaderValueFormat(): JsonField = authHeaderValueFormat + + /** + * Returns the raw JSON value of [authMethod]. + * + * Unlike [authMethod], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("auth_method") + @ExcludeMissing + fun _authMethod(): JsonField = authMethod + + /** + * Returns the raw JSON value of [enabled]. + * + * Unlike [enabled], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("enabled") @ExcludeMissing fun _enabled(): JsonField = enabled + + /** + * 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 [expirationFormat]. + * + * Unlike [expirationFormat], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("expiration_format") + @ExcludeMissing + fun _expirationFormat(): JsonField = expirationFormat + + /** + * Returns the raw JSON value of [method]. + * + * Unlike [method], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("method") @ExcludeMissing fun _method(): JsonField = method + + /** + * Returns the raw JSON value of [params]. + * + * Unlike [params], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("params") @ExcludeMissing fun _params(): JsonField = params + + /** + * Returns the raw JSON value of [requestContentType]. + * + * Unlike [requestContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("request_content_type") + @ExcludeMissing + fun _requestContentType(): JsonField = requestContentType + + /** + * Returns the raw JSON value of [responseContentType]. + * + * Unlike [responseContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("response_content_type") + @ExcludeMissing + fun _responseContentType(): JsonField = responseContentType + + /** + * Returns the raw JSON value of [responseMap]. + * + * Unlike [responseMap], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("response_map") + @ExcludeMissing + fun _responseMap(): JsonField = responseMap + + /** + * Returns the raw JSON value of [triggers]. + * + * Unlike [triggers], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("triggers") + @ExcludeMissing + fun _triggers(): JsonField = triggers + + @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 + * [TokenIntrospectionRequest]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [TokenIntrospectionRequest]. */ + class Builder internal constructor() { + + private var authHeaderValueFormat: JsonField = JsonMissing.of() + private var authMethod: JsonField = JsonMissing.of() + private var enabled: JsonField = JsonMissing.of() + private var endpoint: JsonField = JsonMissing.of() + private var expirationFormat: JsonField = JsonMissing.of() + private var method: JsonField = JsonMissing.of() + private var params: JsonField = JsonMissing.of() + private var requestContentType: JsonField = JsonMissing.of() + private var responseContentType: JsonField = JsonMissing.of() + private var responseMap: JsonField = JsonMissing.of() + private var triggers: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(tokenIntrospectionRequest: TokenIntrospectionRequest) = apply { + authHeaderValueFormat = tokenIntrospectionRequest.authHeaderValueFormat + authMethod = tokenIntrospectionRequest.authMethod + enabled = tokenIntrospectionRequest.enabled + endpoint = tokenIntrospectionRequest.endpoint + expirationFormat = tokenIntrospectionRequest.expirationFormat + method = tokenIntrospectionRequest.method + params = tokenIntrospectionRequest.params + requestContentType = tokenIntrospectionRequest.requestContentType + responseContentType = tokenIntrospectionRequest.responseContentType + responseMap = tokenIntrospectionRequest.responseMap + triggers = tokenIntrospectionRequest.triggers + additionalProperties = + tokenIntrospectionRequest.additionalProperties.toMutableMap() + } + + fun authHeaderValueFormat(authHeaderValueFormat: String) = + authHeaderValueFormat(JsonField.of(authHeaderValueFormat)) + + /** + * Sets [Builder.authHeaderValueFormat] to an arbitrary JSON value. + * + * You should usually call [Builder.authHeaderValueFormat] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun authHeaderValueFormat(authHeaderValueFormat: JsonField) = apply { + this.authHeaderValueFormat = authHeaderValueFormat + } + + fun authMethod(authMethod: String) = authMethod(JsonField.of(authMethod)) + + /** + * Sets [Builder.authMethod] to an arbitrary JSON value. + * + * You should usually call [Builder.authMethod] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun authMethod(authMethod: JsonField) = apply { + this.authMethod = authMethod + } + + fun enabled(enabled: Boolean) = enabled(JsonField.of(enabled)) + + /** + * Sets [Builder.enabled] to an arbitrary JSON value. + * + * You should usually call [Builder.enabled] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun enabled(enabled: JsonField) = apply { this.enabled = enabled } + + 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 } + + fun expirationFormat(expirationFormat: String) = + expirationFormat(JsonField.of(expirationFormat)) + + /** + * Sets [Builder.expirationFormat] to an arbitrary JSON value. + * + * You should usually call [Builder.expirationFormat] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun expirationFormat(expirationFormat: JsonField) = apply { + this.expirationFormat = expirationFormat + } + + fun method(method: String) = method(JsonField.of(method)) + + /** + * Sets [Builder.method] to an arbitrary JSON value. + * + * You should usually call [Builder.method] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun method(method: JsonField) = apply { this.method = method } + + fun params(params: Params) = params(JsonField.of(params)) + + /** + * Sets [Builder.params] to an arbitrary JSON value. + * + * You should usually call [Builder.params] with a well-typed [Params] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun params(params: JsonField) = apply { this.params = params } + + fun requestContentType(requestContentType: String) = + requestContentType(JsonField.of(requestContentType)) + + /** + * Sets [Builder.requestContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.requestContentType] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun requestContentType(requestContentType: JsonField) = apply { + this.requestContentType = requestContentType + } + + fun responseContentType(responseContentType: String) = + responseContentType(JsonField.of(responseContentType)) + + /** + * Sets [Builder.responseContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.responseContentType] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun responseContentType(responseContentType: JsonField) = apply { + this.responseContentType = responseContentType + } + + fun responseMap(responseMap: ResponseMap) = responseMap(JsonField.of(responseMap)) + + /** + * Sets [Builder.responseMap] to an arbitrary JSON value. + * + * You should usually call [Builder.responseMap] with a well-typed [ResponseMap] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun responseMap(responseMap: JsonField) = apply { + this.responseMap = responseMap + } + + fun triggers(triggers: Triggers) = triggers(JsonField.of(triggers)) + + /** + * Sets [Builder.triggers] to an arbitrary JSON value. + * + * You should usually call [Builder.triggers] with a well-typed [Triggers] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun triggers(triggers: JsonField) = apply { this.triggers = triggers } + + 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 [TokenIntrospectionRequest]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): TokenIntrospectionRequest = + TokenIntrospectionRequest( + authHeaderValueFormat, + authMethod, + enabled, + endpoint, + expirationFormat, + method, + params, + requestContentType, + responseContentType, + responseMap, + triggers, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): TokenIntrospectionRequest = apply { + if (validated) { + return@apply + } + + authHeaderValueFormat() + authMethod() + enabled() + endpoint() + expirationFormat() + method() + params().ifPresent { it.validate() } + requestContentType() + responseContentType() + responseMap().ifPresent { it.validate() } + triggers().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (authHeaderValueFormat.asKnown().isPresent) 1 else 0) + + (if (authMethod.asKnown().isPresent) 1 else 0) + + (if (enabled.asKnown().isPresent) 1 else 0) + + (if (endpoint.asKnown().isPresent) 1 else 0) + + (if (expirationFormat.asKnown().isPresent) 1 else 0) + + (if (method.asKnown().isPresent) 1 else 0) + + (params.asKnown().getOrNull()?.validity() ?: 0) + + (if (requestContentType.asKnown().isPresent) 1 else 0) + + (if (responseContentType.asKnown().isPresent) 1 else 0) + + (responseMap.asKnown().getOrNull()?.validity() ?: 0) + + (triggers.asKnown().getOrNull()?.validity() ?: 0) + + class Params + @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 [Params]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Params]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(params: Params) = apply { + additionalProperties = params.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 [Params]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Params = Params(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Params = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 Params && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Params{additionalProperties=$additionalProperties}" + } + + class ResponseMap + @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 [ResponseMap]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ResponseMap]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(responseMap: ResponseMap) = apply { + additionalProperties = responseMap.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 [ResponseMap]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ResponseMap = ResponseMap(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ResponseMap = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 ResponseMap && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ResponseMap{additionalProperties=$additionalProperties}" + } + + class Triggers + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val onTokenGrant: JsonField, + private val onTokenRefresh: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("on_token_grant") + @ExcludeMissing + onTokenGrant: JsonField = JsonMissing.of(), + @JsonProperty("on_token_refresh") + @ExcludeMissing + onTokenRefresh: JsonField = JsonMissing.of(), + ) : this(onTokenGrant, onTokenRefresh, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun onTokenGrant(): Optional = onTokenGrant.getOptional("on_token_grant") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun onTokenRefresh(): Optional = + onTokenRefresh.getOptional("on_token_refresh") + + /** + * Returns the raw JSON value of [onTokenGrant]. + * + * Unlike [onTokenGrant], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("on_token_grant") + @ExcludeMissing + fun _onTokenGrant(): JsonField = onTokenGrant + + /** + * Returns the raw JSON value of [onTokenRefresh]. + * + * Unlike [onTokenRefresh], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("on_token_refresh") + @ExcludeMissing + fun _onTokenRefresh(): JsonField = onTokenRefresh + + @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 [Triggers]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Triggers]. */ + class Builder internal constructor() { + + private var onTokenGrant: JsonField = JsonMissing.of() + private var onTokenRefresh: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(triggers: Triggers) = apply { + onTokenGrant = triggers.onTokenGrant + onTokenRefresh = triggers.onTokenRefresh + additionalProperties = triggers.additionalProperties.toMutableMap() + } + + fun onTokenGrant(onTokenGrant: Boolean) = + onTokenGrant(JsonField.of(onTokenGrant)) + + /** + * Sets [Builder.onTokenGrant] to an arbitrary JSON value. + * + * You should usually call [Builder.onTokenGrant] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun onTokenGrant(onTokenGrant: JsonField) = apply { + this.onTokenGrant = onTokenGrant + } + + fun onTokenRefresh(onTokenRefresh: Boolean) = + onTokenRefresh(JsonField.of(onTokenRefresh)) + + /** + * Sets [Builder.onTokenRefresh] to an arbitrary JSON value. + * + * You should usually call [Builder.onTokenRefresh] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun onTokenRefresh(onTokenRefresh: JsonField) = apply { + this.onTokenRefresh = onTokenRefresh + } + + 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 [Triggers]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Triggers = + Triggers(onTokenGrant, onTokenRefresh, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Triggers = apply { + if (validated) { + return@apply + } + + onTokenGrant() + onTokenRefresh() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (onTokenGrant.asKnown().isPresent) 1 else 0) + + (if (onTokenRefresh.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Triggers && + onTokenGrant == other.onTokenGrant && + onTokenRefresh == other.onTokenRefresh && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(onTokenGrant, onTokenRefresh, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Triggers{onTokenGrant=$onTokenGrant, onTokenRefresh=$onTokenRefresh, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is TokenIntrospectionRequest && + authHeaderValueFormat == other.authHeaderValueFormat && + authMethod == other.authMethod && + enabled == other.enabled && + endpoint == other.endpoint && + expirationFormat == other.expirationFormat && + method == other.method && + params == other.params && + requestContentType == other.requestContentType && + responseContentType == other.responseContentType && + responseMap == other.responseMap && + triggers == other.triggers && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + authHeaderValueFormat, + authMethod, + enabled, + endpoint, + expirationFormat, + method, + params, + requestContentType, + responseContentType, + responseMap, + triggers, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "TokenIntrospectionRequest{authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, enabled=$enabled, endpoint=$endpoint, expirationFormat=$expirationFormat, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, triggers=$triggers, additionalProperties=$additionalProperties}" + } + + class TokenRequest + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val authHeaderValueFormat: JsonField, + private val authMethod: JsonField, + private val endpoint: JsonField, + private val expirationFormat: JsonField, + private val method: JsonField, + private val params: JsonField, + private val requestContentType: JsonField, + private val responseContentType: JsonField, + private val responseMap: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("auth_header_value_format") + @ExcludeMissing + authHeaderValueFormat: JsonField = JsonMissing.of(), + @JsonProperty("auth_method") + @ExcludeMissing + authMethod: JsonField = JsonMissing.of(), + @JsonProperty("endpoint") + @ExcludeMissing + endpoint: JsonField = JsonMissing.of(), + @JsonProperty("expiration_format") + @ExcludeMissing + expirationFormat: JsonField = JsonMissing.of(), + @JsonProperty("method") + @ExcludeMissing + method: JsonField = JsonMissing.of(), + @JsonProperty("params") + @ExcludeMissing + params: JsonField = JsonMissing.of(), + @JsonProperty("request_content_type") + @ExcludeMissing + requestContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_content_type") + @ExcludeMissing + responseContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_map") + @ExcludeMissing + responseMap: JsonField = JsonMissing.of(), + ) : this( + authHeaderValueFormat, + authMethod, + endpoint, + expirationFormat, + method, + params, + requestContentType, + responseContentType, + responseMap, + mutableMapOf(), + ) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authHeaderValueFormat(): Optional = + authHeaderValueFormat.getOptional("auth_header_value_format") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authMethod(): Optional = authMethod.getOptional("auth_method") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun endpoint(): Optional = endpoint.getOptional("endpoint") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun expirationFormat(): Optional = + expirationFormat.getOptional("expiration_format") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun method(): Optional = method.getOptional("method") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun params(): Optional = params.getOptional("params") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun requestContentType(): Optional = + requestContentType.getOptional("request_content_type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun responseContentType(): Optional = + responseContentType.getOptional("response_content_type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun responseMap(): Optional = responseMap.getOptional("response_map") + + /** + * Returns the raw JSON value of [authHeaderValueFormat]. + * + * Unlike [authHeaderValueFormat], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("auth_header_value_format") + @ExcludeMissing + fun _authHeaderValueFormat(): JsonField = authHeaderValueFormat + + /** + * Returns the raw JSON value of [authMethod]. + * + * Unlike [authMethod], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("auth_method") + @ExcludeMissing + fun _authMethod(): JsonField = authMethod + + /** + * 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 [expirationFormat]. + * + * Unlike [expirationFormat], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("expiration_format") + @ExcludeMissing + fun _expirationFormat(): JsonField = expirationFormat + + /** + * Returns the raw JSON value of [method]. + * + * Unlike [method], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("method") @ExcludeMissing fun _method(): JsonField = method + + /** + * Returns the raw JSON value of [params]. + * + * Unlike [params], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("params") @ExcludeMissing fun _params(): JsonField = params + + /** + * Returns the raw JSON value of [requestContentType]. + * + * Unlike [requestContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("request_content_type") + @ExcludeMissing + fun _requestContentType(): JsonField = requestContentType + + /** + * Returns the raw JSON value of [responseContentType]. + * + * Unlike [responseContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("response_content_type") + @ExcludeMissing + fun _responseContentType(): JsonField = responseContentType + + /** + * Returns the raw JSON value of [responseMap]. + * + * Unlike [responseMap], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("response_map") + @ExcludeMissing + fun _responseMap(): JsonField = responseMap + + @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 [TokenRequest]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [TokenRequest]. */ + class Builder internal constructor() { + + private var authHeaderValueFormat: JsonField = JsonMissing.of() + private var authMethod: JsonField = JsonMissing.of() + private var endpoint: JsonField = JsonMissing.of() + private var expirationFormat: JsonField = JsonMissing.of() + private var method: JsonField = JsonMissing.of() + private var params: JsonField = JsonMissing.of() + private var requestContentType: JsonField = JsonMissing.of() + private var responseContentType: JsonField = JsonMissing.of() + private var responseMap: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(tokenRequest: TokenRequest) = apply { + authHeaderValueFormat = tokenRequest.authHeaderValueFormat + authMethod = tokenRequest.authMethod + endpoint = tokenRequest.endpoint + expirationFormat = tokenRequest.expirationFormat + method = tokenRequest.method + params = tokenRequest.params + requestContentType = tokenRequest.requestContentType + responseContentType = tokenRequest.responseContentType + responseMap = tokenRequest.responseMap + additionalProperties = tokenRequest.additionalProperties.toMutableMap() + } + + fun authHeaderValueFormat(authHeaderValueFormat: String) = + authHeaderValueFormat(JsonField.of(authHeaderValueFormat)) + + /** + * Sets [Builder.authHeaderValueFormat] to an arbitrary JSON value. + * + * You should usually call [Builder.authHeaderValueFormat] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun authHeaderValueFormat(authHeaderValueFormat: JsonField) = apply { + this.authHeaderValueFormat = authHeaderValueFormat + } + + fun authMethod(authMethod: String) = authMethod(JsonField.of(authMethod)) + + /** + * Sets [Builder.authMethod] to an arbitrary JSON value. + * + * You should usually call [Builder.authMethod] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun authMethod(authMethod: JsonField) = apply { + this.authMethod = authMethod + } + + 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 } + + fun expirationFormat(expirationFormat: String) = + expirationFormat(JsonField.of(expirationFormat)) + + /** + * Sets [Builder.expirationFormat] to an arbitrary JSON value. + * + * You should usually call [Builder.expirationFormat] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun expirationFormat(expirationFormat: JsonField) = apply { + this.expirationFormat = expirationFormat + } + + fun method(method: String) = method(JsonField.of(method)) + + /** + * Sets [Builder.method] to an arbitrary JSON value. + * + * You should usually call [Builder.method] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun method(method: JsonField) = apply { this.method = method } + + fun params(params: Params) = params(JsonField.of(params)) + + /** + * Sets [Builder.params] to an arbitrary JSON value. + * + * You should usually call [Builder.params] with a well-typed [Params] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun params(params: JsonField) = apply { this.params = params } + + fun requestContentType(requestContentType: String) = + requestContentType(JsonField.of(requestContentType)) + + /** + * Sets [Builder.requestContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.requestContentType] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun requestContentType(requestContentType: JsonField) = apply { + this.requestContentType = requestContentType + } + + fun responseContentType(responseContentType: String) = + responseContentType(JsonField.of(responseContentType)) + + /** + * Sets [Builder.responseContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.responseContentType] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun responseContentType(responseContentType: JsonField) = apply { + this.responseContentType = responseContentType + } + + fun responseMap(responseMap: ResponseMap) = responseMap(JsonField.of(responseMap)) + + /** + * Sets [Builder.responseMap] to an arbitrary JSON value. + * + * You should usually call [Builder.responseMap] with a well-typed [ResponseMap] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun responseMap(responseMap: JsonField) = apply { + this.responseMap = responseMap + } + + 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 [TokenRequest]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): TokenRequest = + TokenRequest( + authHeaderValueFormat, + authMethod, + endpoint, + expirationFormat, + method, + params, + requestContentType, + responseContentType, + responseMap, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): TokenRequest = apply { + if (validated) { + return@apply + } + + authHeaderValueFormat() + authMethod() + endpoint() + expirationFormat() + method() + params().ifPresent { it.validate() } + requestContentType() + responseContentType() + responseMap().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (authHeaderValueFormat.asKnown().isPresent) 1 else 0) + + (if (authMethod.asKnown().isPresent) 1 else 0) + + (if (endpoint.asKnown().isPresent) 1 else 0) + + (if (expirationFormat.asKnown().isPresent) 1 else 0) + + (if (method.asKnown().isPresent) 1 else 0) + + (params.asKnown().getOrNull()?.validity() ?: 0) + + (if (requestContentType.asKnown().isPresent) 1 else 0) + + (if (responseContentType.asKnown().isPresent) 1 else 0) + + (responseMap.asKnown().getOrNull()?.validity() ?: 0) + + class Params + @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 [Params]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Params]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(params: Params) = apply { + additionalProperties = params.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 [Params]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Params = Params(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Params = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 Params && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Params{additionalProperties=$additionalProperties}" + } + + class ResponseMap + @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 [ResponseMap]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ResponseMap]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(responseMap: ResponseMap) = apply { + additionalProperties = responseMap.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 [ResponseMap]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ResponseMap = ResponseMap(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ResponseMap = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 ResponseMap && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ResponseMap{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is TokenRequest && + authHeaderValueFormat == other.authHeaderValueFormat && + authMethod == other.authMethod && + endpoint == other.endpoint && + expirationFormat == other.expirationFormat && + method == other.method && + params == other.params && + requestContentType == other.requestContentType && + responseContentType == other.responseContentType && + responseMap == other.responseMap && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + authHeaderValueFormat, + authMethod, + endpoint, + expirationFormat, + method, + params, + requestContentType, + responseContentType, + responseMap, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "TokenRequest{authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, endpoint=$endpoint, expirationFormat=$expirationFormat, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, additionalProperties=$additionalProperties}" + } + + class UserInfoRequest + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val authHeaderValueFormat: JsonField, + private val authMethod: JsonField, + private val endpoint: JsonField, + private val expirationFormat: JsonField, + private val method: JsonField, + private val params: JsonField, + private val requestContentType: JsonField, + private val responseContentType: JsonField, + private val responseMap: JsonField, + private val triggers: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("auth_header_value_format") + @ExcludeMissing + authHeaderValueFormat: JsonField = JsonMissing.of(), + @JsonProperty("auth_method") + @ExcludeMissing + authMethod: JsonField = JsonMissing.of(), + @JsonProperty("endpoint") + @ExcludeMissing + endpoint: JsonField = JsonMissing.of(), + @JsonProperty("expiration_format") + @ExcludeMissing + expirationFormat: JsonField = JsonMissing.of(), + @JsonProperty("method") + @ExcludeMissing + method: JsonField = JsonMissing.of(), + @JsonProperty("params") + @ExcludeMissing + params: JsonField = JsonMissing.of(), + @JsonProperty("request_content_type") + @ExcludeMissing + requestContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_content_type") + @ExcludeMissing + responseContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_map") + @ExcludeMissing + responseMap: JsonField = JsonMissing.of(), + @JsonProperty("triggers") + @ExcludeMissing + triggers: JsonField = JsonMissing.of(), + ) : this( + authHeaderValueFormat, + authMethod, + endpoint, + expirationFormat, + method, + params, + requestContentType, + responseContentType, + responseMap, + triggers, + mutableMapOf(), + ) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authHeaderValueFormat(): Optional = + authHeaderValueFormat.getOptional("auth_header_value_format") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authMethod(): Optional = authMethod.getOptional("auth_method") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun endpoint(): Optional = endpoint.getOptional("endpoint") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun expirationFormat(): Optional = + expirationFormat.getOptional("expiration_format") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun method(): Optional = method.getOptional("method") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun params(): Optional = params.getOptional("params") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun requestContentType(): Optional = + requestContentType.getOptional("request_content_type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun responseContentType(): Optional = + responseContentType.getOptional("response_content_type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun responseMap(): Optional = responseMap.getOptional("response_map") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun triggers(): Optional = triggers.getOptional("triggers") + + /** + * Returns the raw JSON value of [authHeaderValueFormat]. + * + * Unlike [authHeaderValueFormat], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("auth_header_value_format") + @ExcludeMissing + fun _authHeaderValueFormat(): JsonField = authHeaderValueFormat + + /** + * Returns the raw JSON value of [authMethod]. + * + * Unlike [authMethod], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("auth_method") + @ExcludeMissing + fun _authMethod(): JsonField = authMethod + + /** + * 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 [expirationFormat]. + * + * Unlike [expirationFormat], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("expiration_format") + @ExcludeMissing + fun _expirationFormat(): JsonField = expirationFormat + + /** + * Returns the raw JSON value of [method]. + * + * Unlike [method], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("method") @ExcludeMissing fun _method(): JsonField = method + + /** + * Returns the raw JSON value of [params]. + * + * Unlike [params], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("params") @ExcludeMissing fun _params(): JsonField = params + + /** + * Returns the raw JSON value of [requestContentType]. + * + * Unlike [requestContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("request_content_type") + @ExcludeMissing + fun _requestContentType(): JsonField = requestContentType + + /** + * Returns the raw JSON value of [responseContentType]. + * + * Unlike [responseContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("response_content_type") + @ExcludeMissing + fun _responseContentType(): JsonField = responseContentType + + /** + * Returns the raw JSON value of [responseMap]. + * + * Unlike [responseMap], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("response_map") + @ExcludeMissing + fun _responseMap(): JsonField = responseMap + + /** + * Returns the raw JSON value of [triggers]. + * + * Unlike [triggers], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("triggers") + @ExcludeMissing + fun _triggers(): JsonField = triggers + + @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 [UserInfoRequest]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UserInfoRequest]. */ + class Builder internal constructor() { + + private var authHeaderValueFormat: JsonField = JsonMissing.of() + private var authMethod: JsonField = JsonMissing.of() + private var endpoint: JsonField = JsonMissing.of() + private var expirationFormat: JsonField = JsonMissing.of() + private var method: JsonField = JsonMissing.of() + private var params: JsonField = JsonMissing.of() + private var requestContentType: JsonField = JsonMissing.of() + private var responseContentType: JsonField = JsonMissing.of() + private var responseMap: JsonField = JsonMissing.of() + private var triggers: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(userInfoRequest: UserInfoRequest) = apply { + authHeaderValueFormat = userInfoRequest.authHeaderValueFormat + authMethod = userInfoRequest.authMethod + endpoint = userInfoRequest.endpoint + expirationFormat = userInfoRequest.expirationFormat + method = userInfoRequest.method + params = userInfoRequest.params + requestContentType = userInfoRequest.requestContentType + responseContentType = userInfoRequest.responseContentType + responseMap = userInfoRequest.responseMap + triggers = userInfoRequest.triggers + additionalProperties = userInfoRequest.additionalProperties.toMutableMap() + } + + fun authHeaderValueFormat(authHeaderValueFormat: String) = + authHeaderValueFormat(JsonField.of(authHeaderValueFormat)) + + /** + * Sets [Builder.authHeaderValueFormat] to an arbitrary JSON value. + * + * You should usually call [Builder.authHeaderValueFormat] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun authHeaderValueFormat(authHeaderValueFormat: JsonField) = apply { + this.authHeaderValueFormat = authHeaderValueFormat + } + + fun authMethod(authMethod: String) = authMethod(JsonField.of(authMethod)) + + /** + * Sets [Builder.authMethod] to an arbitrary JSON value. + * + * You should usually call [Builder.authMethod] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun authMethod(authMethod: JsonField) = apply { + this.authMethod = authMethod + } + + 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 } + + fun expirationFormat(expirationFormat: String) = + expirationFormat(JsonField.of(expirationFormat)) + + /** + * Sets [Builder.expirationFormat] to an arbitrary JSON value. + * + * You should usually call [Builder.expirationFormat] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun expirationFormat(expirationFormat: JsonField) = apply { + this.expirationFormat = expirationFormat + } + + fun method(method: String) = method(JsonField.of(method)) + + /** + * Sets [Builder.method] to an arbitrary JSON value. + * + * You should usually call [Builder.method] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun method(method: JsonField) = apply { this.method = method } + + fun params(params: Params) = params(JsonField.of(params)) + + /** + * Sets [Builder.params] to an arbitrary JSON value. + * + * You should usually call [Builder.params] with a well-typed [Params] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun params(params: JsonField) = apply { this.params = params } + + fun requestContentType(requestContentType: String) = + requestContentType(JsonField.of(requestContentType)) + + /** + * Sets [Builder.requestContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.requestContentType] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun requestContentType(requestContentType: JsonField) = apply { + this.requestContentType = requestContentType + } + + fun responseContentType(responseContentType: String) = + responseContentType(JsonField.of(responseContentType)) + + /** + * Sets [Builder.responseContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.responseContentType] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun responseContentType(responseContentType: JsonField) = apply { + this.responseContentType = responseContentType + } + + fun responseMap(responseMap: ResponseMap) = responseMap(JsonField.of(responseMap)) + + /** + * Sets [Builder.responseMap] to an arbitrary JSON value. + * + * You should usually call [Builder.responseMap] with a well-typed [ResponseMap] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun responseMap(responseMap: JsonField) = apply { + this.responseMap = responseMap + } + + fun triggers(triggers: Triggers) = triggers(JsonField.of(triggers)) + + /** + * Sets [Builder.triggers] to an arbitrary JSON value. + * + * You should usually call [Builder.triggers] with a well-typed [Triggers] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun triggers(triggers: JsonField) = apply { this.triggers = triggers } + + 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 [UserInfoRequest]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): UserInfoRequest = + UserInfoRequest( + authHeaderValueFormat, + authMethod, + endpoint, + expirationFormat, + method, + params, + requestContentType, + responseContentType, + responseMap, + triggers, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): UserInfoRequest = apply { + if (validated) { + return@apply + } + + authHeaderValueFormat() + authMethod() + endpoint() + expirationFormat() + method() + params().ifPresent { it.validate() } + requestContentType() + responseContentType() + responseMap().ifPresent { it.validate() } + triggers().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (authHeaderValueFormat.asKnown().isPresent) 1 else 0) + + (if (authMethod.asKnown().isPresent) 1 else 0) + + (if (endpoint.asKnown().isPresent) 1 else 0) + + (if (expirationFormat.asKnown().isPresent) 1 else 0) + + (if (method.asKnown().isPresent) 1 else 0) + + (params.asKnown().getOrNull()?.validity() ?: 0) + + (if (requestContentType.asKnown().isPresent) 1 else 0) + + (if (responseContentType.asKnown().isPresent) 1 else 0) + + (responseMap.asKnown().getOrNull()?.validity() ?: 0) + + (triggers.asKnown().getOrNull()?.validity() ?: 0) + + class Params + @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 [Params]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Params]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(params: Params) = apply { + additionalProperties = params.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 [Params]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Params = Params(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Params = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 Params && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Params{additionalProperties=$additionalProperties}" + } + + class ResponseMap + @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 [ResponseMap]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ResponseMap]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(responseMap: ResponseMap) = apply { + additionalProperties = responseMap.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 [ResponseMap]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ResponseMap = ResponseMap(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): ResponseMap = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 ResponseMap && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ResponseMap{additionalProperties=$additionalProperties}" + } + + class Triggers + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val onTokenGrant: JsonField, + private val onTokenRefresh: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("on_token_grant") + @ExcludeMissing + onTokenGrant: JsonField = JsonMissing.of(), + @JsonProperty("on_token_refresh") + @ExcludeMissing + onTokenRefresh: JsonField = JsonMissing.of(), + ) : this(onTokenGrant, onTokenRefresh, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun onTokenGrant(): Optional = onTokenGrant.getOptional("on_token_grant") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun onTokenRefresh(): Optional = + onTokenRefresh.getOptional("on_token_refresh") + + /** + * Returns the raw JSON value of [onTokenGrant]. + * + * Unlike [onTokenGrant], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("on_token_grant") + @ExcludeMissing + fun _onTokenGrant(): JsonField = onTokenGrant + + /** + * Returns the raw JSON value of [onTokenRefresh]. + * + * Unlike [onTokenRefresh], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("on_token_refresh") + @ExcludeMissing + fun _onTokenRefresh(): JsonField = onTokenRefresh + + @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 [Triggers]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Triggers]. */ + class Builder internal constructor() { + + private var onTokenGrant: JsonField = JsonMissing.of() + private var onTokenRefresh: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(triggers: Triggers) = apply { + onTokenGrant = triggers.onTokenGrant + onTokenRefresh = triggers.onTokenRefresh + additionalProperties = triggers.additionalProperties.toMutableMap() + } + + fun onTokenGrant(onTokenGrant: Boolean) = + onTokenGrant(JsonField.of(onTokenGrant)) + + /** + * Sets [Builder.onTokenGrant] to an arbitrary JSON value. + * + * You should usually call [Builder.onTokenGrant] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun onTokenGrant(onTokenGrant: JsonField) = apply { + this.onTokenGrant = onTokenGrant + } + + fun onTokenRefresh(onTokenRefresh: Boolean) = + onTokenRefresh(JsonField.of(onTokenRefresh)) + + /** + * Sets [Builder.onTokenRefresh] to an arbitrary JSON value. + * + * You should usually call [Builder.onTokenRefresh] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun onTokenRefresh(onTokenRefresh: JsonField) = apply { + this.onTokenRefresh = onTokenRefresh + } + + 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 [Triggers]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Triggers = + Triggers(onTokenGrant, onTokenRefresh, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Triggers = apply { + if (validated) { + return@apply + } + + onTokenGrant() + onTokenRefresh() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (onTokenGrant.asKnown().isPresent) 1 else 0) + + (if (onTokenRefresh.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Triggers && + onTokenGrant == other.onTokenGrant && + onTokenRefresh == other.onTokenRefresh && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(onTokenGrant, onTokenRefresh, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Triggers{onTokenGrant=$onTokenGrant, onTokenRefresh=$onTokenRefresh, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UserInfoRequest && + authHeaderValueFormat == other.authHeaderValueFormat && + authMethod == other.authMethod && + endpoint == other.endpoint && + expirationFormat == other.expirationFormat && + method == other.method && + params == other.params && + requestContentType == other.requestContentType && + responseContentType == other.responseContentType && + responseMap == other.responseMap && + triggers == other.triggers && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + authHeaderValueFormat, + authMethod, + endpoint, + expirationFormat, + method, + params, + requestContentType, + responseContentType, + responseMap, + triggers, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "UserInfoRequest{authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, endpoint=$endpoint, expirationFormat=$expirationFormat, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, triggers=$triggers, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Oauth2 && + authorizeRequest == other.authorizeRequest && + clientId == other.clientId && + clientSecret == other.clientSecret && + pkce == other.pkce && + redirectUri == other.redirectUri && + refreshRequest == other.refreshRequest && + scopeDelimiter == other.scopeDelimiter && + tokenIntrospectionRequest == other.tokenIntrospectionRequest && + tokenRequest == other.tokenRequest && + userInfoRequest == other.userInfoRequest && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + authorizeRequest, + clientId, + clientSecret, + pkce, + redirectUri, + refreshRequest, + scopeDelimiter, + tokenIntrospectionRequest, + tokenRequest, + userInfoRequest, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Oauth2{authorizeRequest=$authorizeRequest, clientId=$clientId, clientSecret=$clientSecret, pkce=$pkce, redirectUri=$redirectUri, refreshRequest=$refreshRequest, scopeDelimiter=$scopeDelimiter, tokenIntrospectionRequest=$tokenIntrospectionRequest, tokenRequest=$tokenRequest, userInfoRequest=$userInfoRequest, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AuthProviderResponse && + id == other.id && + binding == other.binding && + createdAt == other.createdAt && + description == other.description && + oauth2 == other.oauth2 && + providerId == other.providerId && + status == other.status && + type == other.type && + updatedAt == other.updatedAt && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + binding, + createdAt, + description, + oauth2, + providerId, + status, + type, + updatedAt, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AuthProviderResponse{id=$id, binding=$binding, createdAt=$createdAt, description=$description, oauth2=$oauth2, providerId=$providerId, status=$status, type=$type, updatedAt=$updatedAt, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthProviderCreateRequest.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/authproviders/AuthProviderUpdateRequest.kt similarity index 55% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/AuthProviderCreateRequest.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/admin/authproviders/AuthProviderUpdateRequest.kt index 245a7e3..159520d 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthProviderCreateRequest.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/authproviders/AuthProviderUpdateRequest.kt @@ -1,6 +1,6 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.admin.authproviders import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter @@ -11,103 +11,142 @@ import dev.arcade.core.ExcludeMissing import dev.arcade.core.JsonField import dev.arcade.core.JsonMissing import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.checkRequired -import dev.arcade.core.immutableEmptyMap import dev.arcade.core.toImmutable import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect -class AuthProviderCreateRequest -@JsonCreator +class AuthProviderUpdateRequest +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("external_id") - @ExcludeMissing - private val externalId: JsonField = JsonMissing.of(), - @JsonProperty("oauth2") - @ExcludeMissing - private val oauth2: JsonField = JsonMissing.of(), - @JsonProperty("provider_id") - @ExcludeMissing - private val providerId: JsonField = JsonMissing.of(), - @JsonProperty("status") - @ExcludeMissing - private val status: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val description: JsonField, + private val oauth2: JsonField, + private val providerId: JsonField, + private val status: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - fun id(): String = id.getRequired("id") - - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) - - /** The unique external ID for the auth provider */ - fun externalId(): Optional = Optional.ofNullable(externalId.getNullable("external_id")) - - fun oauth2(): Optional = Optional.ofNullable(oauth2.getNullable("oauth2")) - - fun providerId(): Optional = Optional.ofNullable(providerId.getNullable("provider_id")) - - fun status(): Optional = Optional.ofNullable(status.getNullable("status")) - - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("oauth2") @ExcludeMissing oauth2: JsonField = JsonMissing.of(), + @JsonProperty("provider_id") + @ExcludeMissing + providerId: JsonField = JsonMissing.of(), + @JsonProperty("status") @ExcludeMissing status: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(id, description, oauth2, providerId, status, type, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun oauth2(): Optional = oauth2.getOptional("oauth2") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun providerId(): Optional = providerId.getOptional("provider_id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun status(): Optional = status.getOptional("status") + + /** + * @throws ArcadeInvalidDataException 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 [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 - /** The unique external ID for the auth provider */ - @JsonProperty("external_id") @ExcludeMissing fun _externalId(): JsonField = externalId - + /** + * Returns the raw JSON value of [oauth2]. + * + * Unlike [oauth2], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("oauth2") @ExcludeMissing fun _oauth2(): JsonField = oauth2 + /** + * Returns the raw JSON value of [providerId]. + * + * Unlike [providerId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("provider_id") @ExcludeMissing fun _providerId(): JsonField = providerId + /** + * 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 = additionalProperties - - private var validated: Boolean = false - - fun validate(): AuthProviderCreateRequest = apply { - if (validated) { - return@apply - } - - id() - description() - externalId() - oauth2().ifPresent { it.validate() } - providerId() - status() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [AuthProviderUpdateRequest]. + */ @JvmStatic fun builder() = Builder() } - /** A builder for [AuthProviderCreateRequest]. */ + /** A builder for [AuthProviderUpdateRequest]. */ class Builder internal constructor() { - private var id: JsonField? = null + private var id: JsonField = JsonMissing.of() private var description: JsonField = JsonMissing.of() - private var externalId: JsonField = JsonMissing.of() private var oauth2: JsonField = JsonMissing.of() private var providerId: JsonField = JsonMissing.of() private var status: JsonField = JsonMissing.of() @@ -115,45 +154,76 @@ private constructor( private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic - internal fun from(authProviderCreateRequest: AuthProviderCreateRequest) = apply { - id = authProviderCreateRequest.id - description = authProviderCreateRequest.description - externalId = authProviderCreateRequest.externalId - oauth2 = authProviderCreateRequest.oauth2 - providerId = authProviderCreateRequest.providerId - status = authProviderCreateRequest.status - type = authProviderCreateRequest.type - additionalProperties = authProviderCreateRequest.additionalProperties.toMutableMap() + internal fun from(authProviderUpdateRequest: AuthProviderUpdateRequest) = apply { + id = authProviderUpdateRequest.id + description = authProviderUpdateRequest.description + oauth2 = authProviderUpdateRequest.oauth2 + providerId = authProviderUpdateRequest.providerId + status = authProviderUpdateRequest.status + type = authProviderUpdateRequest.type + additionalProperties = authProviderUpdateRequest.additionalProperties.toMutableMap() } 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 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 unique external ID for the auth provider */ - fun externalId(externalId: String) = externalId(JsonField.of(externalId)) - - /** The unique external ID for the auth provider */ - fun externalId(externalId: JsonField) = apply { this.externalId = externalId } - fun oauth2(oauth2: Oauth2) = oauth2(JsonField.of(oauth2)) + /** + * Sets [Builder.oauth2] to an arbitrary JSON value. + * + * You should usually call [Builder.oauth2] with a well-typed [Oauth2] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun oauth2(oauth2: JsonField) = apply { this.oauth2 = oauth2 } fun providerId(providerId: String) = providerId(JsonField.of(providerId)) + /** + * Sets [Builder.providerId] to an arbitrary JSON value. + * + * You should usually call [Builder.providerId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun providerId(providerId: JsonField) = apply { this.providerId = providerId } fun status(status: String) = status(JsonField.of(status)) + /** + * Sets [Builder.status] to an arbitrary JSON value. + * + * You should usually call [Builder.status] with a well-typed [String] 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 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 { @@ -175,196 +245,340 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): AuthProviderCreateRequest = - AuthProviderCreateRequest( - checkRequired("id", id), + /** + * Returns an immutable instance of [AuthProviderUpdateRequest]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): AuthProviderUpdateRequest = + AuthProviderUpdateRequest( + id, description, - externalId, oauth2, providerId, status, type, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect - class Oauth2 - @JsonCreator - private constructor( - @JsonProperty("client_id") - @ExcludeMissing - private val clientId: JsonField = JsonMissing.of(), - @JsonProperty("authorize_request") - @ExcludeMissing - private val authorizeRequest: JsonField = JsonMissing.of(), - @JsonProperty("client_secret") - @ExcludeMissing - private val clientSecret: JsonField = JsonMissing.of(), - @JsonProperty("pkce") @ExcludeMissing private val pkce: JsonField = JsonMissing.of(), - @JsonProperty("refresh_request") - @ExcludeMissing - private val refreshRequest: JsonField = JsonMissing.of(), - @JsonProperty("scope_delimiter") - @ExcludeMissing - private val scopeDelimiter: JsonField = JsonMissing.of(), - @JsonProperty("token_introspection_request") - @ExcludeMissing - private val tokenIntrospectionRequest: JsonField = - JsonMissing.of(), - @JsonProperty("token_request") - @ExcludeMissing - private val tokenRequest: JsonField = JsonMissing.of(), - @JsonProperty("user_info_request") - @ExcludeMissing - private val userInfoRequest: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + private var validated: Boolean = false - fun clientId(): String = clientId.getRequired("client_id") + fun validate(): AuthProviderUpdateRequest = apply { + if (validated) { + return@apply + } - fun authorizeRequest(): Optional = - Optional.ofNullable(authorizeRequest.getNullable("authorize_request")) + id() + description() + oauth2().ifPresent { it.validate() } + providerId() + status() + type() + validated = true + } - fun clientSecret(): Optional = - Optional.ofNullable(clientSecret.getNullable("client_secret")) + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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) + + (oauth2.asKnown().getOrNull()?.validity() ?: 0) + + (if (providerId.asKnown().isPresent) 1 else 0) + + (if (status.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) - fun pkce(): Optional = Optional.ofNullable(pkce.getNullable("pkce")) + class Oauth2 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val authorizeRequest: JsonField, + private val clientId: JsonField, + private val clientSecret: JsonField, + private val pkce: JsonField, + private val refreshRequest: JsonField, + private val scopeDelimiter: JsonField, + private val tokenRequest: JsonField, + private val userInfoRequest: JsonField, + private val additionalProperties: MutableMap, + ) { + @JsonCreator + private constructor( + @JsonProperty("authorize_request") + @ExcludeMissing + authorizeRequest: JsonField = JsonMissing.of(), + @JsonProperty("client_id") + @ExcludeMissing + clientId: JsonField = JsonMissing.of(), + @JsonProperty("client_secret") + @ExcludeMissing + clientSecret: JsonField = JsonMissing.of(), + @JsonProperty("pkce") @ExcludeMissing pkce: JsonField = JsonMissing.of(), + @JsonProperty("refresh_request") + @ExcludeMissing + refreshRequest: JsonField = JsonMissing.of(), + @JsonProperty("scope_delimiter") + @ExcludeMissing + scopeDelimiter: JsonField = JsonMissing.of(), + @JsonProperty("token_request") + @ExcludeMissing + tokenRequest: JsonField = JsonMissing.of(), + @JsonProperty("user_info_request") + @ExcludeMissing + userInfoRequest: JsonField = JsonMissing.of(), + ) : this( + authorizeRequest, + clientId, + clientSecret, + pkce, + refreshRequest, + scopeDelimiter, + tokenRequest, + userInfoRequest, + mutableMapOf(), + ) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun authorizeRequest(): Optional = + authorizeRequest.getOptional("authorize_request") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun clientId(): Optional = clientId.getOptional("client_id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun clientSecret(): Optional = clientSecret.getOptional("client_secret") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun pkce(): Optional = pkce.getOptional("pkce") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun refreshRequest(): Optional = - Optional.ofNullable(refreshRequest.getNullable("refresh_request")) + refreshRequest.getOptional("refresh_request") + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun scopeDelimiter(): Optional = - Optional.ofNullable(scopeDelimiter.getNullable("scope_delimiter")) - - fun tokenIntrospectionRequest(): Optional = - Optional.ofNullable( - tokenIntrospectionRequest.getNullable("token_introspection_request") - ) - - fun tokenRequest(): Optional = - Optional.ofNullable(tokenRequest.getNullable("token_request")) - + scopeDelimiter.getOptional("scope_delimiter") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun tokenRequest(): Optional = tokenRequest.getOptional("token_request") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun userInfoRequest(): Optional = - Optional.ofNullable(userInfoRequest.getNullable("user_info_request")) - - @JsonProperty("client_id") @ExcludeMissing fun _clientId(): JsonField = clientId - + userInfoRequest.getOptional("user_info_request") + + /** + * Returns the raw JSON value of [authorizeRequest]. + * + * Unlike [authorizeRequest], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("authorize_request") @ExcludeMissing fun _authorizeRequest(): JsonField = authorizeRequest + /** + * Returns the raw JSON value of [clientId]. + * + * Unlike [clientId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("client_id") @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("client_secret") @ExcludeMissing fun _clientSecret(): JsonField = clientSecret + /** + * Returns the raw JSON value of [pkce]. + * + * Unlike [pkce], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("pkce") @ExcludeMissing fun _pkce(): JsonField = pkce + /** + * Returns the raw JSON value of [refreshRequest]. + * + * Unlike [refreshRequest], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("refresh_request") @ExcludeMissing fun _refreshRequest(): JsonField = refreshRequest + /** + * Returns the raw JSON value of [scopeDelimiter]. + * + * Unlike [scopeDelimiter], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("scope_delimiter") @ExcludeMissing fun _scopeDelimiter(): JsonField = scopeDelimiter - @JsonProperty("token_introspection_request") - @ExcludeMissing - fun _tokenIntrospectionRequest(): JsonField = - tokenIntrospectionRequest - + /** + * Returns the raw JSON value of [tokenRequest]. + * + * Unlike [tokenRequest], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("token_request") @ExcludeMissing fun _tokenRequest(): JsonField = tokenRequest + /** + * Returns the raw JSON value of [userInfoRequest]. + * + * Unlike [userInfoRequest], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("user_info_request") @ExcludeMissing fun _userInfoRequest(): JsonField = userInfoRequest + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Oauth2 = apply { - if (validated) { - return@apply - } - - clientId() - authorizeRequest().ifPresent { it.validate() } - clientSecret() - pkce().ifPresent { it.validate() } - refreshRequest().ifPresent { it.validate() } - scopeDelimiter() - tokenIntrospectionRequest().ifPresent { it.validate() } - tokenRequest().ifPresent { it.validate() } - userInfoRequest().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Oauth2]. */ @JvmStatic fun builder() = Builder() } /** A builder for [Oauth2]. */ class Builder internal constructor() { - private var clientId: JsonField? = null private var authorizeRequest: JsonField = JsonMissing.of() + private var clientId: JsonField = JsonMissing.of() private var clientSecret: JsonField = JsonMissing.of() private var pkce: JsonField = JsonMissing.of() private var refreshRequest: JsonField = JsonMissing.of() private var scopeDelimiter: JsonField = JsonMissing.of() - private var tokenIntrospectionRequest: JsonField = - JsonMissing.of() private var tokenRequest: JsonField = JsonMissing.of() private var userInfoRequest: JsonField = JsonMissing.of() private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic internal fun from(oauth2: Oauth2) = apply { - clientId = oauth2.clientId authorizeRequest = oauth2.authorizeRequest + clientId = oauth2.clientId clientSecret = oauth2.clientSecret pkce = oauth2.pkce refreshRequest = oauth2.refreshRequest scopeDelimiter = oauth2.scopeDelimiter - tokenIntrospectionRequest = oauth2.tokenIntrospectionRequest tokenRequest = oauth2.tokenRequest userInfoRequest = oauth2.userInfoRequest additionalProperties = oauth2.additionalProperties.toMutableMap() } - fun clientId(clientId: String) = clientId(JsonField.of(clientId)) - - fun clientId(clientId: JsonField) = apply { this.clientId = clientId } - fun authorizeRequest(authorizeRequest: AuthorizeRequest) = authorizeRequest(JsonField.of(authorizeRequest)) + /** + * Sets [Builder.authorizeRequest] to an arbitrary JSON value. + * + * You should usually call [Builder.authorizeRequest] with a well-typed + * [AuthorizeRequest] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ fun authorizeRequest(authorizeRequest: JsonField) = apply { this.authorizeRequest = authorizeRequest } + 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 } + 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 } fun pkce(pkce: Pkce) = pkce(JsonField.of(pkce)) + /** + * Sets [Builder.pkce] to an arbitrary JSON value. + * + * You should usually call [Builder.pkce] with a well-typed [Pkce] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun pkce(pkce: JsonField) = apply { this.pkce = pkce } fun refreshRequest(refreshRequest: RefreshRequest) = refreshRequest(JsonField.of(refreshRequest)) + /** + * Sets [Builder.refreshRequest] to an arbitrary JSON value. + * + * You should usually call [Builder.refreshRequest] with a well-typed [RefreshRequest] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun refreshRequest(refreshRequest: JsonField) = apply { this.refreshRequest = refreshRequest } @@ -372,19 +586,26 @@ private constructor( fun scopeDelimiter(scopeDelimiter: ScopeDelimiter) = scopeDelimiter(JsonField.of(scopeDelimiter)) + /** + * Sets [Builder.scopeDelimiter] to an arbitrary JSON value. + * + * You should usually call [Builder.scopeDelimiter] with a well-typed [ScopeDelimiter] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun scopeDelimiter(scopeDelimiter: JsonField) = apply { this.scopeDelimiter = scopeDelimiter } - fun tokenIntrospectionRequest(tokenIntrospectionRequest: TokenIntrospectionRequest) = - tokenIntrospectionRequest(JsonField.of(tokenIntrospectionRequest)) - - fun tokenIntrospectionRequest( - tokenIntrospectionRequest: JsonField - ) = apply { this.tokenIntrospectionRequest = tokenIntrospectionRequest } - fun tokenRequest(tokenRequest: TokenRequest) = tokenRequest(JsonField.of(tokenRequest)) + /** + * Sets [Builder.tokenRequest] to an arbitrary JSON value. + * + * You should usually call [Builder.tokenRequest] with a well-typed [TokenRequest] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun tokenRequest(tokenRequest: JsonField) = apply { this.tokenRequest = tokenRequest } @@ -392,6 +613,13 @@ private constructor( fun userInfoRequest(userInfoRequest: UserInfoRequest) = userInfoRequest(JsonField.of(userInfoRequest)) + /** + * Sets [Builder.userInfoRequest] to an arbitrary JSON value. + * + * You should usually call [Builder.userInfoRequest] with a well-typed [UserInfoRequest] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun userInfoRequest(userInfoRequest: JsonField) = apply { this.userInfoRequest = userInfoRequest } @@ -415,135 +643,267 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Oauth2]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Oauth2 = Oauth2( - checkRequired("clientId", clientId), authorizeRequest, + clientId, clientSecret, pkce, refreshRequest, scopeDelimiter, - tokenIntrospectionRequest, tokenRequest, userInfoRequest, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): Oauth2 = apply { + if (validated) { + return@apply + } + + authorizeRequest().ifPresent { it.validate() } + clientId() + clientSecret() + pkce().ifPresent { it.validate() } + refreshRequest().ifPresent { it.validate() } + scopeDelimiter().ifPresent { it.validate() } + tokenRequest().ifPresent { it.validate() } + userInfoRequest().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (authorizeRequest.asKnown().getOrNull()?.validity() ?: 0) + + (if (clientId.asKnown().isPresent) 1 else 0) + + (if (clientSecret.asKnown().isPresent) 1 else 0) + + (pkce.asKnown().getOrNull()?.validity() ?: 0) + + (refreshRequest.asKnown().getOrNull()?.validity() ?: 0) + + (scopeDelimiter.asKnown().getOrNull()?.validity() ?: 0) + + (tokenRequest.asKnown().getOrNull()?.validity() ?: 0) + + (userInfoRequest.asKnown().getOrNull()?.validity() ?: 0) + class AuthorizeRequest - @JsonCreator + @JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( - @JsonProperty("endpoint") - @ExcludeMissing - private val endpoint: JsonField = JsonMissing.of(), - @JsonProperty("auth_header_value_format") - @ExcludeMissing - private val authHeaderValueFormat: JsonField = JsonMissing.of(), - @JsonProperty("auth_method") - @ExcludeMissing - private val authMethod: JsonField = JsonMissing.of(), - @JsonProperty("method") - @ExcludeMissing - private val method: JsonField = JsonMissing.of(), - @JsonProperty("params") - @ExcludeMissing - private val params: JsonField = JsonMissing.of(), - @JsonProperty("request_content_type") - @ExcludeMissing - private val requestContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_content_type") - @ExcludeMissing - private val responseContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_map") - @ExcludeMissing - private val responseMap: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val authHeaderValueFormat: JsonField, + private val authMethod: JsonField, + private val endpoint: JsonField, + private val method: JsonField, + private val params: JsonField, + private val requestContentType: JsonField, + private val responseContentType: JsonField, + private val responseMap: JsonField, + private val additionalProperties: MutableMap, ) { - fun endpoint(): String = endpoint.getRequired("endpoint") + @JsonCreator + private constructor( + @JsonProperty("auth_header_value_format") + @ExcludeMissing + authHeaderValueFormat: JsonField = JsonMissing.of(), + @JsonProperty("auth_method") + @ExcludeMissing + authMethod: JsonField = JsonMissing.of(), + @JsonProperty("endpoint") + @ExcludeMissing + endpoint: JsonField = JsonMissing.of(), + @JsonProperty("method") + @ExcludeMissing + method: JsonField = JsonMissing.of(), + @JsonProperty("params") + @ExcludeMissing + params: JsonField = JsonMissing.of(), + @JsonProperty("request_content_type") + @ExcludeMissing + requestContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_content_type") + @ExcludeMissing + responseContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_map") + @ExcludeMissing + responseMap: JsonField = JsonMissing.of(), + ) : this( + authHeaderValueFormat, + authMethod, + endpoint, + method, + params, + requestContentType, + responseContentType, + responseMap, + mutableMapOf(), + ) + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ fun authHeaderValueFormat(): Optional = - Optional.ofNullable(authHeaderValueFormat.getNullable("auth_header_value_format")) + authHeaderValueFormat.getOptional("auth_header_value_format") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authMethod(): Optional = authMethod.getOptional("auth_method") - fun authMethod(): Optional = - Optional.ofNullable(authMethod.getNullable("auth_method")) + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun endpoint(): Optional = endpoint.getOptional("endpoint") - fun method(): Optional = Optional.ofNullable(method.getNullable("method")) + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun method(): Optional = method.getOptional("method") - fun params(): Optional = Optional.ofNullable(params.getNullable("params")) + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun params(): Optional = params.getOptional("params") + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ fun requestContentType(): Optional = - Optional.ofNullable(requestContentType.getNullable("request_content_type")) + requestContentType.getOptional("request_content_type") + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ fun responseContentType(): Optional = - Optional.ofNullable(responseContentType.getNullable("response_content_type")) + responseContentType.getOptional("response_content_type") - fun responseMap(): Optional = - Optional.ofNullable(responseMap.getNullable("response_map")) - - @JsonProperty("endpoint") @ExcludeMissing fun _endpoint(): JsonField = endpoint + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun responseMap(): Optional = responseMap.getOptional("response_map") + /** + * Returns the raw JSON value of [authHeaderValueFormat]. + * + * Unlike [authHeaderValueFormat], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("auth_header_value_format") @ExcludeMissing fun _authHeaderValueFormat(): JsonField = authHeaderValueFormat + /** + * Returns the raw JSON value of [authMethod]. + * + * Unlike [authMethod], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("auth_method") @ExcludeMissing fun _authMethod(): JsonField = authMethod + /** + * 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 [method]. + * + * Unlike [method], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("method") @ExcludeMissing fun _method(): JsonField = method + /** + * Returns the raw JSON value of [params]. + * + * Unlike [params], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("params") @ExcludeMissing fun _params(): JsonField = params + /** + * Returns the raw JSON value of [requestContentType]. + * + * Unlike [requestContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("request_content_type") @ExcludeMissing fun _requestContentType(): JsonField = requestContentType + /** + * Returns the raw JSON value of [responseContentType]. + * + * Unlike [responseContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("response_content_type") @ExcludeMissing fun _responseContentType(): JsonField = responseContentType + /** + * Returns the raw JSON value of [responseMap]. + * + * Unlike [responseMap], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("response_map") @ExcludeMissing fun _responseMap(): JsonField = responseMap + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) - private var validated: Boolean = false - - fun validate(): AuthorizeRequest = apply { - if (validated) { - return@apply - } - - endpoint() - authHeaderValueFormat() - authMethod() - method() - params().ifPresent { it.validate() } - requestContentType() - responseContentType() - responseMap().ifPresent { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) + fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [AuthorizeRequest]. */ @JvmStatic fun builder() = Builder() } /** A builder for [AuthorizeRequest]. */ class Builder internal constructor() { - private var endpoint: JsonField? = null private var authHeaderValueFormat: JsonField = JsonMissing.of() private var authMethod: JsonField = JsonMissing.of() + private var endpoint: JsonField = JsonMissing.of() private var method: JsonField = JsonMissing.of() private var params: JsonField = JsonMissing.of() private var requestContentType: JsonField = JsonMissing.of() @@ -553,9 +913,9 @@ private constructor( @JvmSynthetic internal fun from(authorizeRequest: AuthorizeRequest) = apply { - endpoint = authorizeRequest.endpoint authHeaderValueFormat = authorizeRequest.authHeaderValueFormat authMethod = authorizeRequest.authMethod + endpoint = authorizeRequest.endpoint method = authorizeRequest.method params = authorizeRequest.params requestContentType = authorizeRequest.requestContentType @@ -564,34 +924,76 @@ private constructor( additionalProperties = authorizeRequest.additionalProperties.toMutableMap() } - fun endpoint(endpoint: String) = endpoint(JsonField.of(endpoint)) - - fun endpoint(endpoint: JsonField) = apply { this.endpoint = endpoint } - fun authHeaderValueFormat(authHeaderValueFormat: String) = authHeaderValueFormat(JsonField.of(authHeaderValueFormat)) + /** + * Sets [Builder.authHeaderValueFormat] to an arbitrary JSON value. + * + * You should usually call [Builder.authHeaderValueFormat] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun authHeaderValueFormat(authHeaderValueFormat: JsonField) = apply { this.authHeaderValueFormat = authHeaderValueFormat } fun authMethod(authMethod: String) = authMethod(JsonField.of(authMethod)) + /** + * Sets [Builder.authMethod] to an arbitrary JSON value. + * + * You should usually call [Builder.authMethod] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun authMethod(authMethod: JsonField) = apply { this.authMethod = authMethod } + 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 } + fun method(method: String) = method(JsonField.of(method)) + /** + * Sets [Builder.method] to an arbitrary JSON value. + * + * You should usually call [Builder.method] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun method(method: JsonField) = apply { this.method = method } fun params(params: Params) = params(JsonField.of(params)) + /** + * Sets [Builder.params] to an arbitrary JSON value. + * + * You should usually call [Builder.params] with a well-typed [Params] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun params(params: JsonField) = apply { this.params = params } fun requestContentType(requestContentType: RequestContentType) = requestContentType(JsonField.of(requestContentType)) + /** + * Sets [Builder.requestContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.requestContentType] with a well-typed + * [RequestContentType] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun requestContentType(requestContentType: JsonField) = apply { this.requestContentType = requestContentType } @@ -599,6 +1001,13 @@ private constructor( fun responseContentType(responseContentType: ResponseContentType) = responseContentType(JsonField.of(responseContentType)) + /** + * Sets [Builder.responseContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.responseContentType] with a well-typed + * [ResponseContentType] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun responseContentType(responseContentType: JsonField) = apply { this.responseContentType = responseContentType @@ -606,6 +1015,13 @@ private constructor( fun responseMap(responseMap: ResponseMap) = responseMap(JsonField.of(responseMap)) + /** + * Sets [Builder.responseMap] to an arbitrary JSON value. + * + * You should usually call [Builder.responseMap] with a well-typed [ResponseMap] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ fun responseMap(responseMap: JsonField) = apply { this.responseMap = responseMap } @@ -632,46 +1048,84 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [AuthorizeRequest]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): AuthorizeRequest = AuthorizeRequest( - checkRequired("endpoint", endpoint), authHeaderValueFormat, authMethod, + endpoint, method, params, requestContentType, responseContentType, responseMap, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): AuthorizeRequest = apply { + if (validated) { + return@apply + } + + authHeaderValueFormat() + authMethod() + endpoint() + method() + params().ifPresent { it.validate() } + requestContentType().ifPresent { it.validate() } + responseContentType().ifPresent { it.validate() } + responseMap().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (authHeaderValueFormat.asKnown().isPresent) 1 else 0) + + (if (authMethod.asKnown().isPresent) 1 else 0) + + (if (endpoint.asKnown().isPresent) 1 else 0) + + (if (method.asKnown().isPresent) 1 else 0) + + (params.asKnown().getOrNull()?.validity() ?: 0) + + (requestContentType.asKnown().getOrNull()?.validity() ?: 0) + + (responseContentType.asKnown().getOrNull()?.validity() ?: 0) + + (responseMap.asKnown().getOrNull()?.validity() ?: 0) + class Params @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Params = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Params]. */ @JvmStatic fun builder() = Builder() } @@ -707,20 +1161,53 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Params]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Params = Params(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): Params = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 /* spotless:off */ other is Params && additionalProperties == other.additionalProperties /* spotless:on */ + return other is Params && additionalProperties == other.additionalProperties } - /* spotless:off */ private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ override fun hashCode(): Int = hashCode @@ -823,12 +1310,39 @@ private constructor( ArcadeInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): RequestContentType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 /* spotless:off */ other is RequestContentType && value == other.value /* spotless:on */ + return other is RequestContentType && value == other.value } override fun hashCode() = value.hashCode() @@ -932,12 +1446,39 @@ private constructor( ArcadeInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): ResponseContentType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 /* spotless:off */ other is ResponseContentType && value == other.value /* spotless:on */ + return other is ResponseContentType && value == other.value } override fun hashCode() = value.hashCode() @@ -945,32 +1486,22 @@ private constructor( override fun toString() = value.toString() } - @NoAutoDetect class ResponseMap @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): ResponseMap = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [ResponseMap]. */ @JvmStatic fun builder() = Builder() } @@ -1006,20 +1537,54 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [ResponseMap]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): ResponseMap = ResponseMap(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): ResponseMap = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 /* spotless:off */ other is ResponseMap && additionalProperties == other.additionalProperties /* spotless:on */ + return other is ResponseMap && + additionalProperties == other.additionalProperties } - /* spotless:off */ private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ override fun hashCode(): Int = hashCode @@ -1031,64 +1596,101 @@ private constructor( return true } - return /* spotless:off */ other is AuthorizeRequest && endpoint == other.endpoint && authHeaderValueFormat == other.authHeaderValueFormat && authMethod == other.authMethod && method == other.method && params == other.params && requestContentType == other.requestContentType && responseContentType == other.responseContentType && responseMap == other.responseMap && additionalProperties == other.additionalProperties /* spotless:on */ + return other is AuthorizeRequest && + authHeaderValueFormat == other.authHeaderValueFormat && + authMethod == other.authMethod && + endpoint == other.endpoint && + method == other.method && + params == other.params && + requestContentType == other.requestContentType && + responseContentType == other.responseContentType && + responseMap == other.responseMap && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(endpoint, authHeaderValueFormat, authMethod, method, params, requestContentType, responseContentType, responseMap, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash( + authHeaderValueFormat, + authMethod, + endpoint, + method, + params, + requestContentType, + responseContentType, + responseMap, + additionalProperties, + ) + } override fun hashCode(): Int = hashCode override fun toString() = - "AuthorizeRequest{endpoint=$endpoint, authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, additionalProperties=$additionalProperties}" + "AuthorizeRequest{authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, endpoint=$endpoint, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Pkce - @JsonCreator + @JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( - @JsonProperty("code_challenge_method") - @ExcludeMissing - private val codeChallengeMethod: JsonField = JsonMissing.of(), - @JsonProperty("enabled") - @ExcludeMissing - private val enabled: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val codeChallengeMethod: JsonField, + private val enabled: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("code_challenge_method") + @ExcludeMissing + codeChallengeMethod: JsonField = JsonMissing.of(), + @JsonProperty("enabled") + @ExcludeMissing + enabled: JsonField = JsonMissing.of(), + ) : this(codeChallengeMethod, enabled, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ fun codeChallengeMethod(): Optional = - Optional.ofNullable(codeChallengeMethod.getNullable("code_challenge_method")) + codeChallengeMethod.getOptional("code_challenge_method") - fun enabled(): Optional = Optional.ofNullable(enabled.getNullable("enabled")) + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun enabled(): Optional = enabled.getOptional("enabled") + /** + * Returns the raw JSON value of [codeChallengeMethod]. + * + * Unlike [codeChallengeMethod], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("code_challenge_method") @ExcludeMissing fun _codeChallengeMethod(): JsonField = codeChallengeMethod + /** + * Returns the raw JSON value of [enabled]. + * + * Unlike [enabled], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("enabled") @ExcludeMissing fun _enabled(): JsonField = enabled + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Pkce = apply { - if (validated) { - return@apply - } - - codeChallengeMethod() - enabled() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Pkce]. */ @JvmStatic fun builder() = Builder() } @@ -1109,12 +1711,26 @@ private constructor( fun codeChallengeMethod(codeChallengeMethod: String) = codeChallengeMethod(JsonField.of(codeChallengeMethod)) + /** + * Sets [Builder.codeChallengeMethod] to an arbitrary JSON value. + * + * You should usually call [Builder.codeChallengeMethod] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ fun codeChallengeMethod(codeChallengeMethod: JsonField) = apply { this.codeChallengeMethod = codeChallengeMethod } fun enabled(enabled: Boolean) = enabled(JsonField.of(enabled)) + /** + * Sets [Builder.enabled] to an arbitrary JSON value. + * + * You should usually call [Builder.enabled] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun enabled(enabled: JsonField) = apply { this.enabled = enabled } fun additionalProperties(additionalProperties: Map) = apply { @@ -1139,21 +1755,60 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Pkce]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Pkce = - Pkce(codeChallengeMethod, enabled, additionalProperties.toImmutable()) + Pkce(codeChallengeMethod, enabled, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Pkce = apply { + if (validated) { + return@apply + } + + codeChallengeMethod() + enabled() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (codeChallengeMethod.asKnown().isPresent) 1 else 0) + + (if (enabled.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is Pkce && codeChallengeMethod == other.codeChallengeMethod && enabled == other.enabled && additionalProperties == other.additionalProperties /* spotless:on */ + return other is Pkce && + codeChallengeMethod == other.codeChallengeMethod && + enabled == other.enabled && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(codeChallengeMethod, enabled, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash(codeChallengeMethod, enabled, additionalProperties) + } override fun hashCode(): Int = hashCode @@ -1161,120 +1816,205 @@ private constructor( "Pkce{codeChallengeMethod=$codeChallengeMethod, enabled=$enabled, additionalProperties=$additionalProperties}" } - @NoAutoDetect class RefreshRequest - @JsonCreator + @JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( - @JsonProperty("endpoint") - @ExcludeMissing - private val endpoint: JsonField = JsonMissing.of(), - @JsonProperty("auth_header_value_format") - @ExcludeMissing - private val authHeaderValueFormat: JsonField = JsonMissing.of(), - @JsonProperty("auth_method") - @ExcludeMissing - private val authMethod: JsonField = JsonMissing.of(), - @JsonProperty("method") - @ExcludeMissing - private val method: JsonField = JsonMissing.of(), - @JsonProperty("params") - @ExcludeMissing - private val params: JsonField = JsonMissing.of(), - @JsonProperty("request_content_type") - @ExcludeMissing - private val requestContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_content_type") - @ExcludeMissing - private val responseContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_map") - @ExcludeMissing - private val responseMap: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val authHeaderValueFormat: JsonField, + private val authMethod: JsonField, + private val endpoint: JsonField, + private val method: JsonField, + private val params: JsonField, + private val requestContentType: JsonField, + private val responseContentType: JsonField, + private val responseMap: JsonField, + private val additionalProperties: MutableMap, ) { - fun endpoint(): String = endpoint.getRequired("endpoint") - - fun authHeaderValueFormat(): Optional = - Optional.ofNullable(authHeaderValueFormat.getNullable("auth_header_value_format")) - - fun authMethod(): Optional = - Optional.ofNullable(authMethod.getNullable("auth_method")) - - fun method(): Optional = Optional.ofNullable(method.getNullable("method")) - - fun params(): Optional = Optional.ofNullable(params.getNullable("params")) - - fun requestContentType(): Optional = - Optional.ofNullable(requestContentType.getNullable("request_content_type")) - - fun responseContentType(): Optional = - Optional.ofNullable(responseContentType.getNullable("response_content_type")) - - fun responseMap(): Optional = - Optional.ofNullable(responseMap.getNullable("response_map")) + @JsonCreator + private constructor( + @JsonProperty("auth_header_value_format") + @ExcludeMissing + authHeaderValueFormat: JsonField = JsonMissing.of(), + @JsonProperty("auth_method") + @ExcludeMissing + authMethod: JsonField = JsonMissing.of(), + @JsonProperty("endpoint") + @ExcludeMissing + endpoint: JsonField = JsonMissing.of(), + @JsonProperty("method") + @ExcludeMissing + method: JsonField = JsonMissing.of(), + @JsonProperty("params") + @ExcludeMissing + params: JsonField = JsonMissing.of(), + @JsonProperty("request_content_type") + @ExcludeMissing + requestContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_content_type") + @ExcludeMissing + responseContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_map") + @ExcludeMissing + responseMap: JsonField = JsonMissing.of(), + ) : this( + authHeaderValueFormat, + authMethod, + endpoint, + method, + params, + requestContentType, + responseContentType, + responseMap, + mutableMapOf(), + ) - @JsonProperty("endpoint") @ExcludeMissing fun _endpoint(): JsonField = endpoint + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authHeaderValueFormat(): Optional = + authHeaderValueFormat.getOptional("auth_header_value_format") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authMethod(): Optional = authMethod.getOptional("auth_method") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun endpoint(): Optional = endpoint.getOptional("endpoint") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun method(): Optional = method.getOptional("method") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun params(): Optional = params.getOptional("params") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun requestContentType(): Optional = + requestContentType.getOptional("request_content_type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun responseContentType(): Optional = + responseContentType.getOptional("response_content_type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun responseMap(): Optional = responseMap.getOptional("response_map") + /** + * Returns the raw JSON value of [authHeaderValueFormat]. + * + * Unlike [authHeaderValueFormat], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("auth_header_value_format") @ExcludeMissing fun _authHeaderValueFormat(): JsonField = authHeaderValueFormat + /** + * Returns the raw JSON value of [authMethod]. + * + * Unlike [authMethod], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("auth_method") @ExcludeMissing fun _authMethod(): JsonField = authMethod + /** + * 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 [method]. + * + * Unlike [method], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("method") @ExcludeMissing fun _method(): JsonField = method + /** + * Returns the raw JSON value of [params]. + * + * Unlike [params], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("params") @ExcludeMissing fun _params(): JsonField = params + /** + * Returns the raw JSON value of [requestContentType]. + * + * Unlike [requestContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("request_content_type") @ExcludeMissing fun _requestContentType(): JsonField = requestContentType + /** + * Returns the raw JSON value of [responseContentType]. + * + * Unlike [responseContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("response_content_type") @ExcludeMissing fun _responseContentType(): JsonField = responseContentType + /** + * Returns the raw JSON value of [responseMap]. + * + * Unlike [responseMap], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("response_map") @ExcludeMissing fun _responseMap(): JsonField = responseMap + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): RefreshRequest = apply { - if (validated) { - return@apply - } - - endpoint() - authHeaderValueFormat() - authMethod() - method() - params().ifPresent { it.validate() } - requestContentType() - responseContentType() - responseMap().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [RefreshRequest]. */ @JvmStatic fun builder() = Builder() } /** A builder for [RefreshRequest]. */ class Builder internal constructor() { - private var endpoint: JsonField? = null private var authHeaderValueFormat: JsonField = JsonMissing.of() private var authMethod: JsonField = JsonMissing.of() + private var endpoint: JsonField = JsonMissing.of() private var method: JsonField = JsonMissing.of() private var params: JsonField = JsonMissing.of() private var requestContentType: JsonField = JsonMissing.of() @@ -1284,9 +2024,9 @@ private constructor( @JvmSynthetic internal fun from(refreshRequest: RefreshRequest) = apply { - endpoint = refreshRequest.endpoint authHeaderValueFormat = refreshRequest.authHeaderValueFormat authMethod = refreshRequest.authMethod + endpoint = refreshRequest.endpoint method = refreshRequest.method params = refreshRequest.params requestContentType = refreshRequest.requestContentType @@ -1295,34 +2035,76 @@ private constructor( additionalProperties = refreshRequest.additionalProperties.toMutableMap() } - fun endpoint(endpoint: String) = endpoint(JsonField.of(endpoint)) - - fun endpoint(endpoint: JsonField) = apply { this.endpoint = endpoint } - fun authHeaderValueFormat(authHeaderValueFormat: String) = authHeaderValueFormat(JsonField.of(authHeaderValueFormat)) + /** + * Sets [Builder.authHeaderValueFormat] to an arbitrary JSON value. + * + * You should usually call [Builder.authHeaderValueFormat] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun authHeaderValueFormat(authHeaderValueFormat: JsonField) = apply { this.authHeaderValueFormat = authHeaderValueFormat } fun authMethod(authMethod: String) = authMethod(JsonField.of(authMethod)) + /** + * Sets [Builder.authMethod] to an arbitrary JSON value. + * + * You should usually call [Builder.authMethod] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun authMethod(authMethod: JsonField) = apply { this.authMethod = authMethod } + 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 } + fun method(method: String) = method(JsonField.of(method)) + /** + * Sets [Builder.method] to an arbitrary JSON value. + * + * You should usually call [Builder.method] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun method(method: JsonField) = apply { this.method = method } fun params(params: Params) = params(JsonField.of(params)) + /** + * Sets [Builder.params] to an arbitrary JSON value. + * + * You should usually call [Builder.params] with a well-typed [Params] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun params(params: JsonField) = apply { this.params = params } fun requestContentType(requestContentType: RequestContentType) = requestContentType(JsonField.of(requestContentType)) + /** + * Sets [Builder.requestContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.requestContentType] with a well-typed + * [RequestContentType] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun requestContentType(requestContentType: JsonField) = apply { this.requestContentType = requestContentType } @@ -1330,6 +2112,13 @@ private constructor( fun responseContentType(responseContentType: ResponseContentType) = responseContentType(JsonField.of(responseContentType)) + /** + * Sets [Builder.responseContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.responseContentType] with a well-typed + * [ResponseContentType] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun responseContentType(responseContentType: JsonField) = apply { this.responseContentType = responseContentType @@ -1337,6 +2126,13 @@ private constructor( fun responseMap(responseMap: ResponseMap) = responseMap(JsonField.of(responseMap)) + /** + * Sets [Builder.responseMap] to an arbitrary JSON value. + * + * You should usually call [Builder.responseMap] with a well-typed [ResponseMap] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ fun responseMap(responseMap: JsonField) = apply { this.responseMap = responseMap } @@ -1363,46 +2159,84 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [RefreshRequest]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): RefreshRequest = RefreshRequest( - checkRequired("endpoint", endpoint), authHeaderValueFormat, authMethod, + endpoint, method, params, requestContentType, responseContentType, responseMap, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): RefreshRequest = apply { + if (validated) { + return@apply + } + + authHeaderValueFormat() + authMethod() + endpoint() + method() + params().ifPresent { it.validate() } + requestContentType().ifPresent { it.validate() } + responseContentType().ifPresent { it.validate() } + responseMap().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (authHeaderValueFormat.asKnown().isPresent) 1 else 0) + + (if (authMethod.asKnown().isPresent) 1 else 0) + + (if (endpoint.asKnown().isPresent) 1 else 0) + + (if (method.asKnown().isPresent) 1 else 0) + + (params.asKnown().getOrNull()?.validity() ?: 0) + + (requestContentType.asKnown().getOrNull()?.validity() ?: 0) + + (responseContentType.asKnown().getOrNull()?.validity() ?: 0) + + (responseMap.asKnown().getOrNull()?.validity() ?: 0) + class Params @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Params = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Params]. */ @JvmStatic fun builder() = Builder() } @@ -1438,20 +2272,53 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Params]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Params = Params(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): Params = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 /* spotless:off */ other is Params && additionalProperties == other.additionalProperties /* spotless:on */ + return other is Params && additionalProperties == other.additionalProperties } - /* spotless:off */ private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ override fun hashCode(): Int = hashCode @@ -1554,12 +2421,39 @@ private constructor( ArcadeInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): RequestContentType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 /* spotless:off */ other is RequestContentType && value == other.value /* spotless:on */ + return other is RequestContentType && value == other.value } override fun hashCode() = value.hashCode() @@ -1663,12 +2557,39 @@ private constructor( ArcadeInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): ResponseContentType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 /* spotless:off */ other is ResponseContentType && value == other.value /* spotless:on */ + return other is ResponseContentType && value == other.value } override fun hashCode() = value.hashCode() @@ -1676,32 +2597,22 @@ private constructor( override fun toString() = value.toString() } - @NoAutoDetect class ResponseMap @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): ResponseMap = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [ResponseMap]. */ @JvmStatic fun builder() = Builder() } @@ -1737,20 +2648,54 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [ResponseMap]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): ResponseMap = ResponseMap(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): ResponseMap = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 /* spotless:off */ other is ResponseMap && additionalProperties == other.additionalProperties /* spotless:on */ + return other is ResponseMap && + additionalProperties == other.additionalProperties } - /* spotless:off */ private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ override fun hashCode(): Int = hashCode @@ -1762,17 +2707,36 @@ private constructor( return true } - return /* spotless:off */ other is RefreshRequest && endpoint == other.endpoint && authHeaderValueFormat == other.authHeaderValueFormat && authMethod == other.authMethod && method == other.method && params == other.params && requestContentType == other.requestContentType && responseContentType == other.responseContentType && responseMap == other.responseMap && additionalProperties == other.additionalProperties /* spotless:on */ + return other is RefreshRequest && + authHeaderValueFormat == other.authHeaderValueFormat && + authMethod == other.authMethod && + endpoint == other.endpoint && + method == other.method && + params == other.params && + requestContentType == other.requestContentType && + responseContentType == other.responseContentType && + responseMap == other.responseMap && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(endpoint, authHeaderValueFormat, authMethod, method, params, requestContentType, responseContentType, responseMap, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash( + authHeaderValueFormat, + authMethod, + endpoint, + method, + params, + requestContentType, + responseContentType, + responseMap, + additionalProperties, + ) + } override fun hashCode(): Int = hashCode override fun toString() = - "RefreshRequest{endpoint=$endpoint, authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, additionalProperties=$additionalProperties}" + "RefreshRequest{authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, endpoint=$endpoint, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, additionalProperties=$additionalProperties}" } class ScopeDelimiter @@ -1791,17 +2755,17 @@ private constructor( companion object { - @JvmField val Unknown0 = of(",") + @JvmField val Unknown2 = of(",") - @JvmField val Unknown2 = of(" ") + @JvmField val Unknown3 = of(" ") @JvmStatic fun of(value: String) = ScopeDelimiter(JsonField.of(value)) } /** An enum containing [ScopeDelimiter]'s known values. */ enum class Known { - Unknown0, Unknown2, + Unknown3, } /** @@ -1814,8 +2778,8 @@ private constructor( * - It was constructed with an arbitrary value using the [of] method. */ enum class Value { - Unknown0, Unknown2, + Unknown3, /** * An enum member indicating that [ScopeDelimiter] was instantiated with an unknown * value. @@ -1832,8 +2796,8 @@ private constructor( */ fun value(): Value = when (this) { - Unknown0 -> Value.Unknown0 Unknown2 -> Value.Unknown2 + Unknown3 -> Value.Unknown3 else -> Value._UNKNOWN } @@ -1848,8 +2812,8 @@ private constructor( */ fun known(): Known = when (this) { - Unknown0 -> Known.Unknown0 Unknown2 -> Known.Unknown2 + Unknown3 -> Known.Unknown3 else -> throw ArcadeInvalidDataException("Unknown ScopeDelimiter: $value") } @@ -1867,12 +2831,39 @@ private constructor( ArcadeInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): ScopeDelimiter = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 /* spotless:off */ other is ScopeDelimiter && value == other.value /* spotless:on */ + return other is ScopeDelimiter && value == other.value } override fun hashCode() = value.hashCode() @@ -1880,131 +2871,205 @@ private constructor( override fun toString() = value.toString() } - @NoAutoDetect - class TokenIntrospectionRequest - @JsonCreator + class TokenRequest + @JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( - @JsonProperty("endpoint") - @ExcludeMissing - private val endpoint: JsonField = JsonMissing.of(), - @JsonProperty("triggers") - @ExcludeMissing - private val triggers: JsonField = JsonMissing.of(), - @JsonProperty("auth_header_value_format") - @ExcludeMissing - private val authHeaderValueFormat: JsonField = JsonMissing.of(), - @JsonProperty("auth_method") - @ExcludeMissing - private val authMethod: JsonField = JsonMissing.of(), - @JsonProperty("method") - @ExcludeMissing - private val method: JsonField = JsonMissing.of(), - @JsonProperty("params") - @ExcludeMissing - private val params: JsonField = JsonMissing.of(), - @JsonProperty("request_content_type") - @ExcludeMissing - private val requestContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_content_type") - @ExcludeMissing - private val responseContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_map") - @ExcludeMissing - private val responseMap: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val authHeaderValueFormat: JsonField, + private val authMethod: JsonField, + private val endpoint: JsonField, + private val method: JsonField, + private val params: JsonField, + private val requestContentType: JsonField, + private val responseContentType: JsonField, + private val responseMap: JsonField, + private val additionalProperties: MutableMap, ) { - fun endpoint(): String = endpoint.getRequired("endpoint") - - fun triggers(): Triggers = triggers.getRequired("triggers") + @JsonCreator + private constructor( + @JsonProperty("auth_header_value_format") + @ExcludeMissing + authHeaderValueFormat: JsonField = JsonMissing.of(), + @JsonProperty("auth_method") + @ExcludeMissing + authMethod: JsonField = JsonMissing.of(), + @JsonProperty("endpoint") + @ExcludeMissing + endpoint: JsonField = JsonMissing.of(), + @JsonProperty("method") + @ExcludeMissing + method: JsonField = JsonMissing.of(), + @JsonProperty("params") + @ExcludeMissing + params: JsonField = JsonMissing.of(), + @JsonProperty("request_content_type") + @ExcludeMissing + requestContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_content_type") + @ExcludeMissing + responseContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_map") + @ExcludeMissing + responseMap: JsonField = JsonMissing.of(), + ) : this( + authHeaderValueFormat, + authMethod, + endpoint, + method, + params, + requestContentType, + responseContentType, + responseMap, + mutableMapOf(), + ) + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ fun authHeaderValueFormat(): Optional = - Optional.ofNullable(authHeaderValueFormat.getNullable("auth_header_value_format")) + authHeaderValueFormat.getOptional("auth_header_value_format") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authMethod(): Optional = authMethod.getOptional("auth_method") - fun authMethod(): Optional = - Optional.ofNullable(authMethod.getNullable("auth_method")) + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun endpoint(): Optional = endpoint.getOptional("endpoint") - fun method(): Optional = Optional.ofNullable(method.getNullable("method")) + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun method(): Optional = method.getOptional("method") - fun params(): Optional = Optional.ofNullable(params.getNullable("params")) + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun params(): Optional = params.getOptional("params") + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ fun requestContentType(): Optional = - Optional.ofNullable(requestContentType.getNullable("request_content_type")) + requestContentType.getOptional("request_content_type") + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ fun responseContentType(): Optional = - Optional.ofNullable(responseContentType.getNullable("response_content_type")) - - fun responseMap(): Optional = - Optional.ofNullable(responseMap.getNullable("response_map")) - - @JsonProperty("endpoint") @ExcludeMissing fun _endpoint(): JsonField = endpoint + responseContentType.getOptional("response_content_type") - @JsonProperty("triggers") - @ExcludeMissing - fun _triggers(): JsonField = triggers + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun responseMap(): Optional = responseMap.getOptional("response_map") + /** + * Returns the raw JSON value of [authHeaderValueFormat]. + * + * Unlike [authHeaderValueFormat], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("auth_header_value_format") @ExcludeMissing fun _authHeaderValueFormat(): JsonField = authHeaderValueFormat + /** + * Returns the raw JSON value of [authMethod]. + * + * Unlike [authMethod], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("auth_method") @ExcludeMissing fun _authMethod(): JsonField = authMethod + /** + * 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 [method]. + * + * Unlike [method], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("method") @ExcludeMissing fun _method(): JsonField = method + /** + * Returns the raw JSON value of [params]. + * + * Unlike [params], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("params") @ExcludeMissing fun _params(): JsonField = params + /** + * Returns the raw JSON value of [requestContentType]. + * + * Unlike [requestContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("request_content_type") @ExcludeMissing fun _requestContentType(): JsonField = requestContentType + /** + * Returns the raw JSON value of [responseContentType]. + * + * Unlike [responseContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("response_content_type") @ExcludeMissing fun _responseContentType(): JsonField = responseContentType + /** + * Returns the raw JSON value of [responseMap]. + * + * Unlike [responseMap], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("response_map") @ExcludeMissing fun _responseMap(): JsonField = responseMap + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): TokenIntrospectionRequest = apply { - if (validated) { - return@apply - } - - endpoint() - triggers().validate() - authHeaderValueFormat() - authMethod() - method() - params().ifPresent { it.validate() } - requestContentType() - responseContentType() - responseMap().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [TokenRequest]. */ @JvmStatic fun builder() = Builder() } - /** A builder for [TokenIntrospectionRequest]. */ + /** A builder for [TokenRequest]. */ class Builder internal constructor() { - private var endpoint: JsonField? = null - private var triggers: JsonField? = null private var authHeaderValueFormat: JsonField = JsonMissing.of() private var authMethod: JsonField = JsonMissing.of() + private var endpoint: JsonField = JsonMissing.of() private var method: JsonField = JsonMissing.of() private var params: JsonField = JsonMissing.of() private var requestContentType: JsonField = JsonMissing.of() @@ -2013,52 +3078,88 @@ private constructor( private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic - internal fun from(tokenIntrospectionRequest: TokenIntrospectionRequest) = apply { - endpoint = tokenIntrospectionRequest.endpoint - triggers = tokenIntrospectionRequest.triggers - authHeaderValueFormat = tokenIntrospectionRequest.authHeaderValueFormat - authMethod = tokenIntrospectionRequest.authMethod - method = tokenIntrospectionRequest.method - params = tokenIntrospectionRequest.params - requestContentType = tokenIntrospectionRequest.requestContentType - responseContentType = tokenIntrospectionRequest.responseContentType - responseMap = tokenIntrospectionRequest.responseMap - additionalProperties = - tokenIntrospectionRequest.additionalProperties.toMutableMap() + internal fun from(tokenRequest: TokenRequest) = apply { + authHeaderValueFormat = tokenRequest.authHeaderValueFormat + authMethod = tokenRequest.authMethod + endpoint = tokenRequest.endpoint + method = tokenRequest.method + params = tokenRequest.params + requestContentType = tokenRequest.requestContentType + responseContentType = tokenRequest.responseContentType + responseMap = tokenRequest.responseMap + additionalProperties = tokenRequest.additionalProperties.toMutableMap() } - fun endpoint(endpoint: String) = endpoint(JsonField.of(endpoint)) - - fun endpoint(endpoint: JsonField) = apply { this.endpoint = endpoint } - - fun triggers(triggers: Triggers) = triggers(JsonField.of(triggers)) - - fun triggers(triggers: JsonField) = apply { this.triggers = triggers } - fun authHeaderValueFormat(authHeaderValueFormat: String) = authHeaderValueFormat(JsonField.of(authHeaderValueFormat)) + /** + * Sets [Builder.authHeaderValueFormat] to an arbitrary JSON value. + * + * You should usually call [Builder.authHeaderValueFormat] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun authHeaderValueFormat(authHeaderValueFormat: JsonField) = apply { this.authHeaderValueFormat = authHeaderValueFormat } fun authMethod(authMethod: String) = authMethod(JsonField.of(authMethod)) + /** + * Sets [Builder.authMethod] to an arbitrary JSON value. + * + * You should usually call [Builder.authMethod] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun authMethod(authMethod: JsonField) = apply { this.authMethod = authMethod } + 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 } + fun method(method: String) = method(JsonField.of(method)) + /** + * Sets [Builder.method] to an arbitrary JSON value. + * + * You should usually call [Builder.method] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun method(method: JsonField) = apply { this.method = method } fun params(params: Params) = params(JsonField.of(params)) + /** + * Sets [Builder.params] to an arbitrary JSON value. + * + * You should usually call [Builder.params] with a well-typed [Params] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun params(params: JsonField) = apply { this.params = params } fun requestContentType(requestContentType: RequestContentType) = requestContentType(JsonField.of(requestContentType)) + /** + * Sets [Builder.requestContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.requestContentType] with a well-typed + * [RequestContentType] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun requestContentType(requestContentType: JsonField) = apply { this.requestContentType = requestContentType } @@ -2066,6 +3167,13 @@ private constructor( fun responseContentType(responseContentType: ResponseContentType) = responseContentType(JsonField.of(responseContentType)) + /** + * Sets [Builder.responseContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.responseContentType] with a well-typed + * [ResponseContentType] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun responseContentType(responseContentType: JsonField) = apply { this.responseContentType = responseContentType @@ -2073,6 +3181,13 @@ private constructor( fun responseMap(responseMap: ResponseMap) = responseMap(JsonField.of(responseMap)) + /** + * Sets [Builder.responseMap] to an arbitrary JSON value. + * + * You should usually call [Builder.responseMap] with a well-typed [ResponseMap] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ fun responseMap(responseMap: JsonField) = apply { this.responseMap = responseMap } @@ -2099,98 +3214,95 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): TokenIntrospectionRequest = - TokenIntrospectionRequest( - checkRequired("endpoint", endpoint), - checkRequired("triggers", triggers), + /** + * Returns an immutable instance of [TokenRequest]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): TokenRequest = + TokenRequest( authHeaderValueFormat, authMethod, + endpoint, method, params, requestContentType, responseContentType, responseMap, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect - class Triggers - @JsonCreator - private constructor( - @JsonProperty("on_token_grant") - @ExcludeMissing - private val onTokenGrant: JsonField = JsonMissing.of(), - @JsonProperty("on_token_refresh") - @ExcludeMissing - private val onTokenRefresh: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + private var validated: Boolean = false + + fun validate(): TokenRequest = apply { + if (validated) { + return@apply + } - fun onTokenGrant(): Optional = - Optional.ofNullable(onTokenGrant.getNullable("on_token_grant")) + authHeaderValueFormat() + authMethod() + endpoint() + method() + params().ifPresent { it.validate() } + requestContentType().ifPresent { it.validate() } + responseContentType().ifPresent { it.validate() } + responseMap().ifPresent { it.validate() } + validated = true + } - fun onTokenRefresh(): Optional = - Optional.ofNullable(onTokenRefresh.getNullable("on_token_refresh")) + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } - @JsonProperty("on_token_grant") - @ExcludeMissing - fun _onTokenGrant(): JsonField = onTokenGrant + /** + * Returns 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 (authHeaderValueFormat.asKnown().isPresent) 1 else 0) + + (if (authMethod.asKnown().isPresent) 1 else 0) + + (if (endpoint.asKnown().isPresent) 1 else 0) + + (if (method.asKnown().isPresent) 1 else 0) + + (params.asKnown().getOrNull()?.validity() ?: 0) + + (requestContentType.asKnown().getOrNull()?.validity() ?: 0) + + (responseContentType.asKnown().getOrNull()?.validity() ?: 0) + + (responseMap.asKnown().getOrNull()?.validity() ?: 0) - @JsonProperty("on_token_refresh") - @ExcludeMissing - fun _onTokenRefresh(): JsonField = onTokenRefresh + class Params + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Triggers = apply { - if (validated) { - return@apply - } - - onTokenGrant() - onTokenRefresh() - validated = true - } - fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Params]. */ @JvmStatic fun builder() = Builder() } - /** A builder for [Triggers]. */ + /** A builder for [Params]. */ class Builder internal constructor() { - private var onTokenGrant: JsonField = JsonMissing.of() - private var onTokenRefresh: JsonField = JsonMissing.of() private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic - internal fun from(triggers: Triggers) = apply { - onTokenGrant = triggers.onTokenGrant - onTokenRefresh = triggers.onTokenRefresh - additionalProperties = triggers.additionalProperties.toMutableMap() - } - - fun onTokenGrant(onTokenGrant: Boolean) = - onTokenGrant(JsonField.of(onTokenGrant)) - - fun onTokenGrant(onTokenGrant: JsonField) = apply { - this.onTokenGrant = onTokenGrant - } - - fun onTokenRefresh(onTokenRefresh: Boolean) = - onTokenRefresh(JsonField.of(onTokenRefresh)) - - fun onTokenRefresh(onTokenRefresh: JsonField) = apply { - this.onTokenRefresh = onTokenRefresh + internal fun from(params: Params) = apply { + additionalProperties = params.additionalProperties.toMutableMap() } fun additionalProperties(additionalProperties: Map) = apply { @@ -2215,112 +3327,62 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Triggers = - Triggers(onTokenGrant, onTokenRefresh, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Params]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Params = Params(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Params = apply { + if (validated) { + return@apply + } + + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 /* spotless:off */ other is Triggers && onTokenGrant == other.onTokenGrant && onTokenRefresh == other.onTokenRefresh && additionalProperties == other.additionalProperties /* spotless:on */ + return other is Params && additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(onTokenGrant, onTokenRefresh, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } override fun hashCode(): Int = hashCode - override fun toString() = - "Triggers{onTokenGrant=$onTokenGrant, onTokenRefresh=$onTokenRefresh, additionalProperties=$additionalProperties}" + override fun toString() = "Params{additionalProperties=$additionalProperties}" } - @NoAutoDetect - class Params + class RequestContentType @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Params = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Params]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(params: Params) = apply { - additionalProperties = params.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) - } - - fun build(): Params = Params(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Params && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "Params{additionalProperties=$additionalProperties}" - } - - class RequestContentType - @JsonCreator - private constructor(private val value: JsonField) : Enum { + private constructor(private val value: JsonField) : Enum { /** * Returns this class instance's raw value. @@ -2414,12 +3476,39 @@ private constructor( ArcadeInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): RequestContentType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 /* spotless:off */ other is RequestContentType && value == other.value /* spotless:on */ + return other is RequestContentType && value == other.value } override fun hashCode() = value.hashCode() @@ -2523,12 +3612,39 @@ private constructor( ArcadeInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): ResponseContentType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 /* spotless:off */ other is ResponseContentType && value == other.value /* spotless:on */ + return other is ResponseContentType && value == other.value } override fun hashCode() = value.hashCode() @@ -2536,32 +3652,22 @@ private constructor( override fun toString() = value.toString() } - @NoAutoDetect class ResponseMap @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): ResponseMap = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [ResponseMap]. */ @JvmStatic fun builder() = Builder() } @@ -2597,20 +3703,54 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [ResponseMap]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): ResponseMap = ResponseMap(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): ResponseMap = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 /* spotless:off */ other is ResponseMap && additionalProperties == other.additionalProperties /* spotless:on */ + return other is ResponseMap && + additionalProperties == other.additionalProperties } - /* spotless:off */ private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ override fun hashCode(): Int = hashCode @@ -2622,811 +3762,350 @@ private constructor( return true } - return /* spotless:off */ other is TokenIntrospectionRequest && endpoint == other.endpoint && triggers == other.triggers && authHeaderValueFormat == other.authHeaderValueFormat && authMethod == other.authMethod && method == other.method && params == other.params && requestContentType == other.requestContentType && responseContentType == other.responseContentType && responseMap == other.responseMap && additionalProperties == other.additionalProperties /* spotless:on */ + return other is TokenRequest && + authHeaderValueFormat == other.authHeaderValueFormat && + authMethod == other.authMethod && + endpoint == other.endpoint && + method == other.method && + params == other.params && + requestContentType == other.requestContentType && + responseContentType == other.responseContentType && + responseMap == other.responseMap && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(endpoint, triggers, authHeaderValueFormat, authMethod, method, params, requestContentType, responseContentType, responseMap, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash( + authHeaderValueFormat, + authMethod, + endpoint, + method, + params, + requestContentType, + responseContentType, + responseMap, + additionalProperties, + ) + } override fun hashCode(): Int = hashCode override fun toString() = - "TokenIntrospectionRequest{endpoint=$endpoint, triggers=$triggers, authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, additionalProperties=$additionalProperties}" + "TokenRequest{authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, endpoint=$endpoint, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, additionalProperties=$additionalProperties}" } - @NoAutoDetect - class TokenRequest - @JsonCreator + class UserInfoRequest + @JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( - @JsonProperty("endpoint") - @ExcludeMissing - private val endpoint: JsonField = JsonMissing.of(), - @JsonProperty("auth_header_value_format") - @ExcludeMissing - private val authHeaderValueFormat: JsonField = JsonMissing.of(), - @JsonProperty("auth_method") - @ExcludeMissing - private val authMethod: JsonField = JsonMissing.of(), - @JsonProperty("method") - @ExcludeMissing - private val method: JsonField = JsonMissing.of(), - @JsonProperty("params") - @ExcludeMissing - private val params: JsonField = JsonMissing.of(), - @JsonProperty("request_content_type") - @ExcludeMissing - private val requestContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_content_type") - @ExcludeMissing - private val responseContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_map") - @ExcludeMissing - private val responseMap: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val authHeaderValueFormat: JsonField, + private val authMethod: JsonField, + private val endpoint: JsonField, + private val method: JsonField, + private val params: JsonField, + private val requestContentType: JsonField, + private val responseContentType: JsonField, + private val responseMap: JsonField, + private val triggers: JsonField, + private val additionalProperties: MutableMap, ) { - fun endpoint(): String = endpoint.getRequired("endpoint") + @JsonCreator + private constructor( + @JsonProperty("auth_header_value_format") + @ExcludeMissing + authHeaderValueFormat: JsonField = JsonMissing.of(), + @JsonProperty("auth_method") + @ExcludeMissing + authMethod: JsonField = JsonMissing.of(), + @JsonProperty("endpoint") + @ExcludeMissing + endpoint: JsonField = JsonMissing.of(), + @JsonProperty("method") + @ExcludeMissing + method: JsonField = JsonMissing.of(), + @JsonProperty("params") + @ExcludeMissing + params: JsonField = JsonMissing.of(), + @JsonProperty("request_content_type") + @ExcludeMissing + requestContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_content_type") + @ExcludeMissing + responseContentType: JsonField = JsonMissing.of(), + @JsonProperty("response_map") + @ExcludeMissing + responseMap: JsonField = JsonMissing.of(), + @JsonProperty("triggers") + @ExcludeMissing + triggers: JsonField = JsonMissing.of(), + ) : this( + authHeaderValueFormat, + authMethod, + endpoint, + method, + params, + requestContentType, + responseContentType, + responseMap, + triggers, + mutableMapOf(), + ) + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ fun authHeaderValueFormat(): Optional = - Optional.ofNullable(authHeaderValueFormat.getNullable("auth_header_value_format")) + authHeaderValueFormat.getOptional("auth_header_value_format") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authMethod(): Optional = authMethod.getOptional("auth_method") - fun authMethod(): Optional = - Optional.ofNullable(authMethod.getNullable("auth_method")) + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun endpoint(): Optional = endpoint.getOptional("endpoint") - fun method(): Optional = Optional.ofNullable(method.getNullable("method")) + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun method(): Optional = method.getOptional("method") - fun params(): Optional = Optional.ofNullable(params.getNullable("params")) + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun params(): Optional = params.getOptional("params") + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ fun requestContentType(): Optional = - Optional.ofNullable(requestContentType.getNullable("request_content_type")) + requestContentType.getOptional("request_content_type") + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ fun responseContentType(): Optional = - Optional.ofNullable(responseContentType.getNullable("response_content_type")) + responseContentType.getOptional("response_content_type") - fun responseMap(): Optional = - Optional.ofNullable(responseMap.getNullable("response_map")) + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun responseMap(): Optional = responseMap.getOptional("response_map") - @JsonProperty("endpoint") @ExcludeMissing fun _endpoint(): JsonField = endpoint + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun triggers(): Optional = triggers.getOptional("triggers") + /** + * Returns the raw JSON value of [authHeaderValueFormat]. + * + * Unlike [authHeaderValueFormat], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("auth_header_value_format") @ExcludeMissing fun _authHeaderValueFormat(): JsonField = authHeaderValueFormat + /** + * Returns the raw JSON value of [authMethod]. + * + * Unlike [authMethod], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("auth_method") @ExcludeMissing fun _authMethod(): JsonField = authMethod + /** + * 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 [method]. + * + * Unlike [method], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("method") @ExcludeMissing fun _method(): JsonField = method + /** + * Returns the raw JSON value of [params]. + * + * Unlike [params], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("params") @ExcludeMissing fun _params(): JsonField = params + /** + * Returns the raw JSON value of [requestContentType]. + * + * Unlike [requestContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("request_content_type") @ExcludeMissing fun _requestContentType(): JsonField = requestContentType + /** + * Returns the raw JSON value of [responseContentType]. + * + * Unlike [responseContentType], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("response_content_type") @ExcludeMissing fun _responseContentType(): JsonField = responseContentType + /** + * Returns the raw JSON value of [responseMap]. + * + * Unlike [responseMap], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("response_map") @ExcludeMissing fun _responseMap(): JsonField = responseMap - @JsonAnyGetter + /** + * Returns the raw JSON value of [triggers]. + * + * Unlike [triggers], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("triggers") @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): TokenRequest = apply { - if (validated) { - return@apply - } + fun _triggers(): JsonField = triggers - endpoint() - authHeaderValueFormat() - authMethod() - method() - params().ifPresent { it.validate() } - requestContentType() - responseContentType() - responseMap().ifPresent { it.validate() } - validated = true + @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 [UserInfoRequest]. */ @JvmStatic fun builder() = Builder() } - /** A builder for [TokenRequest]. */ + /** A builder for [UserInfoRequest]. */ class Builder internal constructor() { - private var endpoint: JsonField? = null - private var authHeaderValueFormat: JsonField = JsonMissing.of() - private var authMethod: JsonField = JsonMissing.of() - private var method: JsonField = JsonMissing.of() - private var params: JsonField = JsonMissing.of() - private var requestContentType: JsonField = JsonMissing.of() - private var responseContentType: JsonField = JsonMissing.of() - private var responseMap: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(tokenRequest: TokenRequest) = apply { - endpoint = tokenRequest.endpoint - authHeaderValueFormat = tokenRequest.authHeaderValueFormat - authMethod = tokenRequest.authMethod - method = tokenRequest.method - params = tokenRequest.params - requestContentType = tokenRequest.requestContentType - responseContentType = tokenRequest.responseContentType - responseMap = tokenRequest.responseMap - additionalProperties = tokenRequest.additionalProperties.toMutableMap() - } - - fun endpoint(endpoint: String) = endpoint(JsonField.of(endpoint)) - - fun endpoint(endpoint: JsonField) = apply { this.endpoint = endpoint } - - fun authHeaderValueFormat(authHeaderValueFormat: String) = - authHeaderValueFormat(JsonField.of(authHeaderValueFormat)) - - fun authHeaderValueFormat(authHeaderValueFormat: JsonField) = apply { - this.authHeaderValueFormat = authHeaderValueFormat - } - - fun authMethod(authMethod: String) = authMethod(JsonField.of(authMethod)) - - fun authMethod(authMethod: JsonField) = apply { - this.authMethod = authMethod - } - - fun method(method: String) = method(JsonField.of(method)) - - fun method(method: JsonField) = apply { this.method = method } - - fun params(params: Params) = params(JsonField.of(params)) - - fun params(params: JsonField) = apply { this.params = params } - - fun requestContentType(requestContentType: RequestContentType) = - requestContentType(JsonField.of(requestContentType)) - - fun requestContentType(requestContentType: JsonField) = apply { - this.requestContentType = requestContentType - } - - fun responseContentType(responseContentType: ResponseContentType) = - responseContentType(JsonField.of(responseContentType)) - - fun responseContentType(responseContentType: JsonField) = - apply { - this.responseContentType = responseContentType - } - - fun responseMap(responseMap: ResponseMap) = responseMap(JsonField.of(responseMap)) - - fun responseMap(responseMap: JsonField) = apply { - this.responseMap = responseMap - } - - 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) - } - - fun build(): TokenRequest = - TokenRequest( - checkRequired("endpoint", endpoint), - authHeaderValueFormat, - authMethod, - method, - params, - requestContentType, - responseContentType, - responseMap, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class Params - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Params = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Params]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(params: Params) = apply { - additionalProperties = params.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) - } - - fun build(): Params = Params(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Params && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "Params{additionalProperties=$additionalProperties}" - } - - class RequestContentType - @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 APPLICATION_X_WWW_FORM_URLENCODED = of("application/x-www-form-urlencoded") - - @JvmField val APPLICATION_JSON = of("application/json") - - @JvmStatic fun of(value: String) = RequestContentType(JsonField.of(value)) - } - - /** An enum containing [RequestContentType]'s known values. */ - enum class Known { - APPLICATION_X_WWW_FORM_URLENCODED, - APPLICATION_JSON, - } - - /** - * An enum containing [RequestContentType]'s known values, as well as an [_UNKNOWN] - * member. - * - * An instance of [RequestContentType] 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 { - APPLICATION_X_WWW_FORM_URLENCODED, - APPLICATION_JSON, - /** - * An enum member indicating that [RequestContentType] 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) { - APPLICATION_X_WWW_FORM_URLENCODED -> Value.APPLICATION_X_WWW_FORM_URLENCODED - APPLICATION_JSON -> Value.APPLICATION_JSON - 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 ArcadeInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - APPLICATION_X_WWW_FORM_URLENCODED -> Known.APPLICATION_X_WWW_FORM_URLENCODED - APPLICATION_JSON -> Known.APPLICATION_JSON - else -> - throw ArcadeInvalidDataException("Unknown RequestContentType: $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 ArcadeInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - ArcadeInvalidDataException("Value is not a String") - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is RequestContentType && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - class ResponseContentType - @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 APPLICATION_X_WWW_FORM_URLENCODED = of("application/x-www-form-urlencoded") - - @JvmField val APPLICATION_JSON = of("application/json") - - @JvmStatic fun of(value: String) = ResponseContentType(JsonField.of(value)) - } - - /** An enum containing [ResponseContentType]'s known values. */ - enum class Known { - APPLICATION_X_WWW_FORM_URLENCODED, - APPLICATION_JSON, - } - - /** - * An enum containing [ResponseContentType]'s known values, as well as an [_UNKNOWN] - * member. - * - * An instance of [ResponseContentType] 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 { - APPLICATION_X_WWW_FORM_URLENCODED, - APPLICATION_JSON, - /** - * An enum member indicating that [ResponseContentType] 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) { - APPLICATION_X_WWW_FORM_URLENCODED -> Value.APPLICATION_X_WWW_FORM_URLENCODED - APPLICATION_JSON -> Value.APPLICATION_JSON - 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 ArcadeInvalidDataException if this class instance's value is a not a - * known member. - */ - fun known(): Known = - when (this) { - APPLICATION_X_WWW_FORM_URLENCODED -> Known.APPLICATION_X_WWW_FORM_URLENCODED - APPLICATION_JSON -> Known.APPLICATION_JSON - else -> - throw ArcadeInvalidDataException("Unknown ResponseContentType: $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 ArcadeInvalidDataException if this class instance's value does not have - * the expected primitive type. - */ - fun asString(): String = - _value().asString().orElseThrow { - ArcadeInvalidDataException("Value is not a String") - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ResponseContentType && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - @NoAutoDetect - class ResponseMap - @JsonCreator - private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() - ) { - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ResponseMap = apply { - if (validated) { - return@apply - } - - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ResponseMap]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(responseMap: ResponseMap) = apply { - additionalProperties = responseMap.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) - } - - fun build(): ResponseMap = ResponseMap(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is ResponseMap && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "ResponseMap{additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is TokenRequest && endpoint == other.endpoint && authHeaderValueFormat == other.authHeaderValueFormat && authMethod == other.authMethod && method == other.method && params == other.params && requestContentType == other.requestContentType && responseContentType == other.responseContentType && responseMap == other.responseMap && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(endpoint, authHeaderValueFormat, authMethod, method, params, requestContentType, responseContentType, responseMap, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "TokenRequest{endpoint=$endpoint, authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class UserInfoRequest - @JsonCreator - private constructor( - @JsonProperty("endpoint") - @ExcludeMissing - private val endpoint: JsonField = JsonMissing.of(), - @JsonProperty("triggers") - @ExcludeMissing - private val triggers: JsonField = JsonMissing.of(), - @JsonProperty("auth_header_value_format") - @ExcludeMissing - private val authHeaderValueFormat: JsonField = JsonMissing.of(), - @JsonProperty("auth_method") - @ExcludeMissing - private val authMethod: JsonField = JsonMissing.of(), - @JsonProperty("method") - @ExcludeMissing - private val method: JsonField = JsonMissing.of(), - @JsonProperty("params") - @ExcludeMissing - private val params: JsonField = JsonMissing.of(), - @JsonProperty("request_content_type") - @ExcludeMissing - private val requestContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_content_type") - @ExcludeMissing - private val responseContentType: JsonField = JsonMissing.of(), - @JsonProperty("response_map") - @ExcludeMissing - private val responseMap: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun endpoint(): String = endpoint.getRequired("endpoint") - - fun triggers(): Triggers = triggers.getRequired("triggers") - - fun authHeaderValueFormat(): Optional = - Optional.ofNullable(authHeaderValueFormat.getNullable("auth_header_value_format")) - - fun authMethod(): Optional = - Optional.ofNullable(authMethod.getNullable("auth_method")) - - fun method(): Optional = Optional.ofNullable(method.getNullable("method")) - - fun params(): Optional = Optional.ofNullable(params.getNullable("params")) - - fun requestContentType(): Optional = - Optional.ofNullable(requestContentType.getNullable("request_content_type")) - - fun responseContentType(): Optional = - Optional.ofNullable(responseContentType.getNullable("response_content_type")) - - fun responseMap(): Optional = - Optional.ofNullable(responseMap.getNullable("response_map")) - - @JsonProperty("endpoint") @ExcludeMissing fun _endpoint(): JsonField = endpoint - - @JsonProperty("triggers") - @ExcludeMissing - fun _triggers(): JsonField = triggers - - @JsonProperty("auth_header_value_format") - @ExcludeMissing - fun _authHeaderValueFormat(): JsonField = authHeaderValueFormat - - @JsonProperty("auth_method") - @ExcludeMissing - fun _authMethod(): JsonField = authMethod - - @JsonProperty("method") @ExcludeMissing fun _method(): JsonField = method - - @JsonProperty("params") @ExcludeMissing fun _params(): JsonField = params - - @JsonProperty("request_content_type") - @ExcludeMissing - fun _requestContentType(): JsonField = requestContentType - - @JsonProperty("response_content_type") - @ExcludeMissing - fun _responseContentType(): JsonField = responseContentType - - @JsonProperty("response_map") - @ExcludeMissing - fun _responseMap(): JsonField = responseMap - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): UserInfoRequest = apply { - if (validated) { - return@apply - } - - endpoint() - triggers().validate() - authHeaderValueFormat() - authMethod() - method() - params().ifPresent { it.validate() } - requestContentType() - responseContentType() - responseMap().ifPresent { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [UserInfoRequest]. */ - class Builder internal constructor() { - - private var endpoint: JsonField? = null - private var triggers: JsonField? = null private var authHeaderValueFormat: JsonField = JsonMissing.of() private var authMethod: JsonField = JsonMissing.of() + private var endpoint: JsonField = JsonMissing.of() private var method: JsonField = JsonMissing.of() private var params: JsonField = JsonMissing.of() private var requestContentType: JsonField = JsonMissing.of() private var responseContentType: JsonField = JsonMissing.of() private var responseMap: JsonField = JsonMissing.of() + private var triggers: JsonField = JsonMissing.of() private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic internal fun from(userInfoRequest: UserInfoRequest) = apply { - endpoint = userInfoRequest.endpoint - triggers = userInfoRequest.triggers authHeaderValueFormat = userInfoRequest.authHeaderValueFormat authMethod = userInfoRequest.authMethod + endpoint = userInfoRequest.endpoint method = userInfoRequest.method params = userInfoRequest.params requestContentType = userInfoRequest.requestContentType responseContentType = userInfoRequest.responseContentType responseMap = userInfoRequest.responseMap + triggers = userInfoRequest.triggers additionalProperties = userInfoRequest.additionalProperties.toMutableMap() } - fun endpoint(endpoint: String) = endpoint(JsonField.of(endpoint)) - - fun endpoint(endpoint: JsonField) = apply { this.endpoint = endpoint } - - fun triggers(triggers: Triggers) = triggers(JsonField.of(triggers)) - - fun triggers(triggers: JsonField) = apply { this.triggers = triggers } - fun authHeaderValueFormat(authHeaderValueFormat: String) = authHeaderValueFormat(JsonField.of(authHeaderValueFormat)) + /** + * Sets [Builder.authHeaderValueFormat] to an arbitrary JSON value. + * + * You should usually call [Builder.authHeaderValueFormat] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun authHeaderValueFormat(authHeaderValueFormat: JsonField) = apply { this.authHeaderValueFormat = authHeaderValueFormat } fun authMethod(authMethod: String) = authMethod(JsonField.of(authMethod)) + /** + * Sets [Builder.authMethod] to an arbitrary JSON value. + * + * You should usually call [Builder.authMethod] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun authMethod(authMethod: JsonField) = apply { this.authMethod = authMethod } + 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 } + fun method(method: String) = method(JsonField.of(method)) + /** + * Sets [Builder.method] to an arbitrary JSON value. + * + * You should usually call [Builder.method] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun method(method: JsonField) = apply { this.method = method } fun params(params: Params) = params(JsonField.of(params)) + /** + * Sets [Builder.params] to an arbitrary JSON value. + * + * You should usually call [Builder.params] with a well-typed [Params] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun params(params: JsonField) = apply { this.params = params } fun requestContentType(requestContentType: RequestContentType) = requestContentType(JsonField.of(requestContentType)) + /** + * Sets [Builder.requestContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.requestContentType] with a well-typed + * [RequestContentType] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun requestContentType(requestContentType: JsonField) = apply { this.requestContentType = requestContentType } @@ -3434,6 +4113,13 @@ private constructor( fun responseContentType(responseContentType: ResponseContentType) = responseContentType(JsonField.of(responseContentType)) + /** + * Sets [Builder.responseContentType] to an arbitrary JSON value. + * + * You should usually call [Builder.responseContentType] with a well-typed + * [ResponseContentType] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun responseContentType(responseContentType: JsonField) = apply { this.responseContentType = responseContentType @@ -3441,10 +4127,28 @@ private constructor( fun responseMap(responseMap: ResponseMap) = responseMap(JsonField.of(responseMap)) + /** + * Sets [Builder.responseMap] to an arbitrary JSON value. + * + * You should usually call [Builder.responseMap] with a well-typed [ResponseMap] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ fun responseMap(responseMap: JsonField) = apply { this.responseMap = responseMap } + fun triggers(triggers: Triggers) = triggers(JsonField.of(triggers)) + + /** + * Sets [Builder.triggers] to an arbitrary JSON value. + * + * You should usually call [Builder.triggers] with a well-typed [Triggers] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun triggers(triggers: JsonField) = apply { this.triggers = triggers } + fun additionalProperties(additionalProperties: Map) = apply { this.additionalProperties.clear() putAllAdditionalProperties(additionalProperties) @@ -3467,170 +4171,87 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [UserInfoRequest]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): UserInfoRequest = UserInfoRequest( - checkRequired("endpoint", endpoint), - checkRequired("triggers", triggers), authHeaderValueFormat, authMethod, + endpoint, method, params, requestContentType, - responseContentType, - responseMap, - additionalProperties.toImmutable(), - ) - } - - @NoAutoDetect - class Triggers - @JsonCreator - private constructor( - @JsonProperty("on_token_grant") - @ExcludeMissing - private val onTokenGrant: JsonField = JsonMissing.of(), - @JsonProperty("on_token_refresh") - @ExcludeMissing - private val onTokenRefresh: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun onTokenGrant(): Optional = - Optional.ofNullable(onTokenGrant.getNullable("on_token_grant")) - - fun onTokenRefresh(): Optional = - Optional.ofNullable(onTokenRefresh.getNullable("on_token_refresh")) - - @JsonProperty("on_token_grant") - @ExcludeMissing - fun _onTokenGrant(): JsonField = onTokenGrant - - @JsonProperty("on_token_refresh") - @ExcludeMissing - fun _onTokenRefresh(): JsonField = onTokenRefresh - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Triggers = apply { - if (validated) { - return@apply - } - - onTokenGrant() - onTokenRefresh() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Triggers]. */ - class Builder internal constructor() { - - private var onTokenGrant: JsonField = JsonMissing.of() - private var onTokenRefresh: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(triggers: Triggers) = apply { - onTokenGrant = triggers.onTokenGrant - onTokenRefresh = triggers.onTokenRefresh - additionalProperties = triggers.additionalProperties.toMutableMap() - } - - fun onTokenGrant(onTokenGrant: Boolean) = - onTokenGrant(JsonField.of(onTokenGrant)) - - fun onTokenGrant(onTokenGrant: JsonField) = apply { - this.onTokenGrant = onTokenGrant - } - - fun onTokenRefresh(onTokenRefresh: Boolean) = - onTokenRefresh(JsonField.of(onTokenRefresh)) - - fun onTokenRefresh(onTokenRefresh: JsonField) = apply { - this.onTokenRefresh = onTokenRefresh - } - - 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) - } + responseContentType, + responseMap, + triggers, + additionalProperties.toMutableMap(), + ) + } - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } + private var validated: Boolean = false - fun build(): Triggers = - Triggers(onTokenGrant, onTokenRefresh, additionalProperties.toImmutable()) + fun validate(): UserInfoRequest = apply { + if (validated) { + return@apply } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } + authHeaderValueFormat() + authMethod() + endpoint() + method() + params().ifPresent { it.validate() } + requestContentType().ifPresent { it.validate() } + responseContentType().ifPresent { it.validate() } + responseMap().ifPresent { it.validate() } + triggers().ifPresent { it.validate() } + validated = true + } - return /* spotless:off */ other is Triggers && onTokenGrant == other.onTokenGrant && onTokenRefresh == other.onTokenRefresh && additionalProperties == other.additionalProperties /* spotless:on */ + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(onTokenGrant, onTokenRefresh, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Triggers{onTokenGrant=$onTokenGrant, onTokenRefresh=$onTokenRefresh, additionalProperties=$additionalProperties}" - } + /** + * Returns 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 (authHeaderValueFormat.asKnown().isPresent) 1 else 0) + + (if (authMethod.asKnown().isPresent) 1 else 0) + + (if (endpoint.asKnown().isPresent) 1 else 0) + + (if (method.asKnown().isPresent) 1 else 0) + + (params.asKnown().getOrNull()?.validity() ?: 0) + + (requestContentType.asKnown().getOrNull()?.validity() ?: 0) + + (responseContentType.asKnown().getOrNull()?.validity() ?: 0) + + (responseMap.asKnown().getOrNull()?.validity() ?: 0) + + (triggers.asKnown().getOrNull()?.validity() ?: 0) - @NoAutoDetect class Params @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Params = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Params]. */ @JvmStatic fun builder() = Builder() } @@ -3666,20 +4287,53 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Params]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Params = Params(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): Params = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 /* spotless:off */ other is Params && additionalProperties == other.additionalProperties /* spotless:on */ + return other is Params && additionalProperties == other.additionalProperties } - /* spotless:off */ private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ override fun hashCode(): Int = hashCode @@ -3782,12 +4436,39 @@ private constructor( ArcadeInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): RequestContentType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 /* spotless:off */ other is RequestContentType && value == other.value /* spotless:on */ + return other is RequestContentType && value == other.value } override fun hashCode() = value.hashCode() @@ -3891,12 +4572,39 @@ private constructor( ArcadeInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): ResponseContentType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 /* spotless:off */ other is ResponseContentType && value == other.value /* spotless:on */ + return other is ResponseContentType && value == other.value } override fun hashCode() = value.hashCode() @@ -3904,18 +4612,65 @@ private constructor( override fun toString() = value.toString() } - @NoAutoDetect class ResponseMap @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @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 [ResponseMap]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ResponseMap]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(responseMap: ResponseMap) = apply { + additionalProperties = responseMap.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 [ResponseMap]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ResponseMap = ResponseMap(additionalProperties.toImmutable()) + } + private var validated: Boolean = false fun validate(): ResponseMap = apply { @@ -3926,21 +4681,151 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 ResponseMap && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ResponseMap{additionalProperties=$additionalProperties}" + } + + class Triggers + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val onTokenGrant: JsonField, + private val onTokenRefresh: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("on_token_grant") + @ExcludeMissing + onTokenGrant: JsonField = JsonMissing.of(), + @JsonProperty("on_token_refresh") + @ExcludeMissing + onTokenRefresh: JsonField = JsonMissing.of(), + ) : this(onTokenGrant, onTokenRefresh, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun onTokenGrant(): Optional = onTokenGrant.getOptional("on_token_grant") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun onTokenRefresh(): Optional = + onTokenRefresh.getOptional("on_token_refresh") + + /** + * Returns the raw JSON value of [onTokenGrant]. + * + * Unlike [onTokenGrant], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("on_token_grant") + @ExcludeMissing + fun _onTokenGrant(): JsonField = onTokenGrant + + /** + * Returns the raw JSON value of [onTokenRefresh]. + * + * Unlike [onTokenRefresh], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("on_token_refresh") + @ExcludeMissing + fun _onTokenRefresh(): JsonField = onTokenRefresh + + @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 [Triggers]. */ @JvmStatic fun builder() = Builder() } - /** A builder for [ResponseMap]. */ + /** A builder for [Triggers]. */ class Builder internal constructor() { + private var onTokenGrant: JsonField = JsonMissing.of() + private var onTokenRefresh: JsonField = JsonMissing.of() private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic - internal fun from(responseMap: ResponseMap) = apply { - additionalProperties = responseMap.additionalProperties.toMutableMap() + internal fun from(triggers: Triggers) = apply { + onTokenGrant = triggers.onTokenGrant + onTokenRefresh = triggers.onTokenRefresh + additionalProperties = triggers.additionalProperties.toMutableMap() + } + + fun onTokenGrant(onTokenGrant: Boolean) = + onTokenGrant(JsonField.of(onTokenGrant)) + + /** + * Sets [Builder.onTokenGrant] to an arbitrary JSON value. + * + * You should usually call [Builder.onTokenGrant] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun onTokenGrant(onTokenGrant: JsonField) = apply { + this.onTokenGrant = onTokenGrant + } + + fun onTokenRefresh(onTokenRefresh: Boolean) = + onTokenRefresh(JsonField.of(onTokenRefresh)) + + /** + * Sets [Builder.onTokenRefresh] to an arbitrary JSON value. + * + * You should usually call [Builder.onTokenRefresh] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun onTokenRefresh(onTokenRefresh: JsonField) = apply { + this.onTokenRefresh = onTokenRefresh } fun additionalProperties(additionalProperties: Map) = apply { @@ -3965,24 +4850,65 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): ResponseMap = ResponseMap(additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Triggers]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Triggers = + Triggers(onTokenGrant, onTokenRefresh, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Triggers = apply { + if (validated) { + return@apply + } + + onTokenGrant() + onTokenRefresh() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (onTokenGrant.asKnown().isPresent) 1 else 0) + + (if (onTokenRefresh.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is ResponseMap && additionalProperties == other.additionalProperties /* spotless:on */ + return other is Triggers && + onTokenGrant == other.onTokenGrant && + onTokenRefresh == other.onTokenRefresh && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash(onTokenGrant, onTokenRefresh, additionalProperties) + } override fun hashCode(): Int = hashCode - override fun toString() = "ResponseMap{additionalProperties=$additionalProperties}" + override fun toString() = + "Triggers{onTokenGrant=$onTokenGrant, onTokenRefresh=$onTokenRefresh, additionalProperties=$additionalProperties}" } override fun equals(other: Any?): Boolean { @@ -3990,17 +4916,38 @@ private constructor( return true } - return /* spotless:off */ other is UserInfoRequest && endpoint == other.endpoint && triggers == other.triggers && authHeaderValueFormat == other.authHeaderValueFormat && authMethod == other.authMethod && method == other.method && params == other.params && requestContentType == other.requestContentType && responseContentType == other.responseContentType && responseMap == other.responseMap && additionalProperties == other.additionalProperties /* spotless:on */ + return other is UserInfoRequest && + authHeaderValueFormat == other.authHeaderValueFormat && + authMethod == other.authMethod && + endpoint == other.endpoint && + method == other.method && + params == other.params && + requestContentType == other.requestContentType && + responseContentType == other.responseContentType && + responseMap == other.responseMap && + triggers == other.triggers && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(endpoint, triggers, authHeaderValueFormat, authMethod, method, params, requestContentType, responseContentType, responseMap, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash( + authHeaderValueFormat, + authMethod, + endpoint, + method, + params, + requestContentType, + responseContentType, + responseMap, + triggers, + additionalProperties, + ) + } override fun hashCode(): Int = hashCode override fun toString() = - "UserInfoRequest{endpoint=$endpoint, triggers=$triggers, authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, additionalProperties=$additionalProperties}" + "UserInfoRequest{authHeaderValueFormat=$authHeaderValueFormat, authMethod=$authMethod, endpoint=$endpoint, method=$method, params=$params, requestContentType=$requestContentType, responseContentType=$responseContentType, responseMap=$responseMap, triggers=$triggers, additionalProperties=$additionalProperties}" } override fun equals(other: Any?): Boolean { @@ -4008,17 +4955,36 @@ private constructor( return true } - return /* spotless:off */ other is Oauth2 && clientId == other.clientId && authorizeRequest == other.authorizeRequest && clientSecret == other.clientSecret && pkce == other.pkce && refreshRequest == other.refreshRequest && scopeDelimiter == other.scopeDelimiter && tokenIntrospectionRequest == other.tokenIntrospectionRequest && tokenRequest == other.tokenRequest && userInfoRequest == other.userInfoRequest && additionalProperties == other.additionalProperties /* spotless:on */ + return other is Oauth2 && + authorizeRequest == other.authorizeRequest && + clientId == other.clientId && + clientSecret == other.clientSecret && + pkce == other.pkce && + refreshRequest == other.refreshRequest && + scopeDelimiter == other.scopeDelimiter && + tokenRequest == other.tokenRequest && + userInfoRequest == other.userInfoRequest && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(clientId, authorizeRequest, clientSecret, pkce, refreshRequest, scopeDelimiter, tokenIntrospectionRequest, tokenRequest, userInfoRequest, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash( + authorizeRequest, + clientId, + clientSecret, + pkce, + refreshRequest, + scopeDelimiter, + tokenRequest, + userInfoRequest, + additionalProperties, + ) + } override fun hashCode(): Int = hashCode override fun toString() = - "Oauth2{clientId=$clientId, authorizeRequest=$authorizeRequest, clientSecret=$clientSecret, pkce=$pkce, refreshRequest=$refreshRequest, scopeDelimiter=$scopeDelimiter, tokenIntrospectionRequest=$tokenIntrospectionRequest, tokenRequest=$tokenRequest, userInfoRequest=$userInfoRequest, additionalProperties=$additionalProperties}" + "Oauth2{authorizeRequest=$authorizeRequest, clientId=$clientId, clientSecret=$clientSecret, pkce=$pkce, refreshRequest=$refreshRequest, scopeDelimiter=$scopeDelimiter, tokenRequest=$tokenRequest, userInfoRequest=$userInfoRequest, additionalProperties=$additionalProperties}" } override fun equals(other: Any?): Boolean { @@ -4026,15 +4992,22 @@ private constructor( return true } - return /* spotless:off */ other is AuthProviderCreateRequest && id == other.id && description == other.description && externalId == other.externalId && oauth2 == other.oauth2 && providerId == other.providerId && status == other.status && type == other.type && additionalProperties == other.additionalProperties /* spotless:on */ + return other is AuthProviderUpdateRequest && + id == other.id && + description == other.description && + oauth2 == other.oauth2 && + providerId == other.providerId && + status == other.status && + type == other.type && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(id, description, externalId, oauth2, providerId, status, type, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash(id, description, oauth2, providerId, status, type, additionalProperties) + } override fun hashCode(): Int = hashCode override fun toString() = - "AuthProviderCreateRequest{id=$id, description=$description, externalId=$externalId, oauth2=$oauth2, providerId=$providerId, status=$status, type=$type, additionalProperties=$additionalProperties}" + "AuthProviderUpdateRequest{id=$id, description=$description, oauth2=$oauth2, providerId=$providerId, status=$status, type=$type, additionalProperties=$additionalProperties}" } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminSecretCreateParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/secrets/SecretCreateParams.kt similarity index 55% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/AdminSecretCreateParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/admin/secrets/SecretCreateParams.kt index 2638b6d..a52b828 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminSecretCreateParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/secrets/SecretCreateParams.kt @@ -1,6 +1,6 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.admin.secrets import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter @@ -10,176 +10,77 @@ import dev.arcade.core.ExcludeMissing import dev.arcade.core.JsonField import dev.arcade.core.JsonMissing import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params import dev.arcade.core.checkRequired import dev.arcade.core.http.Headers import dev.arcade.core.http.QueryParams -import dev.arcade.core.immutableEmptyMap -import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Create or update a secret */ -class AdminSecretCreateParams +class SecretCreateParams private constructor( - private val secretKey: String, + private val secretKey: String?, private val body: Body, private val additionalHeaders: Headers, private val additionalQueryParams: QueryParams, ) : Params { - fun secretKey(): String = secretKey + fun secretKey(): Optional = Optional.ofNullable(secretKey) + /** + * @throws ArcadeInvalidDataException 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 = body.value() + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun description(): Optional = body.description() + /** + * Returns the raw JSON value of [value]. + * + * Unlike [value], this method doesn't throw if the JSON field has an unexpected type. + */ fun _value(): JsonField = body._value() + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ fun _description(): JsonField = body._description() 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 - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> secretKey - else -> "" - } - } - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("value") - @ExcludeMissing - private val value: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun value(): String = value.getRequired("value") - - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) - - @JsonProperty("value") @ExcludeMissing fun _value(): JsonField = value - - @JsonProperty("description") - @ExcludeMissing - fun _description(): JsonField = description - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - value() - description() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var value: JsonField? = null - private var description: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - value = body.value - description = body.description - additionalProperties = body.additionalProperties.toMutableMap() - } - - fun value(value: String) = value(JsonField.of(value)) - - fun value(value: JsonField) = apply { this.value = value } - - fun description(description: String) = description(JsonField.of(description)) - - fun description(description: JsonField) = apply { - this.description = description - } - - 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) - } - - fun build(): Body = - Body(checkRequired("value", value), description, additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && value == other.value && description == other.description && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(value, description, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{value=$value, description=$description, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [SecretCreateParams]. + * + * The following fields are required: + * ```java + * .value() + * ``` + */ @JvmStatic fun builder() = Builder() } - /** A builder for [AdminSecretCreateParams]. */ - @NoAutoDetect + /** A builder for [SecretCreateParams]. */ class Builder internal constructor() { private var secretKey: String? = null @@ -188,21 +89,47 @@ private constructor( private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @JvmSynthetic - internal fun from(adminSecretCreateParams: AdminSecretCreateParams) = apply { - secretKey = adminSecretCreateParams.secretKey - body = adminSecretCreateParams.body.toBuilder() - additionalHeaders = adminSecretCreateParams.additionalHeaders.toBuilder() - additionalQueryParams = adminSecretCreateParams.additionalQueryParams.toBuilder() + internal fun from(secretCreateParams: SecretCreateParams) = apply { + secretKey = secretCreateParams.secretKey + body = secretCreateParams.body.toBuilder() + additionalHeaders = secretCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = secretCreateParams.additionalQueryParams.toBuilder() } - fun secretKey(secretKey: String) = apply { this.secretKey = secretKey } + fun secretKey(secretKey: String?) = apply { this.secretKey = secretKey } + + /** Alias for calling [Builder.secretKey] with `secretKey.orElse(null)`. */ + fun secretKey(secretKey: Optional) = secretKey(secretKey.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: + * - [value] + * - [description] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } fun value(value: String) = apply { body.value(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 { body.value(value) } fun description(description: String) = apply { body.description(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 { body.description(description) } fun additionalBodyProperties(additionalBodyProperties: Map) = apply { @@ -322,25 +249,250 @@ private constructor( additionalQueryParams.removeAll(keys) } - fun build(): AdminSecretCreateParams = - AdminSecretCreateParams( - checkRequired("secretKey", secretKey), + /** + * Returns an immutable instance of [SecretCreateParams]. + * + * 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(): SecretCreateParams = + SecretCreateParams( + secretKey, body.build(), additionalHeaders.build(), additionalQueryParams.build(), ) } + fun _body(): Body = body + + fun _pathParam(index: Int): String = + when (index) { + 0 -> secretKey ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val value: JsonField, + private val description: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("value") @ExcludeMissing value: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + ) : this(value, description, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException 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.getRequired("value") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + + /** + * 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 + + /** + * 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 + + @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 + * .value() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var value: JsonField? = null + private var description: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + value = body.value + description = body.description + additionalProperties = body.additionalProperties.toMutableMap() + } + + 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 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 + } + + 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 + * .value() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("value", value), + description, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + value() + description() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + value == other.value && + description == other.description && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(value, description, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{value=$value, description=$description, additionalProperties=$additionalProperties}" + } + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is AdminSecretCreateParams && secretKey == other.secretKey && body == other.body && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is SecretCreateParams && + secretKey == other.secretKey && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(secretKey, body, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(secretKey, body, additionalHeaders, additionalQueryParams) override fun toString() = - "AdminSecretCreateParams{secretKey=$secretKey, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" + "SecretCreateParams{secretKey=$secretKey, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminSecretDeleteParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/secrets/SecretDeleteParams.kt similarity index 73% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/AdminSecretDeleteParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/admin/secrets/SecretDeleteParams.kt index f2cc1a5..a2321e7 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminSecretDeleteParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/secrets/SecretDeleteParams.kt @@ -1,58 +1,47 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.admin.secrets import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params -import dev.arcade.core.checkRequired import dev.arcade.core.http.Headers import dev.arcade.core.http.QueryParams import dev.arcade.core.toImmutable import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Delete a secret by its ID */ -class AdminSecretDeleteParams +class SecretDeleteParams private constructor( - private val secretId: String, + private val secretId: String?, private val additionalHeaders: Headers, private val additionalQueryParams: QueryParams, private val additionalBodyProperties: Map, ) : Params { - fun secretId(): String = secretId - - fun _additionalHeaders(): Headers = additionalHeaders - - fun _additionalQueryParams(): QueryParams = additionalQueryParams + fun secretId(): Optional = Optional.ofNullable(secretId) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties - @JvmSynthetic - internal fun _body(): Optional> = - Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders - fun getPathParam(index: Int): String { - return when (index) { - 0 -> secretId - else -> "" - } - } + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): SecretDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [SecretDeleteParams]. */ @JvmStatic fun builder() = Builder() } - /** A builder for [AdminSecretDeleteParams]. */ - @NoAutoDetect + /** A builder for [SecretDeleteParams]. */ class Builder internal constructor() { private var secretId: String? = null @@ -61,15 +50,17 @@ private constructor( private var additionalBodyProperties: MutableMap = mutableMapOf() @JvmSynthetic - internal fun from(adminSecretDeleteParams: AdminSecretDeleteParams) = apply { - secretId = adminSecretDeleteParams.secretId - additionalHeaders = adminSecretDeleteParams.additionalHeaders.toBuilder() - additionalQueryParams = adminSecretDeleteParams.additionalQueryParams.toBuilder() - additionalBodyProperties = - adminSecretDeleteParams.additionalBodyProperties.toMutableMap() + internal fun from(secretDeleteParams: SecretDeleteParams) = apply { + secretId = secretDeleteParams.secretId + additionalHeaders = secretDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = secretDeleteParams.additionalQueryParams.toBuilder() + additionalBodyProperties = secretDeleteParams.additionalBodyProperties.toMutableMap() } - fun secretId(secretId: String) = apply { this.secretId = secretId } + fun secretId(secretId: String?) = apply { this.secretId = secretId } + + /** Alias for calling [Builder.secretId] with `secretId.orElse(null)`. */ + fun secretId(secretId: Optional) = secretId(secretId.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -191,25 +182,48 @@ private constructor( keys.forEach(::removeAdditionalBodyProperty) } - fun build(): AdminSecretDeleteParams = - AdminSecretDeleteParams( - checkRequired("secretId", secretId), + /** + * Returns an immutable instance of [SecretDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): SecretDeleteParams = + SecretDeleteParams( + secretId, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), ) } + fun _body(): Optional> = + Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + + fun _pathParam(index: Int): String = + when (index) { + 0 -> secretId ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is AdminSecretDeleteParams && secretId == other.secretId && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is SecretDeleteParams && + secretId == other.secretId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(secretId, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(secretId, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = - "AdminSecretDeleteParams{secretId=$secretId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" + "SecretDeleteParams{secretId=$secretId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminSecretListParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/secrets/SecretListParams.kt similarity index 79% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/AdminSecretListParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/admin/secrets/SecretListParams.kt index 61188d9..fdb9eb9 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminSecretListParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/secrets/SecretListParams.kt @@ -1,46 +1,45 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.admin.secrets -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params import dev.arcade.core.http.Headers import dev.arcade.core.http.QueryParams import java.util.Objects /** List all secrets that are visible to the caller */ -class AdminSecretListParams +class SecretListParams 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 - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): SecretListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [SecretListParams]. */ @JvmStatic fun builder() = Builder() } - /** A builder for [AdminSecretListParams]. */ - @NoAutoDetect + /** A builder for [SecretListParams]. */ class Builder internal constructor() { private var additionalHeaders: Headers.Builder = Headers.builder() private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @JvmSynthetic - internal fun from(adminSecretListParams: AdminSecretListParams) = apply { - additionalHeaders = adminSecretListParams.additionalHeaders.toBuilder() - additionalQueryParams = adminSecretListParams.additionalQueryParams.toBuilder() + internal fun from(secretListParams: SecretListParams) = apply { + additionalHeaders = secretListParams.additionalHeaders.toBuilder() + additionalQueryParams = secretListParams.additionalQueryParams.toBuilder() } fun additionalHeaders(additionalHeaders: Headers) = apply { @@ -141,20 +140,31 @@ private constructor( additionalQueryParams.removeAll(keys) } - fun build(): AdminSecretListParams = - AdminSecretListParams(additionalHeaders.build(), additionalQueryParams.build()) + /** + * Returns an immutable instance of [SecretListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): SecretListParams = + SecretListParams(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 /* spotless:off */ other is AdminSecretListParams && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is SecretListParams && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(additionalHeaders, additionalQueryParams) override fun toString() = - "AdminSecretListParams{additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" + "SecretListParams{additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/secrets/SecretListResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/secrets/SecretListResponse.kt new file mode 100644 index 0000000..9459f39 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/secrets/SecretListResponse.kt @@ -0,0 +1,302 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.admin.secrets + +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 dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.core.checkKnown +import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class SecretListResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val items: JsonField>, + private val limit: JsonField, + private val offset: JsonField, + private val pageCount: JsonField, + private val totalCount: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("items") + @ExcludeMissing + items: JsonField> = JsonMissing.of(), + @JsonProperty("limit") @ExcludeMissing limit: JsonField = JsonMissing.of(), + @JsonProperty("offset") @ExcludeMissing offset: JsonField = JsonMissing.of(), + @JsonProperty("page_count") @ExcludeMissing pageCount: JsonField = JsonMissing.of(), + @JsonProperty("total_count") @ExcludeMissing totalCount: JsonField = JsonMissing.of(), + ) : this(items, limit, offset, pageCount, totalCount, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun items(): Optional> = items.getOptional("items") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun limit(): Optional = limit.getOptional("limit") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun offset(): Optional = offset.getOptional("offset") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun pageCount(): Optional = pageCount.getOptional("page_count") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun totalCount(): Optional = totalCount.getOptional("total_count") + + /** + * Returns the raw JSON value of [items]. + * + * Unlike [items], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("items") @ExcludeMissing fun _items(): JsonField> = items + + /** + * Returns the raw JSON value of [limit]. + * + * Unlike [limit], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("limit") @ExcludeMissing fun _limit(): JsonField = limit + + /** + * Returns the raw JSON value of [offset]. + * + * Unlike [offset], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("offset") @ExcludeMissing fun _offset(): JsonField = offset + + /** + * Returns the raw JSON value of [pageCount]. + * + * Unlike [pageCount], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("page_count") @ExcludeMissing fun _pageCount(): JsonField = pageCount + + /** + * Returns the raw JSON value of [totalCount]. + * + * Unlike [totalCount], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("total_count") @ExcludeMissing fun _totalCount(): JsonField = totalCount + + @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 [SecretListResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [SecretListResponse]. */ + class Builder internal constructor() { + + private var items: JsonField>? = null + private var limit: JsonField = JsonMissing.of() + private var offset: JsonField = JsonMissing.of() + private var pageCount: JsonField = JsonMissing.of() + private var totalCount: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(secretListResponse: SecretListResponse) = apply { + items = secretListResponse.items.map { it.toMutableList() } + limit = secretListResponse.limit + offset = secretListResponse.offset + pageCount = secretListResponse.pageCount + totalCount = secretListResponse.totalCount + additionalProperties = secretListResponse.additionalProperties.toMutableMap() + } + + fun items(items: List) = items(JsonField.of(items)) + + /** + * Sets [Builder.items] to an arbitrary JSON value. + * + * You should usually call [Builder.items] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun items(items: JsonField>) = apply { + this.items = items.map { it.toMutableList() } + } + + /** + * Adds a single [SecretResponse] to [items]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addItem(item: SecretResponse) = apply { + items = + (items ?: JsonField.of(mutableListOf())).also { checkKnown("items", it).add(item) } + } + + fun limit(limit: Long) = limit(JsonField.of(limit)) + + /** + * Sets [Builder.limit] to an arbitrary JSON value. + * + * You should usually call [Builder.limit] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun limit(limit: JsonField) = apply { this.limit = limit } + + fun offset(offset: Long) = offset(JsonField.of(offset)) + + /** + * Sets [Builder.offset] to an arbitrary JSON value. + * + * You should usually call [Builder.offset] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun offset(offset: JsonField) = apply { this.offset = offset } + + fun pageCount(pageCount: Long) = pageCount(JsonField.of(pageCount)) + + /** + * Sets [Builder.pageCount] to an arbitrary JSON value. + * + * You should usually call [Builder.pageCount] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun pageCount(pageCount: JsonField) = apply { this.pageCount = pageCount } + + fun totalCount(totalCount: Long) = totalCount(JsonField.of(totalCount)) + + /** + * Sets [Builder.totalCount] to an arbitrary JSON value. + * + * You should usually call [Builder.totalCount] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun totalCount(totalCount: JsonField) = apply { this.totalCount = totalCount } + + 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 [SecretListResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): SecretListResponse = + SecretListResponse( + (items ?: JsonMissing.of()).map { it.toImmutable() }, + limit, + offset, + pageCount, + totalCount, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): SecretListResponse = apply { + if (validated) { + return@apply + } + + items().ifPresent { it.forEach { it.validate() } } + limit() + offset() + pageCount() + totalCount() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (items.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (limit.asKnown().isPresent) 1 else 0) + + (if (offset.asKnown().isPresent) 1 else 0) + + (if (pageCount.asKnown().isPresent) 1 else 0) + + (if (totalCount.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is SecretListResponse && + items == other.items && + limit == other.limit && + offset == other.offset && + pageCount == other.pageCount && + totalCount == other.totalCount && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(items, limit, offset, pageCount, totalCount, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "SecretListResponse{items=$items, limit=$limit, offset=$offset, pageCount=$pageCount, totalCount=$totalCount, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/secrets/SecretResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/secrets/SecretResponse.kt new file mode 100644 index 0000000..4146152 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/secrets/SecretResponse.kt @@ -0,0 +1,678 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.admin.secrets + +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 dev.arcade.core.Enum +import dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class SecretResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val id: JsonField, + private val binding: JsonField, + private val createdAt: JsonField, + private val description: JsonField, + private val key: JsonField, + private val lastAccessedAt: JsonField, + private val updatedAt: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("binding") @ExcludeMissing binding: JsonField = JsonMissing.of(), + @JsonProperty("created_at") @ExcludeMissing createdAt: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("key") @ExcludeMissing key: JsonField = JsonMissing.of(), + @JsonProperty("last_accessed_at") + @ExcludeMissing + lastAccessedAt: JsonField = JsonMissing.of(), + @JsonProperty("updated_at") @ExcludeMissing updatedAt: JsonField = JsonMissing.of(), + ) : this(id, binding, createdAt, description, key, lastAccessedAt, updatedAt, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun binding(): Optional = binding.getOptional("binding") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun createdAt(): Optional = createdAt.getOptional("created_at") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun key(): Optional = key.getOptional("key") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun lastAccessedAt(): Optional = lastAccessedAt.getOptional("last_accessed_at") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun updatedAt(): Optional = updatedAt.getOptional("updated_at") + + /** + * 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 [binding]. + * + * Unlike [binding], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("binding") @ExcludeMissing fun _binding(): JsonField = binding + + /** + * 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 [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 [key]. + * + * Unlike [key], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("key") @ExcludeMissing fun _key(): JsonField = key + + /** + * Returns the raw JSON value of [lastAccessedAt]. + * + * Unlike [lastAccessedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("last_accessed_at") + @ExcludeMissing + fun _lastAccessedAt(): JsonField = lastAccessedAt + + /** + * Returns the raw JSON value of [updatedAt]. + * + * Unlike [updatedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("updated_at") @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 [SecretResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [SecretResponse]. */ + class Builder internal constructor() { + + private var id: JsonField = JsonMissing.of() + private var binding: JsonField = JsonMissing.of() + private var createdAt: JsonField = JsonMissing.of() + private var description: JsonField = JsonMissing.of() + private var key: JsonField = JsonMissing.of() + private var lastAccessedAt: JsonField = JsonMissing.of() + private var updatedAt: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(secretResponse: SecretResponse) = apply { + id = secretResponse.id + binding = secretResponse.binding + createdAt = secretResponse.createdAt + description = secretResponse.description + key = secretResponse.key + lastAccessedAt = secretResponse.lastAccessedAt + updatedAt = secretResponse.updatedAt + additionalProperties = secretResponse.additionalProperties.toMutableMap() + } + + 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 binding(binding: Binding) = binding(JsonField.of(binding)) + + /** + * Sets [Builder.binding] to an arbitrary JSON value. + * + * You should usually call [Builder.binding] with a well-typed [Binding] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun binding(binding: JsonField) = apply { this.binding = binding } + + fun createdAt(createdAt: String) = createdAt(JsonField.of(createdAt)) + + /** + * Sets [Builder.createdAt] to an arbitrary JSON value. + * + * You should usually call [Builder.createdAt] with a well-typed [String] 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 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 } + + fun key(key: String) = key(JsonField.of(key)) + + /** + * Sets [Builder.key] to an arbitrary JSON value. + * + * You should usually call [Builder.key] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun key(key: JsonField) = apply { this.key = key } + + fun lastAccessedAt(lastAccessedAt: String) = lastAccessedAt(JsonField.of(lastAccessedAt)) + + /** + * Sets [Builder.lastAccessedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.lastAccessedAt] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun lastAccessedAt(lastAccessedAt: JsonField) = apply { + this.lastAccessedAt = lastAccessedAt + } + + fun updatedAt(updatedAt: String) = updatedAt(JsonField.of(updatedAt)) + + /** + * Sets [Builder.updatedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.updatedAt] with a well-typed [String] 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 [SecretResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): SecretResponse = + SecretResponse( + id, + binding, + createdAt, + description, + key, + lastAccessedAt, + updatedAt, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): SecretResponse = apply { + if (validated) { + return@apply + } + + id() + binding().ifPresent { it.validate() } + createdAt() + description() + key() + lastAccessedAt() + updatedAt() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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) + + (binding.asKnown().getOrNull()?.validity() ?: 0) + + (if (createdAt.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (if (key.asKnown().isPresent) 1 else 0) + + (if (lastAccessedAt.asKnown().isPresent) 1 else 0) + + (if (updatedAt.asKnown().isPresent) 1 else 0) + + class Binding + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws ArcadeInvalidDataException 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 [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 [Binding]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Binding]. */ + class Builder internal constructor() { + + private var id: JsonField = JsonMissing.of() + private var type: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(binding: Binding) = apply { + id = binding.id + type = binding.type + additionalProperties = binding.additionalProperties.toMutableMap() + } + + 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 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 [Binding]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Binding = Binding(id, type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Binding = apply { + if (validated) { + return@apply + } + + id() + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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) + (type.asKnown().getOrNull()?.validity() ?: 0) + + 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 STATIC = of("static") + + @JvmField val TENANT = of("tenant") + + @JvmField val PROJECT = of("project") + + @JvmField val ACCOUNT = of("account") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + STATIC, + TENANT, + PROJECT, + ACCOUNT, + } + + /** + * 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 { + STATIC, + TENANT, + PROJECT, + ACCOUNT, + /** 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) { + STATIC -> Value.STATIC + TENANT -> Value.TENANT + PROJECT -> Value.PROJECT + ACCOUNT -> Value.ACCOUNT + 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 ArcadeInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + STATIC -> Known.STATIC + TENANT -> Known.TENANT + PROJECT -> Known.PROJECT + ACCOUNT -> Known.ACCOUNT + else -> throw ArcadeInvalidDataException("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 ArcadeInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ArcadeInvalidDataException("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: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 Binding && + 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() = + "Binding{id=$id, type=$type, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is SecretResponse && + id == other.id && + binding == other.binding && + createdAt == other.createdAt && + description == other.description && + key == other.key && + lastAccessedAt == other.lastAccessedAt && + updatedAt == other.updatedAt && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + binding, + createdAt, + description, + key, + lastAccessedAt, + updatedAt, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "SecretResponse{id=$id, binding=$binding, createdAt=$createdAt, description=$description, key=$key, lastAccessedAt=$lastAccessedAt, updatedAt=$updatedAt, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminUserConnectionDeleteParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/userconnections/UserConnectionDeleteParams.kt similarity index 73% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/AdminUserConnectionDeleteParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/admin/userconnections/UserConnectionDeleteParams.kt index 64b26ec..17a7e0f 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/AdminUserConnectionDeleteParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/userconnections/UserConnectionDeleteParams.kt @@ -1,58 +1,49 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.admin.userconnections import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params -import dev.arcade.core.checkRequired import dev.arcade.core.http.Headers import dev.arcade.core.http.QueryParams import dev.arcade.core.toImmutable import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Delete a user/auth provider connection */ -class AdminUserConnectionDeleteParams +class UserConnectionDeleteParams private constructor( - private val id: String, + private val id: String?, private val additionalHeaders: Headers, private val additionalQueryParams: QueryParams, private val additionalBodyProperties: Map, ) : Params { - fun id(): String = id - - fun _additionalHeaders(): Headers = additionalHeaders - - fun _additionalQueryParams(): QueryParams = additionalQueryParams + fun id(): Optional = Optional.ofNullable(id) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties - @JvmSynthetic - internal fun _body(): Optional> = - Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders - fun getPathParam(index: Int): String { - return when (index) { - 0 -> id - else -> "" - } - } + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): UserConnectionDeleteParams = builder().build() + + /** + * Returns a mutable builder for constructing an instance of [UserConnectionDeleteParams]. + */ @JvmStatic fun builder() = Builder() } - /** A builder for [AdminUserConnectionDeleteParams]. */ - @NoAutoDetect + /** A builder for [UserConnectionDeleteParams]. */ class Builder internal constructor() { private var id: String? = null @@ -61,17 +52,18 @@ private constructor( private var additionalBodyProperties: MutableMap = mutableMapOf() @JvmSynthetic - internal fun from(adminUserConnectionDeleteParams: AdminUserConnectionDeleteParams) = - apply { - id = adminUserConnectionDeleteParams.id - additionalHeaders = adminUserConnectionDeleteParams.additionalHeaders.toBuilder() - additionalQueryParams = - adminUserConnectionDeleteParams.additionalQueryParams.toBuilder() - additionalBodyProperties = - adminUserConnectionDeleteParams.additionalBodyProperties.toMutableMap() - } + internal fun from(userConnectionDeleteParams: UserConnectionDeleteParams) = apply { + id = userConnectionDeleteParams.id + additionalHeaders = userConnectionDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = userConnectionDeleteParams.additionalQueryParams.toBuilder() + additionalBodyProperties = + userConnectionDeleteParams.additionalBodyProperties.toMutableMap() + } - fun id(id: String) = apply { this.id = id } + 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() @@ -193,25 +185,48 @@ private constructor( keys.forEach(::removeAdditionalBodyProperty) } - fun build(): AdminUserConnectionDeleteParams = - AdminUserConnectionDeleteParams( - checkRequired("id", id), + /** + * Returns an immutable instance of [UserConnectionDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): UserConnectionDeleteParams = + UserConnectionDeleteParams( + 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 /* spotless:off */ other is AdminUserConnectionDeleteParams && id == other.id && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is UserConnectionDeleteParams && + id == other.id && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(id, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(id, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = - "AdminUserConnectionDeleteParams{id=$id, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" + "UserConnectionDeleteParams{id=$id, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/userconnections/UserConnectionListPage.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/userconnections/UserConnectionListPage.kt new file mode 100644 index 0000000..5b870f8 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/userconnections/UserConnectionListPage.kt @@ -0,0 +1,145 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.admin.userconnections + +import dev.arcade.core.AutoPager +import dev.arcade.core.Page +import dev.arcade.core.checkRequired +import dev.arcade.services.blocking.admin.UserConnectionService +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrDefault +import kotlin.jvm.optionals.getOrNull + +/** @see UserConnectionService.list */ +class UserConnectionListPage +private constructor( + private val service: UserConnectionService, + private val params: UserConnectionListParams, + private val response: UserConnectionListPageResponse, +) : Page { + + /** + * Delegates to [UserConnectionListPageResponse], but gracefully handles missing data. + * + * @see UserConnectionListPageResponse.items + */ + override fun items(): List = + response._items().getOptional("items").getOrNull() ?: emptyList() + + /** + * Delegates to [UserConnectionListPageResponse], but gracefully handles missing data. + * + * @see UserConnectionListPageResponse.totalCount + */ + fun totalCount(): Optional = response._totalCount().getOptional("total_count") + + /** + * Delegates to [UserConnectionListPageResponse], but gracefully handles missing data. + * + * @see UserConnectionListPageResponse.offset + */ + fun offset(): Optional = response._offset().getOptional("offset") + + override fun hasNextPage(): Boolean { + if (items().isEmpty()) { + return false + } + + val offset = offset().getOrDefault(0) + val totalCount = totalCount().getOrNull() + return totalCount == null || offset + items().size < totalCount + } + + fun nextPageParams(): UserConnectionListParams { + val offset = offset().getOrDefault(0) + return params.toBuilder().offset(offset + items().size).build() + } + + override fun nextPage(): UserConnectionListPage = service.list(nextPageParams()) + + fun autoPager(): AutoPager = AutoPager.from(this) + + /** The parameters that were used to request this page. */ + fun params(): UserConnectionListParams = params + + /** The response that this page was parsed from. */ + fun response(): UserConnectionListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [UserConnectionListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UserConnectionListPage]. */ + class Builder internal constructor() { + + private var service: UserConnectionService? = null + private var params: UserConnectionListParams? = null + private var response: UserConnectionListPageResponse? = null + + @JvmSynthetic + internal fun from(userConnectionListPage: UserConnectionListPage) = apply { + service = userConnectionListPage.service + params = userConnectionListPage.params + response = userConnectionListPage.response + } + + fun service(service: UserConnectionService) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: UserConnectionListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: UserConnectionListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [UserConnectionListPage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UserConnectionListPage = + UserConnectionListPage( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UserConnectionListPage && + service == other.service && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, params, response) + + override fun toString() = + "UserConnectionListPage{service=$service, params=$params, response=$response}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/userconnections/UserConnectionListPageAsync.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/userconnections/UserConnectionListPageAsync.kt new file mode 100644 index 0000000..f1867e5 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/userconnections/UserConnectionListPageAsync.kt @@ -0,0 +1,160 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.admin.userconnections + +import dev.arcade.core.AutoPagerAsync +import dev.arcade.core.PageAsync +import dev.arcade.core.checkRequired +import dev.arcade.services.async.admin.UserConnectionServiceAsync +import java.util.Objects +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import kotlin.jvm.optionals.getOrDefault +import kotlin.jvm.optionals.getOrNull + +/** @see UserConnectionServiceAsync.list */ +class UserConnectionListPageAsync +private constructor( + private val service: UserConnectionServiceAsync, + private val streamHandlerExecutor: Executor, + private val params: UserConnectionListParams, + private val response: UserConnectionListPageResponse, +) : PageAsync { + + /** + * Delegates to [UserConnectionListPageResponse], but gracefully handles missing data. + * + * @see UserConnectionListPageResponse.items + */ + override fun items(): List = + response._items().getOptional("items").getOrNull() ?: emptyList() + + /** + * Delegates to [UserConnectionListPageResponse], but gracefully handles missing data. + * + * @see UserConnectionListPageResponse.totalCount + */ + fun totalCount(): Optional = response._totalCount().getOptional("total_count") + + /** + * Delegates to [UserConnectionListPageResponse], but gracefully handles missing data. + * + * @see UserConnectionListPageResponse.offset + */ + fun offset(): Optional = response._offset().getOptional("offset") + + override fun hasNextPage(): Boolean { + if (items().isEmpty()) { + return false + } + + val offset = offset().getOrDefault(0) + val totalCount = totalCount().getOrNull() + return totalCount == null || offset + items().size < totalCount + } + + fun nextPageParams(): UserConnectionListParams { + val offset = offset().getOrDefault(0) + return params.toBuilder().offset(offset + items().size).build() + } + + override fun nextPage(): CompletableFuture = + service.list(nextPageParams()) + + fun autoPager(): AutoPagerAsync = + AutoPagerAsync.from(this, streamHandlerExecutor) + + /** The parameters that were used to request this page. */ + fun params(): UserConnectionListParams = params + + /** The response that this page was parsed from. */ + fun response(): UserConnectionListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [UserConnectionListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UserConnectionListPageAsync]. */ + class Builder internal constructor() { + + private var service: UserConnectionServiceAsync? = null + private var streamHandlerExecutor: Executor? = null + private var params: UserConnectionListParams? = null + private var response: UserConnectionListPageResponse? = null + + @JvmSynthetic + internal fun from(userConnectionListPageAsync: UserConnectionListPageAsync) = apply { + service = userConnectionListPageAsync.service + streamHandlerExecutor = userConnectionListPageAsync.streamHandlerExecutor + params = userConnectionListPageAsync.params + response = userConnectionListPageAsync.response + } + + fun service(service: UserConnectionServiceAsync) = apply { this.service = service } + + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + this.streamHandlerExecutor = streamHandlerExecutor + } + + /** The parameters that were used to request this page. */ + fun params(params: UserConnectionListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: UserConnectionListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [UserConnectionListPageAsync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UserConnectionListPageAsync = + UserConnectionListPageAsync( + checkRequired("service", service), + checkRequired("streamHandlerExecutor", streamHandlerExecutor), + checkRequired("params", params), + checkRequired("response", response), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UserConnectionListPageAsync && + service == other.service && + streamHandlerExecutor == other.streamHandlerExecutor && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, streamHandlerExecutor, params, response) + + override fun toString() = + "UserConnectionListPageAsync{service=$service, streamHandlerExecutor=$streamHandlerExecutor, params=$params, response=$response}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/userconnections/UserConnectionListPageResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/userconnections/UserConnectionListPageResponse.kt new file mode 100644 index 0000000..3d40096 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/userconnections/UserConnectionListPageResponse.kt @@ -0,0 +1,308 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.admin.userconnections + +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 dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.core.checkKnown +import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class UserConnectionListPageResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val items: JsonField>, + private val limit: JsonField, + private val offset: JsonField, + private val pageCount: JsonField, + private val totalCount: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("items") + @ExcludeMissing + items: JsonField> = JsonMissing.of(), + @JsonProperty("limit") @ExcludeMissing limit: JsonField = JsonMissing.of(), + @JsonProperty("offset") @ExcludeMissing offset: JsonField = JsonMissing.of(), + @JsonProperty("page_count") @ExcludeMissing pageCount: JsonField = JsonMissing.of(), + @JsonProperty("total_count") @ExcludeMissing totalCount: JsonField = JsonMissing.of(), + ) : this(items, limit, offset, pageCount, totalCount, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun items(): Optional> = items.getOptional("items") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun limit(): Optional = limit.getOptional("limit") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun offset(): Optional = offset.getOptional("offset") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun pageCount(): Optional = pageCount.getOptional("page_count") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun totalCount(): Optional = totalCount.getOptional("total_count") + + /** + * Returns the raw JSON value of [items]. + * + * Unlike [items], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("items") + @ExcludeMissing + fun _items(): JsonField> = items + + /** + * Returns the raw JSON value of [limit]. + * + * Unlike [limit], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("limit") @ExcludeMissing fun _limit(): JsonField = limit + + /** + * Returns the raw JSON value of [offset]. + * + * Unlike [offset], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("offset") @ExcludeMissing fun _offset(): JsonField = offset + + /** + * Returns the raw JSON value of [pageCount]. + * + * Unlike [pageCount], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("page_count") @ExcludeMissing fun _pageCount(): JsonField = pageCount + + /** + * Returns the raw JSON value of [totalCount]. + * + * Unlike [totalCount], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("total_count") @ExcludeMissing fun _totalCount(): JsonField = totalCount + + @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 + * [UserConnectionListPageResponse]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UserConnectionListPageResponse]. */ + class Builder internal constructor() { + + private var items: JsonField>? = null + private var limit: JsonField = JsonMissing.of() + private var offset: JsonField = JsonMissing.of() + private var pageCount: JsonField = JsonMissing.of() + private var totalCount: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(userConnectionListPageResponse: UserConnectionListPageResponse) = apply { + items = userConnectionListPageResponse.items.map { it.toMutableList() } + limit = userConnectionListPageResponse.limit + offset = userConnectionListPageResponse.offset + pageCount = userConnectionListPageResponse.pageCount + totalCount = userConnectionListPageResponse.totalCount + additionalProperties = + userConnectionListPageResponse.additionalProperties.toMutableMap() + } + + fun items(items: List) = items(JsonField.of(items)) + + /** + * Sets [Builder.items] to an arbitrary JSON value. + * + * You should usually call [Builder.items] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun items(items: JsonField>) = apply { + this.items = items.map { it.toMutableList() } + } + + /** + * Adds a single [UserConnectionResponse] to [items]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addItem(item: UserConnectionResponse) = apply { + items = + (items ?: JsonField.of(mutableListOf())).also { checkKnown("items", it).add(item) } + } + + fun limit(limit: Long) = limit(JsonField.of(limit)) + + /** + * Sets [Builder.limit] to an arbitrary JSON value. + * + * You should usually call [Builder.limit] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun limit(limit: JsonField) = apply { this.limit = limit } + + fun offset(offset: Long) = offset(JsonField.of(offset)) + + /** + * Sets [Builder.offset] to an arbitrary JSON value. + * + * You should usually call [Builder.offset] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun offset(offset: JsonField) = apply { this.offset = offset } + + fun pageCount(pageCount: Long) = pageCount(JsonField.of(pageCount)) + + /** + * Sets [Builder.pageCount] to an arbitrary JSON value. + * + * You should usually call [Builder.pageCount] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun pageCount(pageCount: JsonField) = apply { this.pageCount = pageCount } + + fun totalCount(totalCount: Long) = totalCount(JsonField.of(totalCount)) + + /** + * Sets [Builder.totalCount] to an arbitrary JSON value. + * + * You should usually call [Builder.totalCount] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun totalCount(totalCount: JsonField) = apply { this.totalCount = totalCount } + + 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 [UserConnectionListPageResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): UserConnectionListPageResponse = + UserConnectionListPageResponse( + (items ?: JsonMissing.of()).map { it.toImmutable() }, + limit, + offset, + pageCount, + totalCount, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): UserConnectionListPageResponse = apply { + if (validated) { + return@apply + } + + items().ifPresent { it.forEach { it.validate() } } + limit() + offset() + pageCount() + totalCount() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (items.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (limit.asKnown().isPresent) 1 else 0) + + (if (offset.asKnown().isPresent) 1 else 0) + + (if (pageCount.asKnown().isPresent) 1 else 0) + + (if (totalCount.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UserConnectionListPageResponse && + items == other.items && + limit == other.limit && + offset == other.offset && + pageCount == other.pageCount && + totalCount == other.totalCount && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(items, limit, offset, pageCount, totalCount, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "UserConnectionListPageResponse{items=$items, limit=$limit, offset=$offset, pageCount=$pageCount, totalCount=$totalCount, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/userconnections/UserConnectionListParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/userconnections/UserConnectionListParams.kt new file mode 100644 index 0000000..5f6611c --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/userconnections/UserConnectionListParams.kt @@ -0,0 +1,255 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.admin.userconnections + +import dev.arcade.core.Params +import dev.arcade.core.http.Headers +import dev.arcade.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** List all auth connections */ +class UserConnectionListParams +private constructor( + private val limit: Long?, + private val offset: Long?, + private val providerId: String?, + private val userId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Page size */ + fun limit(): Optional = Optional.ofNullable(limit) + + /** Page offset */ + fun offset(): Optional = Optional.ofNullable(offset) + + /** Provider ID */ + fun providerId(): Optional = Optional.ofNullable(providerId) + + /** User ID */ + fun userId(): Optional = Optional.ofNullable(userId) + + /** 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(): UserConnectionListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [UserConnectionListParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UserConnectionListParams]. */ + class Builder internal constructor() { + + private var limit: Long? = null + private var offset: Long? = null + private var providerId: String? = null + private var userId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(userConnectionListParams: UserConnectionListParams) = apply { + limit = userConnectionListParams.limit + offset = userConnectionListParams.offset + providerId = userConnectionListParams.providerId + userId = userConnectionListParams.userId + additionalHeaders = userConnectionListParams.additionalHeaders.toBuilder() + additionalQueryParams = userConnectionListParams.additionalQueryParams.toBuilder() + } + + /** Page size */ + 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()) + + /** Page offset */ + fun offset(offset: Long?) = apply { this.offset = offset } + + /** + * Alias for [Builder.offset]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun offset(offset: Long) = offset(offset as Long?) + + /** Alias for calling [Builder.offset] with `offset.orElse(null)`. */ + fun offset(offset: Optional) = offset(offset.getOrNull()) + + /** Provider ID */ + fun providerId(providerId: String?) = apply { this.providerId = providerId } + + /** Alias for calling [Builder.providerId] with `providerId.orElse(null)`. */ + fun providerId(providerId: Optional) = providerId(providerId.getOrNull()) + + /** User ID */ + fun userId(userId: String?) = apply { this.userId = userId } + + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.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 [UserConnectionListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): UserConnectionListParams = + UserConnectionListParams( + limit, + offset, + providerId, + userId, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + limit?.let { put("limit", it.toString()) } + offset?.let { put("offset", it.toString()) } + providerId?.let { put("provider_id", it) } + userId?.let { put("user_id", it) } + putAll(additionalQueryParams) + } + .build() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UserConnectionListParams && + limit == other.limit && + offset == other.offset && + providerId == other.providerId && + userId == other.userId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(limit, offset, providerId, userId, additionalHeaders, additionalQueryParams) + + override fun toString() = + "UserConnectionListParams{limit=$limit, offset=$offset, providerId=$providerId, userId=$userId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/userconnections/UserConnectionResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/userconnections/UserConnectionResponse.kt new file mode 100644 index 0000000..e1ea340 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/admin/userconnections/UserConnectionResponse.kt @@ -0,0 +1,475 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.admin.userconnections + +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 dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.core.checkKnown +import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class UserConnectionResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val id: JsonField, + private val connectionId: JsonField, + private val connectionStatus: JsonField, + private val providerDescription: JsonField, + private val providerId: JsonField, + private val providerType: JsonField, + private val providerUserInfo: JsonValue, + private val scopes: JsonField>, + private val userId: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("connection_id") + @ExcludeMissing + connectionId: JsonField = JsonMissing.of(), + @JsonProperty("connection_status") + @ExcludeMissing + connectionStatus: JsonField = JsonMissing.of(), + @JsonProperty("provider_description") + @ExcludeMissing + providerDescription: JsonField = JsonMissing.of(), + @JsonProperty("provider_id") + @ExcludeMissing + providerId: JsonField = JsonMissing.of(), + @JsonProperty("provider_type") + @ExcludeMissing + providerType: JsonField = JsonMissing.of(), + @JsonProperty("provider_user_info") + @ExcludeMissing + providerUserInfo: JsonValue = JsonMissing.of(), + @JsonProperty("scopes") @ExcludeMissing scopes: JsonField> = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + ) : this( + id, + connectionId, + connectionStatus, + providerDescription, + providerId, + providerType, + providerUserInfo, + scopes, + userId, + mutableMapOf(), + ) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun connectionId(): Optional = connectionId.getOptional("connection_id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun connectionStatus(): Optional = connectionStatus.getOptional("connection_status") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun providerDescription(): Optional = + providerDescription.getOptional("provider_description") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun providerId(): Optional = providerId.getOptional("provider_id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun providerType(): Optional = providerType.getOptional("provider_type") + + /** + * This arbitrary value can be deserialized into a custom type using the `convert` method: + * ```java + * MyClass myObject = userConnectionResponse.providerUserInfo().convert(MyClass.class); + * ``` + */ + @JsonProperty("provider_user_info") + @ExcludeMissing + fun _providerUserInfo(): JsonValue = providerUserInfo + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun scopes(): Optional> = scopes.getOptional("scopes") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun userId(): Optional = userId.getOptional("user_id") + + /** + * 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 [connectionId]. + * + * Unlike [connectionId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("connection_id") + @ExcludeMissing + fun _connectionId(): JsonField = connectionId + + /** + * Returns the raw JSON value of [connectionStatus]. + * + * Unlike [connectionStatus], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("connection_status") + @ExcludeMissing + fun _connectionStatus(): JsonField = connectionStatus + + /** + * Returns the raw JSON value of [providerDescription]. + * + * Unlike [providerDescription], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("provider_description") + @ExcludeMissing + fun _providerDescription(): JsonField = providerDescription + + /** + * Returns the raw JSON value of [providerId]. + * + * Unlike [providerId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("provider_id") @ExcludeMissing fun _providerId(): JsonField = providerId + + /** + * Returns the raw JSON value of [providerType]. + * + * Unlike [providerType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("provider_type") + @ExcludeMissing + fun _providerType(): JsonField = providerType + + /** + * Returns the raw JSON value of [scopes]. + * + * Unlike [scopes], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("scopes") @ExcludeMissing fun _scopes(): JsonField> = scopes + + /** + * Returns the raw JSON value of [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + + @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 [UserConnectionResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UserConnectionResponse]. */ + class Builder internal constructor() { + + private var id: JsonField = JsonMissing.of() + private var connectionId: JsonField = JsonMissing.of() + private var connectionStatus: JsonField = JsonMissing.of() + private var providerDescription: JsonField = JsonMissing.of() + private var providerId: JsonField = JsonMissing.of() + private var providerType: JsonField = JsonMissing.of() + private var providerUserInfo: JsonValue = JsonMissing.of() + private var scopes: JsonField>? = null + private var userId: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(userConnectionResponse: UserConnectionResponse) = apply { + id = userConnectionResponse.id + connectionId = userConnectionResponse.connectionId + connectionStatus = userConnectionResponse.connectionStatus + providerDescription = userConnectionResponse.providerDescription + providerId = userConnectionResponse.providerId + providerType = userConnectionResponse.providerType + providerUserInfo = userConnectionResponse.providerUserInfo + scopes = userConnectionResponse.scopes.map { it.toMutableList() } + userId = userConnectionResponse.userId + additionalProperties = userConnectionResponse.additionalProperties.toMutableMap() + } + + 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 connectionId(connectionId: String) = connectionId(JsonField.of(connectionId)) + + /** + * Sets [Builder.connectionId] to an arbitrary JSON value. + * + * You should usually call [Builder.connectionId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun connectionId(connectionId: JsonField) = apply { + this.connectionId = connectionId + } + + fun connectionStatus(connectionStatus: String) = + connectionStatus(JsonField.of(connectionStatus)) + + /** + * Sets [Builder.connectionStatus] to an arbitrary JSON value. + * + * You should usually call [Builder.connectionStatus] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun connectionStatus(connectionStatus: JsonField) = apply { + this.connectionStatus = connectionStatus + } + + fun providerDescription(providerDescription: String) = + providerDescription(JsonField.of(providerDescription)) + + /** + * Sets [Builder.providerDescription] to an arbitrary JSON value. + * + * You should usually call [Builder.providerDescription] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun providerDescription(providerDescription: JsonField) = apply { + this.providerDescription = providerDescription + } + + fun providerId(providerId: String) = providerId(JsonField.of(providerId)) + + /** + * Sets [Builder.providerId] to an arbitrary JSON value. + * + * You should usually call [Builder.providerId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun providerId(providerId: JsonField) = apply { this.providerId = providerId } + + fun providerType(providerType: String) = providerType(JsonField.of(providerType)) + + /** + * Sets [Builder.providerType] to an arbitrary JSON value. + * + * You should usually call [Builder.providerType] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun providerType(providerType: JsonField) = apply { + this.providerType = providerType + } + + fun providerUserInfo(providerUserInfo: JsonValue) = apply { + this.providerUserInfo = providerUserInfo + } + + fun scopes(scopes: List) = scopes(JsonField.of(scopes)) + + /** + * Sets [Builder.scopes] to an arbitrary JSON value. + * + * You should usually call [Builder.scopes] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun scopes(scopes: JsonField>) = apply { + this.scopes = scopes.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [scopes]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addScope(scope: String) = apply { + scopes = + (scopes ?: JsonField.of(mutableListOf())).also { + checkKnown("scopes", it).add(scope) + } + } + + fun userId(userId: String) = userId(JsonField.of(userId)) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun userId(userId: JsonField) = apply { this.userId = userId } + + 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 [UserConnectionResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): UserConnectionResponse = + UserConnectionResponse( + id, + connectionId, + connectionStatus, + providerDescription, + providerId, + providerType, + providerUserInfo, + (scopes ?: JsonMissing.of()).map { it.toImmutable() }, + userId, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): UserConnectionResponse = apply { + if (validated) { + return@apply + } + + id() + connectionId() + connectionStatus() + providerDescription() + providerId() + providerType() + scopes() + userId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (connectionId.asKnown().isPresent) 1 else 0) + + (if (connectionStatus.asKnown().isPresent) 1 else 0) + + (if (providerDescription.asKnown().isPresent) 1 else 0) + + (if (providerId.asKnown().isPresent) 1 else 0) + + (if (providerType.asKnown().isPresent) 1 else 0) + + (scopes.asKnown().getOrNull()?.size ?: 0) + + (if (userId.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UserConnectionResponse && + id == other.id && + connectionId == other.connectionId && + connectionStatus == other.connectionStatus && + providerDescription == other.providerDescription && + providerId == other.providerId && + providerType == other.providerType && + providerUserInfo == other.providerUserInfo && + scopes == other.scopes && + userId == other.userId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + connectionId, + connectionStatus, + providerDescription, + providerId, + providerType, + providerUserInfo, + scopes, + userId, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "UserConnectionResponse{id=$id, connectionId=$connectionId, connectionStatus=$connectionStatus, providerDescription=$providerDescription, providerId=$providerId, providerType=$providerType, providerUserInfo=$providerUserInfo, scopes=$scopes, userId=$userId, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthAuthorizeParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/auth/AuthAuthorizeParams.kt similarity index 84% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/AuthAuthorizeParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/auth/AuthAuthorizeParams.kt index 2f7692d..491f6a4 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthAuthorizeParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/auth/AuthAuthorizeParams.kt @@ -1,9 +1,8 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.auth import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params import dev.arcade.core.checkRequired import dev.arcade.core.http.Headers @@ -22,25 +21,28 @@ private constructor( fun _additionalBodyProperties(): Map = authRequest._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): AuthRequest = authRequest - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [AuthAuthorizeParams]. + * + * The following fields are required: + * ```java + * .authRequest() + * ``` + */ @JvmStatic fun builder() = Builder() } /** A builder for [AuthAuthorizeParams]. */ - @NoAutoDetect class Builder internal constructor() { private var authRequest: AuthRequest? = null @@ -154,6 +156,18 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [AuthAuthorizeParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .authRequest() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): AuthAuthorizeParams = AuthAuthorizeParams( checkRequired("authRequest", authRequest), @@ -162,15 +176,25 @@ private constructor( ) } + fun _body(): AuthRequest = authRequest + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is AuthAuthorizeParams && authRequest == other.authRequest && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is AuthAuthorizeParams && + authRequest == other.authRequest && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(authRequest, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(authRequest, additionalHeaders, additionalQueryParams) override fun toString() = "AuthAuthorizeParams{authRequest=$authRequest, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthConfirmUserParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/auth/AuthConfirmUserParams.kt similarity index 84% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/AuthConfirmUserParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/auth/AuthConfirmUserParams.kt index 95d6033..d7b4809 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthConfirmUserParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/auth/AuthConfirmUserParams.kt @@ -1,9 +1,8 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.auth import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params import dev.arcade.core.checkRequired import dev.arcade.core.http.Headers @@ -23,25 +22,28 @@ private constructor( fun _additionalBodyProperties(): Map = confirmUserRequest._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): ConfirmUserRequest = confirmUserRequest - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [AuthConfirmUserParams]. + * + * The following fields are required: + * ```java + * .confirmUserRequest() + * ``` + */ @JvmStatic fun builder() = Builder() } /** A builder for [AuthConfirmUserParams]. */ - @NoAutoDetect class Builder internal constructor() { private var confirmUserRequest: ConfirmUserRequest? = null @@ -157,6 +159,18 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [AuthConfirmUserParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .confirmUserRequest() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): AuthConfirmUserParams = AuthConfirmUserParams( checkRequired("confirmUserRequest", confirmUserRequest), @@ -165,15 +179,25 @@ private constructor( ) } + fun _body(): ConfirmUserRequest = confirmUserRequest + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is AuthConfirmUserParams && confirmUserRequest == other.confirmUserRequest && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is AuthConfirmUserParams && + confirmUserRequest == other.confirmUserRequest && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(confirmUserRequest, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(confirmUserRequest, additionalHeaders, additionalQueryParams) override fun toString() = "AuthConfirmUserParams{confirmUserRequest=$confirmUserRequest, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/auth/AuthRequest.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/auth/AuthRequest.kt new file mode 100644 index 0000000..6c761a5 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/auth/AuthRequest.kt @@ -0,0 +1,673 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.auth + +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 dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.core.checkKnown +import dev.arcade.core.checkRequired +import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class AuthRequest +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val authRequirement: JsonField, + private val userId: JsonField, + private val nextUri: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("auth_requirement") + @ExcludeMissing + authRequirement: JsonField = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + @JsonProperty("next_uri") @ExcludeMissing nextUri: JsonField = JsonMissing.of(), + ) : this(authRequirement, userId, nextUri, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException 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 authRequirement(): AuthRequirement = authRequirement.getRequired("auth_requirement") + + /** + * @throws ArcadeInvalidDataException 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 userId(): String = userId.getRequired("user_id") + + /** + * Optional: if provided, the user will be redirected to this URI after authorization + * + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun nextUri(): Optional = nextUri.getOptional("next_uri") + + /** + * Returns the raw JSON value of [authRequirement]. + * + * Unlike [authRequirement], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("auth_requirement") + @ExcludeMissing + fun _authRequirement(): JsonField = authRequirement + + /** + * Returns the raw JSON value of [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + + /** + * Returns the raw JSON value of [nextUri]. + * + * Unlike [nextUri], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("next_uri") @ExcludeMissing fun _nextUri(): JsonField = nextUri + + @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 [AuthRequest]. + * + * The following fields are required: + * ```java + * .authRequirement() + * .userId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AuthRequest]. */ + class Builder internal constructor() { + + private var authRequirement: JsonField? = null + private var userId: JsonField? = null + private var nextUri: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(authRequest: AuthRequest) = apply { + authRequirement = authRequest.authRequirement + userId = authRequest.userId + nextUri = authRequest.nextUri + additionalProperties = authRequest.additionalProperties.toMutableMap() + } + + fun authRequirement(authRequirement: AuthRequirement) = + authRequirement(JsonField.of(authRequirement)) + + /** + * Sets [Builder.authRequirement] to an arbitrary JSON value. + * + * You should usually call [Builder.authRequirement] with a well-typed [AuthRequirement] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun authRequirement(authRequirement: JsonField) = apply { + this.authRequirement = authRequirement + } + + fun userId(userId: String) = userId(JsonField.of(userId)) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun userId(userId: JsonField) = apply { this.userId = userId } + + /** Optional: if provided, the user will be redirected to this URI after authorization */ + fun nextUri(nextUri: String) = nextUri(JsonField.of(nextUri)) + + /** + * Sets [Builder.nextUri] to an arbitrary JSON value. + * + * You should usually call [Builder.nextUri] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun nextUri(nextUri: JsonField) = apply { this.nextUri = nextUri } + + 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 [AuthRequest]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .authRequirement() + * .userId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AuthRequest = + AuthRequest( + checkRequired("authRequirement", authRequirement), + checkRequired("userId", userId), + nextUri, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): AuthRequest = apply { + if (validated) { + return@apply + } + + authRequirement().validate() + userId() + nextUri() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (authRequirement.asKnown().getOrNull()?.validity() ?: 0) + + (if (userId.asKnown().isPresent) 1 else 0) + + (if (nextUri.asKnown().isPresent) 1 else 0) + + class AuthRequirement + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val id: JsonField, + private val oauth2: JsonField, + private val providerId: JsonField, + private val providerType: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("oauth2") @ExcludeMissing oauth2: JsonField = JsonMissing.of(), + @JsonProperty("provider_id") + @ExcludeMissing + providerId: JsonField = JsonMissing.of(), + @JsonProperty("provider_type") + @ExcludeMissing + providerType: JsonField = JsonMissing.of(), + ) : this(id, oauth2, providerId, providerType, mutableMapOf()) + + /** + * one of ID or ProviderID must be set + * + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun oauth2(): Optional = oauth2.getOptional("oauth2") + + /** + * one of ID or ProviderID must be set + * + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun providerId(): Optional = providerId.getOptional("provider_id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun providerType(): Optional = providerType.getOptional("provider_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 [oauth2]. + * + * Unlike [oauth2], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("oauth2") @ExcludeMissing fun _oauth2(): JsonField = oauth2 + + /** + * Returns the raw JSON value of [providerId]. + * + * Unlike [providerId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("provider_id") + @ExcludeMissing + fun _providerId(): JsonField = providerId + + /** + * Returns the raw JSON value of [providerType]. + * + * Unlike [providerType], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("provider_type") + @ExcludeMissing + fun _providerType(): JsonField = providerType + + @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 [AuthRequirement]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AuthRequirement]. */ + class Builder internal constructor() { + + private var id: JsonField = JsonMissing.of() + private var oauth2: JsonField = JsonMissing.of() + private var providerId: JsonField = JsonMissing.of() + private var providerType: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(authRequirement: AuthRequirement) = apply { + id = authRequirement.id + oauth2 = authRequirement.oauth2 + providerId = authRequirement.providerId + providerType = authRequirement.providerType + additionalProperties = authRequirement.additionalProperties.toMutableMap() + } + + /** one of ID or ProviderID must be set */ + 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 oauth2(oauth2: Oauth2) = oauth2(JsonField.of(oauth2)) + + /** + * Sets [Builder.oauth2] to an arbitrary JSON value. + * + * You should usually call [Builder.oauth2] with a well-typed [Oauth2] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun oauth2(oauth2: JsonField) = apply { this.oauth2 = oauth2 } + + /** one of ID or ProviderID must be set */ + fun providerId(providerId: String) = providerId(JsonField.of(providerId)) + + /** + * Sets [Builder.providerId] to an arbitrary JSON value. + * + * You should usually call [Builder.providerId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun providerId(providerId: JsonField) = apply { this.providerId = providerId } + + fun providerType(providerType: String) = providerType(JsonField.of(providerType)) + + /** + * Sets [Builder.providerType] to an arbitrary JSON value. + * + * You should usually call [Builder.providerType] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun providerType(providerType: JsonField) = apply { + this.providerType = providerType + } + + 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 [AuthRequirement]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): AuthRequirement = + AuthRequirement( + id, + oauth2, + providerId, + providerType, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): AuthRequirement = apply { + if (validated) { + return@apply + } + + id() + oauth2().ifPresent { it.validate() } + providerId() + providerType() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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) + + (oauth2.asKnown().getOrNull()?.validity() ?: 0) + + (if (providerId.asKnown().isPresent) 1 else 0) + + (if (providerType.asKnown().isPresent) 1 else 0) + + class Oauth2 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val scopes: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("scopes") + @ExcludeMissing + scopes: JsonField> = JsonMissing.of() + ) : this(scopes, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun scopes(): Optional> = scopes.getOptional("scopes") + + /** + * Returns the raw JSON value of [scopes]. + * + * Unlike [scopes], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("scopes") @ExcludeMissing fun _scopes(): JsonField> = scopes + + @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 [Oauth2]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Oauth2]. */ + class Builder internal constructor() { + + private var scopes: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(oauth2: Oauth2) = apply { + scopes = oauth2.scopes.map { it.toMutableList() } + additionalProperties = oauth2.additionalProperties.toMutableMap() + } + + fun scopes(scopes: List) = scopes(JsonField.of(scopes)) + + /** + * Sets [Builder.scopes] to an arbitrary JSON value. + * + * You should usually call [Builder.scopes] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun scopes(scopes: JsonField>) = apply { + this.scopes = scopes.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [scopes]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addScope(scope: String) = apply { + scopes = + (scopes ?: JsonField.of(mutableListOf())).also { + checkKnown("scopes", it).add(scope) + } + } + + 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 [Oauth2]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Oauth2 = + Oauth2( + (scopes ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Oauth2 = apply { + if (validated) { + return@apply + } + + scopes() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (scopes.asKnown().getOrNull()?.size ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Oauth2 && + scopes == other.scopes && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(scopes, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Oauth2{scopes=$scopes, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AuthRequirement && + id == other.id && + oauth2 == other.oauth2 && + providerId == other.providerId && + providerType == other.providerType && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(id, oauth2, providerId, providerType, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AuthRequirement{id=$id, oauth2=$oauth2, providerId=$providerId, providerType=$providerType, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AuthRequest && + authRequirement == other.authRequirement && + userId == other.userId && + nextUri == other.nextUri && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(authRequirement, userId, nextUri, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AuthRequest{authRequirement=$authRequirement, userId=$userId, nextUri=$nextUri, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthStatusParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/auth/AuthStatusParams.kt similarity index 79% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/AuthStatusParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/auth/AuthStatusParams.kt index 00017f6..71aa08c 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/AuthStatusParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/auth/AuthStatusParams.kt @@ -1,14 +1,14 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.auth -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params import dev.arcade.core.checkRequired import dev.arcade.core.http.Headers import dev.arcade.core.http.QueryParams import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** * Checks the status of an ongoing authorization process for a specific tool. If 'wait' param is @@ -29,29 +29,28 @@ private constructor( /** Timeout in seconds (max 59) */ fun wait(): Optional = Optional.ofNullable(wait) + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams { - val queryParams = QueryParams.builder() - this.id.let { queryParams.put("id", listOf(it.toString())) } - this.wait?.let { queryParams.put("wait", listOf(it.toString())) } - queryParams.putAll(additionalQueryParams) - return queryParams.build() - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [AuthStatusParams]. + * + * The following fields are required: + * ```java + * .id() + * ``` + */ @JvmStatic fun builder() = Builder() } /** A builder for [AuthStatusParams]. */ - @NoAutoDetect class Builder internal constructor() { private var id: String? = null @@ -73,12 +72,15 @@ private constructor( /** Timeout in seconds (max 59) */ fun wait(wait: Long?) = apply { this.wait = wait } - /** Timeout in seconds (max 59) */ + /** + * Alias for [Builder.wait]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun wait(wait: Long) = wait(wait as Long?) - /** Timeout in seconds (max 59) */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun wait(wait: Optional) = wait(wait.orElse(null) as Long?) + /** Alias for calling [Builder.wait] with `wait.orElse(null)`. */ + fun wait(wait: Optional) = wait(wait.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -178,6 +180,18 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [AuthStatusParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): AuthStatusParams = AuthStatusParams( checkRequired("id", id), @@ -187,15 +201,30 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + put("id", id) + wait?.let { put("wait", it.toString()) } + putAll(additionalQueryParams) + } + .build() + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is AuthStatusParams && id == other.id && wait == other.wait && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is AuthStatusParams && + id == other.id && + wait == other.wait && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(id, wait, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(id, wait, additionalHeaders, additionalQueryParams) override fun toString() = "AuthStatusParams{id=$id, wait=$wait, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/auth/ConfirmUserRequest.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/auth/ConfirmUserRequest.kt new file mode 100644 index 0000000..dcf9388 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/auth/ConfirmUserRequest.kt @@ -0,0 +1,204 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.auth + +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 dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.core.checkRequired +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections +import java.util.Objects + +class ConfirmUserRequest +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val flowId: JsonField, + private val userId: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("flow_id") @ExcludeMissing flowId: JsonField = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + ) : this(flowId, userId, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException 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 flowId(): String = flowId.getRequired("flow_id") + + /** + * @throws ArcadeInvalidDataException 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 userId(): String = userId.getRequired("user_id") + + /** + * Returns the raw JSON value of [flowId]. + * + * Unlike [flowId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("flow_id") @ExcludeMissing fun _flowId(): JsonField = flowId + + /** + * Returns the raw JSON value of [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + + @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 [ConfirmUserRequest]. + * + * The following fields are required: + * ```java + * .flowId() + * .userId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ConfirmUserRequest]. */ + class Builder internal constructor() { + + private var flowId: JsonField? = null + private var userId: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(confirmUserRequest: ConfirmUserRequest) = apply { + flowId = confirmUserRequest.flowId + userId = confirmUserRequest.userId + additionalProperties = confirmUserRequest.additionalProperties.toMutableMap() + } + + fun flowId(flowId: String) = flowId(JsonField.of(flowId)) + + /** + * Sets [Builder.flowId] to an arbitrary JSON value. + * + * You should usually call [Builder.flowId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun flowId(flowId: JsonField) = apply { this.flowId = flowId } + + fun userId(userId: String) = userId(JsonField.of(userId)) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun userId(userId: JsonField) = apply { this.userId = userId } + + 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 [ConfirmUserRequest]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .flowId() + * .userId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ConfirmUserRequest = + ConfirmUserRequest( + checkRequired("flowId", flowId), + checkRequired("userId", userId), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ConfirmUserRequest = apply { + if (validated) { + return@apply + } + + flowId() + userId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (flowId.asKnown().isPresent) 1 else 0) + (if (userId.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ConfirmUserRequest && + flowId == other.flowId && + userId == other.userId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(flowId, userId, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ConfirmUserRequest{flowId=$flowId, userId=$userId, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/auth/ConfirmUserResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/auth/ConfirmUserResponse.kt new file mode 100644 index 0000000..c76f5ba --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/auth/ConfirmUserResponse.kt @@ -0,0 +1,203 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.auth + +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 dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.core.checkRequired +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional + +class ConfirmUserResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val authId: JsonField, + private val nextUri: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("auth_id") @ExcludeMissing authId: JsonField = JsonMissing.of(), + @JsonProperty("next_uri") @ExcludeMissing nextUri: JsonField = JsonMissing.of(), + ) : this(authId, nextUri, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException 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 authId(): String = authId.getRequired("auth_id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun nextUri(): Optional = nextUri.getOptional("next_uri") + + /** + * Returns the raw JSON value of [authId]. + * + * Unlike [authId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("auth_id") @ExcludeMissing fun _authId(): JsonField = authId + + /** + * Returns the raw JSON value of [nextUri]. + * + * Unlike [nextUri], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("next_uri") @ExcludeMissing fun _nextUri(): JsonField = nextUri + + @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 [ConfirmUserResponse]. + * + * The following fields are required: + * ```java + * .authId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ConfirmUserResponse]. */ + class Builder internal constructor() { + + private var authId: JsonField? = null + private var nextUri: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(confirmUserResponse: ConfirmUserResponse) = apply { + authId = confirmUserResponse.authId + nextUri = confirmUserResponse.nextUri + additionalProperties = confirmUserResponse.additionalProperties.toMutableMap() + } + + fun authId(authId: String) = authId(JsonField.of(authId)) + + /** + * Sets [Builder.authId] to an arbitrary JSON value. + * + * You should usually call [Builder.authId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun authId(authId: JsonField) = apply { this.authId = authId } + + fun nextUri(nextUri: String) = nextUri(JsonField.of(nextUri)) + + /** + * Sets [Builder.nextUri] to an arbitrary JSON value. + * + * You should usually call [Builder.nextUri] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun nextUri(nextUri: JsonField) = apply { this.nextUri = nextUri } + + 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 [ConfirmUserResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .authId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ConfirmUserResponse = + ConfirmUserResponse( + checkRequired("authId", authId), + nextUri, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ConfirmUserResponse = apply { + if (validated) { + return@apply + } + + authId() + nextUri() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (authId.asKnown().isPresent) 1 else 0) + (if (nextUri.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ConfirmUserResponse && + authId == other.authId && + nextUri == other.nextUri && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(authId, nextUri, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ConfirmUserResponse{authId=$authId, nextUri=$nextUri, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/chat/ChatMessage.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/chat/ChatMessage.kt new file mode 100644 index 0000000..d65d93a --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/chat/ChatMessage.kt @@ -0,0 +1,850 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.chat + +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 dev.arcade.core.Enum +import dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.core.checkKnown +import dev.arcade.core.checkRequired +import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class ChatMessage +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val content: JsonField, + private val role: JsonField, + private val name: JsonField, + private val toolCallId: JsonField, + private val toolCalls: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("content") @ExcludeMissing content: JsonField = JsonMissing.of(), + @JsonProperty("role") @ExcludeMissing role: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("tool_call_id") + @ExcludeMissing + toolCallId: JsonField = JsonMissing.of(), + @JsonProperty("tool_calls") + @ExcludeMissing + toolCalls: JsonField> = JsonMissing.of(), + ) : this(content, role, name, toolCallId, toolCalls, mutableMapOf()) + + /** + * The content of the message. + * + * @throws ArcadeInvalidDataException 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 content(): String = content.getRequired("content") + + /** + * The role of the author of this message. One of system, user, tool, or assistant. + * + * @throws ArcadeInvalidDataException 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 role(): String = role.getRequired("role") + + /** + * tool Name + * + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * tool_call_id + * + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun toolCallId(): Optional = toolCallId.getOptional("tool_call_id") + + /** + * tool calls if any + * + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun toolCalls(): Optional> = toolCalls.getOptional("tool_calls") + + /** + * Returns the raw JSON value of [content]. + * + * Unlike [content], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("content") @ExcludeMissing fun _content(): JsonField = content + + /** + * Returns the raw JSON value of [role]. + * + * Unlike [role], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("role") @ExcludeMissing fun _role(): JsonField = role + + /** + * 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 [toolCallId]. + * + * Unlike [toolCallId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tool_call_id") @ExcludeMissing fun _toolCallId(): JsonField = toolCallId + + /** + * Returns the raw JSON value of [toolCalls]. + * + * Unlike [toolCalls], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tool_calls") + @ExcludeMissing + fun _toolCalls(): JsonField> = toolCalls + + @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 [ChatMessage]. + * + * The following fields are required: + * ```java + * .content() + * .role() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatMessage]. */ + class Builder internal constructor() { + + private var content: JsonField? = null + private var role: JsonField? = null + private var name: JsonField = JsonMissing.of() + private var toolCallId: JsonField = JsonMissing.of() + private var toolCalls: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(chatMessage: ChatMessage) = apply { + content = chatMessage.content + role = chatMessage.role + name = chatMessage.name + toolCallId = chatMessage.toolCallId + toolCalls = chatMessage.toolCalls.map { it.toMutableList() } + additionalProperties = chatMessage.additionalProperties.toMutableMap() + } + + /** The content of the message. */ + fun content(content: String) = content(JsonField.of(content)) + + /** + * Sets [Builder.content] to an arbitrary JSON value. + * + * You should usually call [Builder.content] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun content(content: JsonField) = apply { this.content = content } + + /** The role of the author of this message. One of system, user, tool, or assistant. */ + fun role(role: String) = role(JsonField.of(role)) + + /** + * Sets [Builder.role] to an arbitrary JSON value. + * + * You should usually call [Builder.role] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun role(role: JsonField) = apply { this.role = role } + + /** tool Name */ + 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 } + + /** tool_call_id */ + fun toolCallId(toolCallId: String) = toolCallId(JsonField.of(toolCallId)) + + /** + * Sets [Builder.toolCallId] to an arbitrary JSON value. + * + * You should usually call [Builder.toolCallId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun toolCallId(toolCallId: JsonField) = apply { this.toolCallId = toolCallId } + + /** tool calls if any */ + fun toolCalls(toolCalls: List) = toolCalls(JsonField.of(toolCalls)) + + /** + * Sets [Builder.toolCalls] to an arbitrary JSON value. + * + * You should usually call [Builder.toolCalls] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun toolCalls(toolCalls: JsonField>) = apply { + this.toolCalls = toolCalls.map { it.toMutableList() } + } + + /** + * Adds a single [ToolCall] to [toolCalls]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addToolCall(toolCall: ToolCall) = apply { + toolCalls = + (toolCalls ?: JsonField.of(mutableListOf())).also { + checkKnown("toolCalls", it).add(toolCall) + } + } + + 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 [ChatMessage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .content() + * .role() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatMessage = + ChatMessage( + checkRequired("content", content), + checkRequired("role", role), + name, + toolCallId, + (toolCalls ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatMessage = apply { + if (validated) { + return@apply + } + + content() + role() + name() + toolCallId() + toolCalls().ifPresent { it.forEach { it.validate() } } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (content.asKnown().isPresent) 1 else 0) + + (if (role.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (toolCallId.asKnown().isPresent) 1 else 0) + + (toolCalls.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + class ToolCall + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val id: JsonField, + private val function: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("function") + @ExcludeMissing + function: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(id, function, type, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun function(): Optional = function.getOptional("function") + + /** + * @throws ArcadeInvalidDataException 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 [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 [function]. + * + * Unlike [function], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("function") @ExcludeMissing fun _function(): JsonField = function + + /** + * 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 [ToolCall]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ToolCall]. */ + class Builder internal constructor() { + + private var id: JsonField = JsonMissing.of() + private var function: JsonField = JsonMissing.of() + private var type: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(toolCall: ToolCall) = apply { + id = toolCall.id + function = toolCall.function + type = toolCall.type + additionalProperties = toolCall.additionalProperties.toMutableMap() + } + + 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 function(function: Function) = function(JsonField.of(function)) + + /** + * Sets [Builder.function] to an arbitrary JSON value. + * + * You should usually call [Builder.function] with a well-typed [Function] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun function(function: JsonField) = apply { this.function = function } + + 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 [ToolCall]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ToolCall = + ToolCall(id, function, type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): ToolCall = apply { + if (validated) { + return@apply + } + + id() + function().ifPresent { it.validate() } + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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) + + (function.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + + class Function + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val arguments: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("arguments") + @ExcludeMissing + arguments: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + ) : this(arguments, name, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun arguments(): Optional = arguments.getOptional("arguments") + + /** + * @throws ArcadeInvalidDataException 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 [arguments]. + * + * Unlike [arguments], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("arguments") + @ExcludeMissing + fun _arguments(): JsonField = arguments + + /** + * 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 [Function]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Function]. */ + class Builder internal constructor() { + + private var arguments: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(function: Function) = apply { + arguments = function.arguments + name = function.name + additionalProperties = function.additionalProperties.toMutableMap() + } + + fun arguments(arguments: String) = arguments(JsonField.of(arguments)) + + /** + * Sets [Builder.arguments] to an arbitrary JSON value. + * + * You should usually call [Builder.arguments] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun arguments(arguments: JsonField) = apply { this.arguments = arguments } + + 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 [Function]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Function = + Function(arguments, name, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Function = apply { + if (validated) { + return@apply + } + + arguments() + name() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (arguments.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 Function && + arguments == other.arguments && + name == other.name && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(arguments, name, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Function{arguments=$arguments, name=$name, additionalProperties=$additionalProperties}" + } + + 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 FUNCTION = of("function") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + FUNCTION + } + + /** + * 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 { + FUNCTION, + /** 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) { + FUNCTION -> Value.FUNCTION + 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 ArcadeInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + FUNCTION -> Known.FUNCTION + else -> throw ArcadeInvalidDataException("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 ArcadeInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ArcadeInvalidDataException("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: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 ToolCall && + id == other.id && + function == other.function && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(id, function, type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ToolCall{id=$id, function=$function, type=$type, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatMessage && + content == other.content && + role == other.role && + name == other.name && + toolCallId == other.toolCallId && + toolCalls == other.toolCalls && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(content, role, name, toolCallId, toolCalls, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatMessage{content=$content, role=$role, name=$name, toolCallId=$toolCallId, toolCalls=$toolCalls, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/chat/ChatRequest.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/chat/ChatRequest.kt new file mode 100644 index 0000000..39bceff --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/chat/ChatRequest.kt @@ -0,0 +1,1418 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.chat + +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 dev.arcade.core.Enum +import dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.core.checkKnown +import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class ChatRequest +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val frequencyPenalty: JsonField, + private val logitBias: JsonField, + private val logprobs: JsonField, + private val maxTokens: JsonField, + private val messages: JsonField>, + private val model: JsonField, + private val n: JsonField, + private val parallelToolCalls: JsonField, + private val presencePenalty: JsonField, + private val responseFormat: JsonField, + private val seed: JsonField, + private val stop: JsonField>, + private val stream: JsonField, + private val streamOptions: JsonField, + private val temperature: JsonField, + private val toolChoice: JsonValue, + private val tools: JsonValue, + private val topLogprobs: JsonField, + private val topP: JsonField, + private val user: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("frequency_penalty") + @ExcludeMissing + frequencyPenalty: JsonField = JsonMissing.of(), + @JsonProperty("logit_bias") + @ExcludeMissing + logitBias: JsonField = JsonMissing.of(), + @JsonProperty("logprobs") @ExcludeMissing logprobs: JsonField = JsonMissing.of(), + @JsonProperty("max_tokens") @ExcludeMissing maxTokens: JsonField = JsonMissing.of(), + @JsonProperty("messages") + @ExcludeMissing + messages: JsonField> = JsonMissing.of(), + @JsonProperty("model") @ExcludeMissing model: JsonField = JsonMissing.of(), + @JsonProperty("n") @ExcludeMissing n: JsonField = JsonMissing.of(), + @JsonProperty("parallel_tool_calls") + @ExcludeMissing + parallelToolCalls: JsonField = JsonMissing.of(), + @JsonProperty("presence_penalty") + @ExcludeMissing + presencePenalty: JsonField = JsonMissing.of(), + @JsonProperty("response_format") + @ExcludeMissing + responseFormat: JsonField = JsonMissing.of(), + @JsonProperty("seed") @ExcludeMissing seed: JsonField = JsonMissing.of(), + @JsonProperty("stop") @ExcludeMissing stop: JsonField> = JsonMissing.of(), + @JsonProperty("stream") @ExcludeMissing stream: JsonField = JsonMissing.of(), + @JsonProperty("stream_options") + @ExcludeMissing + streamOptions: JsonField = JsonMissing.of(), + @JsonProperty("temperature") + @ExcludeMissing + temperature: JsonField = JsonMissing.of(), + @JsonProperty("tool_choice") @ExcludeMissing toolChoice: JsonValue = JsonMissing.of(), + @JsonProperty("tools") @ExcludeMissing tools: JsonValue = JsonMissing.of(), + @JsonProperty("top_logprobs") + @ExcludeMissing + topLogprobs: JsonField = JsonMissing.of(), + @JsonProperty("top_p") @ExcludeMissing topP: JsonField = JsonMissing.of(), + @JsonProperty("user") @ExcludeMissing user: JsonField = JsonMissing.of(), + ) : this( + frequencyPenalty, + logitBias, + logprobs, + maxTokens, + messages, + model, + n, + parallelToolCalls, + presencePenalty, + responseFormat, + seed, + stop, + stream, + streamOptions, + temperature, + toolChoice, + tools, + topLogprobs, + topP, + user, + mutableMapOf(), + ) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun frequencyPenalty(): Optional = frequencyPenalty.getOptional("frequency_penalty") + + /** + * LogitBias is must be a token id string (specified by their token ID in the tokenizer), not a + * word string. incorrect: `"logit_bias":{"You": 6}`, correct: `"logit_bias":{"1639": 6}` refs: + * https://platform.openai.com/docs/api-reference/chat/create#chat/create-logit_bias + * + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun logitBias(): Optional = logitBias.getOptional("logit_bias") + + /** + * LogProbs indicates whether to return log probabilities of the output tokens or not. If true, + * returns the log probabilities of each output token returned in the content of message. This + * option is currently not available on the gpt-4-vision-preview model. + * + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun logprobs(): Optional = logprobs.getOptional("logprobs") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun maxTokens(): Optional = maxTokens.getOptional("max_tokens") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun messages(): Optional> = messages.getOptional("messages") + + /** + * @throws ArcadeInvalidDataException 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 ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun n(): Optional = n.getOptional("n") + + /** + * Disable the default behavior of parallel tool calls by setting it: false. + * + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun parallelToolCalls(): Optional = + parallelToolCalls.getOptional("parallel_tool_calls") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun presencePenalty(): Optional = presencePenalty.getOptional("presence_penalty") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun responseFormat(): Optional = responseFormat.getOptional("response_format") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun seed(): Optional = seed.getOptional("seed") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun stop(): Optional> = stop.getOptional("stop") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun stream(): Optional = stream.getOptional("stream") + + /** + * Options for streaming response. Only set this when you set stream: true. + * + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun streamOptions(): Optional = streamOptions.getOptional("stream_options") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun temperature(): Optional = temperature.getOptional("temperature") + + /** + * This can be either a string or an ToolChoice object. + * + * This arbitrary value can be deserialized into a custom type using the `convert` method: + * ```java + * MyClass myObject = chatRequest.toolChoice().convert(MyClass.class); + * ``` + */ + @JsonProperty("tool_choice") @ExcludeMissing fun _toolChoice(): JsonValue = toolChoice + + /** + * This arbitrary value can be deserialized into a custom type using the `convert` method: + * ```java + * MyClass myObject = chatRequest.tools().convert(MyClass.class); + * ``` + */ + @JsonProperty("tools") @ExcludeMissing fun _tools(): JsonValue = tools + + /** + * TopLogProbs is an integer between 0 and 5 specifying the number of most likely tokens to + * return at each token position, each with an associated log probability. logprobs must be set + * to true if this parameter is used. + * + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun topLogprobs(): Optional = topLogprobs.getOptional("top_logprobs") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun topP(): Optional = topP.getOptional("top_p") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun user(): Optional = user.getOptional("user") + + /** + * Returns the raw JSON value of [frequencyPenalty]. + * + * Unlike [frequencyPenalty], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("frequency_penalty") + @ExcludeMissing + fun _frequencyPenalty(): JsonField = frequencyPenalty + + /** + * Returns the raw JSON value of [logitBias]. + * + * Unlike [logitBias], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("logit_bias") @ExcludeMissing fun _logitBias(): JsonField = logitBias + + /** + * Returns the raw JSON value of [logprobs]. + * + * Unlike [logprobs], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("logprobs") @ExcludeMissing fun _logprobs(): JsonField = logprobs + + /** + * Returns the raw JSON value of [maxTokens]. + * + * Unlike [maxTokens], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("max_tokens") @ExcludeMissing fun _maxTokens(): JsonField = maxTokens + + /** + * Returns the raw JSON value of [messages]. + * + * Unlike [messages], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("messages") + @ExcludeMissing + fun _messages(): JsonField> = messages + + /** + * 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 [n]. + * + * Unlike [n], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("n") @ExcludeMissing fun _n(): JsonField = n + + /** + * Returns the raw JSON value of [parallelToolCalls]. + * + * Unlike [parallelToolCalls], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("parallel_tool_calls") + @ExcludeMissing + fun _parallelToolCalls(): JsonField = parallelToolCalls + + /** + * Returns the raw JSON value of [presencePenalty]. + * + * Unlike [presencePenalty], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("presence_penalty") + @ExcludeMissing + fun _presencePenalty(): JsonField = presencePenalty + + /** + * Returns the raw JSON value of [responseFormat]. + * + * Unlike [responseFormat], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("response_format") + @ExcludeMissing + fun _responseFormat(): JsonField = responseFormat + + /** + * Returns the raw JSON value of [seed]. + * + * Unlike [seed], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("seed") @ExcludeMissing fun _seed(): JsonField = seed + + /** + * Returns the raw JSON value of [stop]. + * + * Unlike [stop], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("stop") @ExcludeMissing fun _stop(): JsonField> = stop + + /** + * Returns the raw JSON value of [stream]. + * + * Unlike [stream], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("stream") @ExcludeMissing fun _stream(): JsonField = stream + + /** + * Returns the raw JSON value of [streamOptions]. + * + * Unlike [streamOptions], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("stream_options") + @ExcludeMissing + fun _streamOptions(): JsonField = streamOptions + + /** + * Returns the raw JSON value of [temperature]. + * + * Unlike [temperature], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("temperature") @ExcludeMissing fun _temperature(): JsonField = temperature + + /** + * Returns the raw JSON value of [topLogprobs]. + * + * Unlike [topLogprobs], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("top_logprobs") @ExcludeMissing fun _topLogprobs(): JsonField = topLogprobs + + /** + * Returns the raw JSON value of [topP]. + * + * Unlike [topP], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("top_p") @ExcludeMissing fun _topP(): JsonField = topP + + /** + * Returns the raw JSON value of [user]. + * + * Unlike [user], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user") @ExcludeMissing fun _user(): JsonField = user + + @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 [ChatRequest]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatRequest]. */ + class Builder internal constructor() { + + private var frequencyPenalty: JsonField = JsonMissing.of() + private var logitBias: JsonField = JsonMissing.of() + private var logprobs: JsonField = JsonMissing.of() + private var maxTokens: JsonField = JsonMissing.of() + private var messages: JsonField>? = null + private var model: JsonField = JsonMissing.of() + private var n: JsonField = JsonMissing.of() + private var parallelToolCalls: JsonField = JsonMissing.of() + private var presencePenalty: JsonField = JsonMissing.of() + private var responseFormat: JsonField = JsonMissing.of() + private var seed: JsonField = JsonMissing.of() + private var stop: JsonField>? = null + private var stream: JsonField = JsonMissing.of() + private var streamOptions: JsonField = JsonMissing.of() + private var temperature: JsonField = JsonMissing.of() + private var toolChoice: JsonValue = JsonMissing.of() + private var tools: JsonValue = JsonMissing.of() + private var topLogprobs: JsonField = JsonMissing.of() + private var topP: JsonField = JsonMissing.of() + private var user: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(chatRequest: ChatRequest) = apply { + frequencyPenalty = chatRequest.frequencyPenalty + logitBias = chatRequest.logitBias + logprobs = chatRequest.logprobs + maxTokens = chatRequest.maxTokens + messages = chatRequest.messages.map { it.toMutableList() } + model = chatRequest.model + n = chatRequest.n + parallelToolCalls = chatRequest.parallelToolCalls + presencePenalty = chatRequest.presencePenalty + responseFormat = chatRequest.responseFormat + seed = chatRequest.seed + stop = chatRequest.stop.map { it.toMutableList() } + stream = chatRequest.stream + streamOptions = chatRequest.streamOptions + temperature = chatRequest.temperature + toolChoice = chatRequest.toolChoice + tools = chatRequest.tools + topLogprobs = chatRequest.topLogprobs + topP = chatRequest.topP + user = chatRequest.user + additionalProperties = chatRequest.additionalProperties.toMutableMap() + } + + fun frequencyPenalty(frequencyPenalty: Double) = + frequencyPenalty(JsonField.of(frequencyPenalty)) + + /** + * Sets [Builder.frequencyPenalty] to an arbitrary JSON value. + * + * You should usually call [Builder.frequencyPenalty] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun frequencyPenalty(frequencyPenalty: JsonField) = apply { + this.frequencyPenalty = frequencyPenalty + } + + /** + * LogitBias is must be a token id string (specified by their token ID in the tokenizer), + * not a word string. incorrect: `"logit_bias":{"You": 6}`, correct: `"logit_bias":{"1639": + * 6}` refs: + * https://platform.openai.com/docs/api-reference/chat/create#chat/create-logit_bias + */ + fun logitBias(logitBias: LogitBias) = logitBias(JsonField.of(logitBias)) + + /** + * Sets [Builder.logitBias] to an arbitrary JSON value. + * + * You should usually call [Builder.logitBias] with a well-typed [LogitBias] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun logitBias(logitBias: JsonField) = apply { this.logitBias = logitBias } + + /** + * LogProbs indicates whether to return log probabilities of the output tokens or not. If + * true, returns the log probabilities of each output token returned in the content of + * message. This option is currently not available on the gpt-4-vision-preview model. + */ + fun logprobs(logprobs: Boolean) = logprobs(JsonField.of(logprobs)) + + /** + * Sets [Builder.logprobs] to an arbitrary JSON value. + * + * You should usually call [Builder.logprobs] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun logprobs(logprobs: JsonField) = apply { this.logprobs = logprobs } + + fun maxTokens(maxTokens: Long) = maxTokens(JsonField.of(maxTokens)) + + /** + * Sets [Builder.maxTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.maxTokens] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun maxTokens(maxTokens: JsonField) = apply { this.maxTokens = maxTokens } + + fun messages(messages: List) = messages(JsonField.of(messages)) + + /** + * Sets [Builder.messages] to an arbitrary JSON value. + * + * You should usually call [Builder.messages] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun messages(messages: JsonField>) = apply { + this.messages = messages.map { it.toMutableList() } + } + + /** + * Adds a single [ChatMessage] to [messages]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMessage(message: ChatMessage) = apply { + messages = + (messages ?: JsonField.of(mutableListOf())).also { + checkKnown("messages", it).add(message) + } + } + + 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 n(n: Long) = n(JsonField.of(n)) + + /** + * Sets [Builder.n] to an arbitrary JSON value. + * + * You should usually call [Builder.n] with a well-typed [Long] value instead. This method + * is primarily for setting the field to an undocumented or not yet supported value. + */ + fun n(n: JsonField) = apply { this.n = n } + + /** Disable the default behavior of parallel tool calls by setting it: false. */ + fun parallelToolCalls(parallelToolCalls: Boolean) = + parallelToolCalls(JsonField.of(parallelToolCalls)) + + /** + * Sets [Builder.parallelToolCalls] to an arbitrary JSON value. + * + * You should usually call [Builder.parallelToolCalls] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun parallelToolCalls(parallelToolCalls: JsonField) = apply { + this.parallelToolCalls = parallelToolCalls + } + + fun presencePenalty(presencePenalty: Double) = + presencePenalty(JsonField.of(presencePenalty)) + + /** + * Sets [Builder.presencePenalty] to an arbitrary JSON value. + * + * You should usually call [Builder.presencePenalty] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun presencePenalty(presencePenalty: JsonField) = apply { + this.presencePenalty = presencePenalty + } + + fun responseFormat(responseFormat: ResponseFormat) = + responseFormat(JsonField.of(responseFormat)) + + /** + * Sets [Builder.responseFormat] to an arbitrary JSON value. + * + * You should usually call [Builder.responseFormat] with a well-typed [ResponseFormat] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun responseFormat(responseFormat: JsonField) = apply { + this.responseFormat = responseFormat + } + + fun seed(seed: Long) = seed(JsonField.of(seed)) + + /** + * Sets [Builder.seed] to an arbitrary JSON value. + * + * You should usually call [Builder.seed] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun seed(seed: JsonField) = apply { this.seed = seed } + + fun stop(stop: List) = stop(JsonField.of(stop)) + + /** + * Sets [Builder.stop] to an arbitrary JSON value. + * + * You should usually call [Builder.stop] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun stop(stop: JsonField>) = apply { + this.stop = stop.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [Builder.stop]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addStop(stop: String) = apply { + this.stop = + (this.stop ?: JsonField.of(mutableListOf())).also { + checkKnown("stop", it).add(stop) + } + } + + fun stream(stream: Boolean) = stream(JsonField.of(stream)) + + /** + * Sets [Builder.stream] to an arbitrary JSON value. + * + * You should usually call [Builder.stream] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun stream(stream: JsonField) = apply { this.stream = stream } + + /** Options for streaming response. Only set this when you set stream: true. */ + fun streamOptions(streamOptions: StreamOptions) = streamOptions(JsonField.of(streamOptions)) + + /** + * Sets [Builder.streamOptions] to an arbitrary JSON value. + * + * You should usually call [Builder.streamOptions] with a well-typed [StreamOptions] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun streamOptions(streamOptions: JsonField) = apply { + this.streamOptions = streamOptions + } + + fun temperature(temperature: Double) = temperature(JsonField.of(temperature)) + + /** + * Sets [Builder.temperature] to an arbitrary JSON value. + * + * You should usually call [Builder.temperature] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun temperature(temperature: JsonField) = apply { this.temperature = temperature } + + /** This can be either a string or an ToolChoice object. */ + fun toolChoice(toolChoice: JsonValue) = apply { this.toolChoice = toolChoice } + + fun tools(tools: JsonValue) = apply { this.tools = tools } + + /** + * TopLogProbs is an integer between 0 and 5 specifying the number of most likely tokens to + * return at each token position, each with an associated log probability. logprobs must be + * set to true if this parameter is used. + */ + fun topLogprobs(topLogprobs: Long) = topLogprobs(JsonField.of(topLogprobs)) + + /** + * Sets [Builder.topLogprobs] to an arbitrary JSON value. + * + * You should usually call [Builder.topLogprobs] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun topLogprobs(topLogprobs: JsonField) = apply { this.topLogprobs = topLogprobs } + + fun topP(topP: Double) = topP(JsonField.of(topP)) + + /** + * Sets [Builder.topP] to an arbitrary JSON value. + * + * You should usually call [Builder.topP] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun topP(topP: JsonField) = apply { this.topP = topP } + + fun user(user: String) = user(JsonField.of(user)) + + /** + * Sets [Builder.user] to an arbitrary JSON value. + * + * You should usually call [Builder.user] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun user(user: JsonField) = apply { this.user = user } + + 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 [ChatRequest]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ChatRequest = + ChatRequest( + frequencyPenalty, + logitBias, + logprobs, + maxTokens, + (messages ?: JsonMissing.of()).map { it.toImmutable() }, + model, + n, + parallelToolCalls, + presencePenalty, + responseFormat, + seed, + (stop ?: JsonMissing.of()).map { it.toImmutable() }, + stream, + streamOptions, + temperature, + toolChoice, + tools, + topLogprobs, + topP, + user, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatRequest = apply { + if (validated) { + return@apply + } + + frequencyPenalty() + logitBias().ifPresent { it.validate() } + logprobs() + maxTokens() + messages().ifPresent { it.forEach { it.validate() } } + model() + n() + parallelToolCalls() + presencePenalty() + responseFormat().ifPresent { it.validate() } + seed() + stop() + stream() + streamOptions().ifPresent { it.validate() } + temperature() + topLogprobs() + topP() + user() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (frequencyPenalty.asKnown().isPresent) 1 else 0) + + (logitBias.asKnown().getOrNull()?.validity() ?: 0) + + (if (logprobs.asKnown().isPresent) 1 else 0) + + (if (maxTokens.asKnown().isPresent) 1 else 0) + + (messages.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (model.asKnown().isPresent) 1 else 0) + + (if (n.asKnown().isPresent) 1 else 0) + + (if (parallelToolCalls.asKnown().isPresent) 1 else 0) + + (if (presencePenalty.asKnown().isPresent) 1 else 0) + + (responseFormat.asKnown().getOrNull()?.validity() ?: 0) + + (if (seed.asKnown().isPresent) 1 else 0) + + (stop.asKnown().getOrNull()?.size ?: 0) + + (if (stream.asKnown().isPresent) 1 else 0) + + (streamOptions.asKnown().getOrNull()?.validity() ?: 0) + + (if (temperature.asKnown().isPresent) 1 else 0) + + (if (topLogprobs.asKnown().isPresent) 1 else 0) + + (if (topP.asKnown().isPresent) 1 else 0) + + (if (user.asKnown().isPresent) 1 else 0) + + /** + * LogitBias is must be a token id string (specified by their token ID in the tokenizer), not a + * word string. incorrect: `"logit_bias":{"You": 6}`, correct: `"logit_bias":{"1639": 6}` refs: + * https://platform.openai.com/docs/api-reference/chat/create#chat/create-logit_bias + */ + class LogitBias + @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 [LogitBias]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [LogitBias]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(logitBias: LogitBias) = apply { + additionalProperties = logitBias.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 [LogitBias]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): LogitBias = LogitBias(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): LogitBias = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 LogitBias && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "LogitBias{additionalProperties=$additionalProperties}" + } + + class ResponseFormat + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val type: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of() + ) : this(type, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException 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 [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 [ResponseFormat]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ResponseFormat]. */ + class Builder internal constructor() { + + private var type: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(responseFormat: ResponseFormat) = apply { + type = responseFormat.type + additionalProperties = responseFormat.additionalProperties.toMutableMap() + } + + 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 [ResponseFormat]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ResponseFormat = ResponseFormat(type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): ResponseFormat = apply { + if (validated) { + return@apply + } + + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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) + + 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 JSON_OBJECT = of("json_object") + + @JvmField val TEXT = of("text") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + JSON_OBJECT, + TEXT, + } + + /** + * 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 { + JSON_OBJECT, + TEXT, + /** 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) { + JSON_OBJECT -> Value.JSON_OBJECT + TEXT -> Value.TEXT + 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 ArcadeInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + JSON_OBJECT -> Known.JSON_OBJECT + TEXT -> Known.TEXT + else -> throw ArcadeInvalidDataException("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 ArcadeInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ArcadeInvalidDataException("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: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 ResponseFormat && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ResponseFormat{type=$type, additionalProperties=$additionalProperties}" + } + + /** Options for streaming response. Only set this when you set stream: true. */ + class StreamOptions + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val includeUsage: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("include_usage") + @ExcludeMissing + includeUsage: JsonField = JsonMissing.of() + ) : this(includeUsage, mutableMapOf()) + + /** + * If set, an additional chunk will be streamed before the data: [DONE] message. The usage + * field on this chunk shows the token usage statistics for the entire request, and the + * choices field will always be an empty array. All other chunks will also include a usage + * field, but with a null value. + * + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun includeUsage(): Optional = includeUsage.getOptional("include_usage") + + /** + * Returns the raw JSON value of [includeUsage]. + * + * Unlike [includeUsage], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("include_usage") + @ExcludeMissing + fun _includeUsage(): JsonField = includeUsage + + @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 [StreamOptions]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [StreamOptions]. */ + class Builder internal constructor() { + + private var includeUsage: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(streamOptions: StreamOptions) = apply { + includeUsage = streamOptions.includeUsage + additionalProperties = streamOptions.additionalProperties.toMutableMap() + } + + /** + * If set, an additional chunk will be streamed before the data: [DONE] message. The + * usage field on this chunk shows the token usage statistics for the entire request, + * and the choices field will always be an empty array. All other chunks will also + * include a usage field, but with a null value. + */ + fun includeUsage(includeUsage: Boolean) = includeUsage(JsonField.of(includeUsage)) + + /** + * Sets [Builder.includeUsage] to an arbitrary JSON value. + * + * You should usually call [Builder.includeUsage] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun includeUsage(includeUsage: JsonField) = apply { + this.includeUsage = includeUsage + } + + 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 [StreamOptions]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): StreamOptions = + StreamOptions(includeUsage, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): StreamOptions = apply { + if (validated) { + return@apply + } + + includeUsage() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (includeUsage.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is StreamOptions && + includeUsage == other.includeUsage && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(includeUsage, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "StreamOptions{includeUsage=$includeUsage, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatRequest && + frequencyPenalty == other.frequencyPenalty && + logitBias == other.logitBias && + logprobs == other.logprobs && + maxTokens == other.maxTokens && + messages == other.messages && + model == other.model && + n == other.n && + parallelToolCalls == other.parallelToolCalls && + presencePenalty == other.presencePenalty && + responseFormat == other.responseFormat && + seed == other.seed && + stop == other.stop && + stream == other.stream && + streamOptions == other.streamOptions && + temperature == other.temperature && + toolChoice == other.toolChoice && + tools == other.tools && + topLogprobs == other.topLogprobs && + topP == other.topP && + user == other.user && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + frequencyPenalty, + logitBias, + logprobs, + maxTokens, + messages, + model, + n, + parallelToolCalls, + presencePenalty, + responseFormat, + seed, + stop, + stream, + streamOptions, + temperature, + toolChoice, + tools, + topLogprobs, + topP, + user, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatRequest{frequencyPenalty=$frequencyPenalty, logitBias=$logitBias, logprobs=$logprobs, maxTokens=$maxTokens, messages=$messages, model=$model, n=$n, parallelToolCalls=$parallelToolCalls, presencePenalty=$presencePenalty, responseFormat=$responseFormat, seed=$seed, stop=$stop, stream=$stream, streamOptions=$streamOptions, temperature=$temperature, toolChoice=$toolChoice, tools=$tools, topLogprobs=$topLogprobs, topP=$topP, user=$user, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/chat/ChatResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/chat/ChatResponse.kt new file mode 100644 index 0000000..20f907b --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/chat/ChatResponse.kt @@ -0,0 +1,384 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.chat + +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 dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.core.checkKnown +import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class ChatResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val id: JsonField, + private val choices: JsonField>, + private val created: JsonField, + private val model: JsonField, + private val object_: JsonField, + private val systemFingerprint: JsonField, + private val usage: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("choices") + @ExcludeMissing + choices: JsonField> = JsonMissing.of(), + @JsonProperty("created") @ExcludeMissing created: JsonField = JsonMissing.of(), + @JsonProperty("model") @ExcludeMissing model: JsonField = JsonMissing.of(), + @JsonProperty("object") @ExcludeMissing object_: JsonField = JsonMissing.of(), + @JsonProperty("system_fingerprint") + @ExcludeMissing + systemFingerprint: JsonField = JsonMissing.of(), + @JsonProperty("usage") @ExcludeMissing usage: JsonField = JsonMissing.of(), + ) : this(id, choices, created, model, object_, systemFingerprint, usage, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun choices(): Optional> = choices.getOptional("choices") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun created(): Optional = created.getOptional("created") + + /** + * @throws ArcadeInvalidDataException 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 ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun object_(): Optional = object_.getOptional("object") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun systemFingerprint(): Optional = systemFingerprint.getOptional("system_fingerprint") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun usage(): Optional = usage.getOptional("usage") + + /** + * 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 [choices]. + * + * Unlike [choices], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("choices") @ExcludeMissing fun _choices(): JsonField> = choices + + /** + * Returns the raw JSON value of [created]. + * + * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created + + /** + * 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 [object_]. + * + * Unlike [object_], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("object") @ExcludeMissing fun _object_(): JsonField = object_ + + /** + * Returns the raw JSON value of [systemFingerprint]. + * + * Unlike [systemFingerprint], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("system_fingerprint") + @ExcludeMissing + fun _systemFingerprint(): JsonField = systemFingerprint + + /** + * Returns the raw JSON value of [usage]. + * + * Unlike [usage], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("usage") @ExcludeMissing fun _usage(): JsonField = usage + + @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 [ChatResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatResponse]. */ + class Builder internal constructor() { + + private var id: JsonField = JsonMissing.of() + private var choices: JsonField>? = null + private var created: JsonField = JsonMissing.of() + private var model: JsonField = JsonMissing.of() + private var object_: JsonField = JsonMissing.of() + private var systemFingerprint: JsonField = JsonMissing.of() + private var usage: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(chatResponse: ChatResponse) = apply { + id = chatResponse.id + choices = chatResponse.choices.map { it.toMutableList() } + created = chatResponse.created + model = chatResponse.model + object_ = chatResponse.object_ + systemFingerprint = chatResponse.systemFingerprint + usage = chatResponse.usage + additionalProperties = chatResponse.additionalProperties.toMutableMap() + } + + 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 choices(choices: List) = choices(JsonField.of(choices)) + + /** + * Sets [Builder.choices] to an arbitrary JSON value. + * + * You should usually call [Builder.choices] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun choices(choices: JsonField>) = apply { + this.choices = choices.map { it.toMutableList() } + } + + /** + * Adds a single [Choice] to [choices]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addChoice(choice: Choice) = apply { + choices = + (choices ?: JsonField.of(mutableListOf())).also { + checkKnown("choices", it).add(choice) + } + } + + fun created(created: Long) = created(JsonField.of(created)) + + /** + * Sets [Builder.created] to an arbitrary JSON value. + * + * You should usually call [Builder.created] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun created(created: JsonField) = apply { this.created = created } + + 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 object_(object_: String) = object_(JsonField.of(object_)) + + /** + * Sets [Builder.object_] to an arbitrary JSON value. + * + * You should usually call [Builder.object_] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun object_(object_: JsonField) = apply { this.object_ = object_ } + + fun systemFingerprint(systemFingerprint: String) = + systemFingerprint(JsonField.of(systemFingerprint)) + + /** + * Sets [Builder.systemFingerprint] to an arbitrary JSON value. + * + * You should usually call [Builder.systemFingerprint] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun systemFingerprint(systemFingerprint: JsonField) = apply { + this.systemFingerprint = systemFingerprint + } + + fun usage(usage: Usage) = usage(JsonField.of(usage)) + + /** + * Sets [Builder.usage] to an arbitrary JSON value. + * + * You should usually call [Builder.usage] with a well-typed [Usage] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun usage(usage: JsonField) = apply { this.usage = usage } + + 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 [ChatResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ChatResponse = + ChatResponse( + id, + (choices ?: JsonMissing.of()).map { it.toImmutable() }, + created, + model, + object_, + systemFingerprint, + usage, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ChatResponse = apply { + if (validated) { + return@apply + } + + id() + choices().ifPresent { it.forEach { it.validate() } } + created() + model() + object_() + systemFingerprint() + usage().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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) + + (choices.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (created.asKnown().isPresent) 1 else 0) + + (if (model.asKnown().isPresent) 1 else 0) + + (if (object_.asKnown().isPresent) 1 else 0) + + (if (systemFingerprint.asKnown().isPresent) 1 else 0) + + (usage.asKnown().getOrNull()?.validity() ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatResponse && + id == other.id && + choices == other.choices && + created == other.created && + model == other.model && + object_ == other.object_ && + systemFingerprint == other.systemFingerprint && + usage == other.usage && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + choices, + created, + model, + object_, + systemFingerprint, + usage, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatResponse{id=$id, choices=$choices, created=$created, model=$model, object_=$object_, systemFingerprint=$systemFingerprint, usage=$usage, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/chat/Choice.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/chat/Choice.kt new file mode 100644 index 0000000..e652d4e --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/chat/Choice.kt @@ -0,0 +1,369 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.chat + +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 dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.core.checkKnown +import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import dev.arcade.models.AuthorizationResponse +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class Choice +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val finishReason: JsonField, + private val index: JsonField, + private val logprobs: JsonValue, + private val message: JsonField, + private val toolAuthorizations: JsonField>, + private val toolMessages: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("finish_reason") + @ExcludeMissing + finishReason: JsonField = JsonMissing.of(), + @JsonProperty("index") @ExcludeMissing index: JsonField = JsonMissing.of(), + @JsonProperty("logprobs") @ExcludeMissing logprobs: JsonValue = JsonMissing.of(), + @JsonProperty("message") @ExcludeMissing message: JsonField = JsonMissing.of(), + @JsonProperty("tool_authorizations") + @ExcludeMissing + toolAuthorizations: JsonField> = JsonMissing.of(), + @JsonProperty("tool_messages") + @ExcludeMissing + toolMessages: JsonField> = JsonMissing.of(), + ) : this( + finishReason, + index, + logprobs, + message, + toolAuthorizations, + toolMessages, + mutableMapOf(), + ) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun finishReason(): Optional = finishReason.getOptional("finish_reason") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun index(): Optional = index.getOptional("index") + + /** + * This arbitrary value can be deserialized into a custom type using the `convert` method: + * ```java + * MyClass myObject = choice.logprobs().convert(MyClass.class); + * ``` + */ + @JsonProperty("logprobs") @ExcludeMissing fun _logprobs(): JsonValue = logprobs + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun message(): Optional = message.getOptional("message") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun toolAuthorizations(): Optional> = + toolAuthorizations.getOptional("tool_authorizations") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun toolMessages(): Optional> = toolMessages.getOptional("tool_messages") + + /** + * Returns the raw JSON value of [finishReason]. + * + * Unlike [finishReason], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("finish_reason") + @ExcludeMissing + fun _finishReason(): JsonField = finishReason + + /** + * Returns the raw JSON value of [index]. + * + * Unlike [index], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("index") @ExcludeMissing fun _index(): JsonField = index + + /** + * Returns the raw JSON value of [message]. + * + * Unlike [message], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("message") @ExcludeMissing fun _message(): JsonField = message + + /** + * Returns the raw JSON value of [toolAuthorizations]. + * + * Unlike [toolAuthorizations], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("tool_authorizations") + @ExcludeMissing + fun _toolAuthorizations(): JsonField> = toolAuthorizations + + /** + * Returns the raw JSON value of [toolMessages]. + * + * Unlike [toolMessages], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tool_messages") + @ExcludeMissing + fun _toolMessages(): JsonField> = toolMessages + + @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 [Choice]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Choice]. */ + class Builder internal constructor() { + + private var finishReason: JsonField = JsonMissing.of() + private var index: JsonField = JsonMissing.of() + private var logprobs: JsonValue = JsonMissing.of() + private var message: JsonField = JsonMissing.of() + private var toolAuthorizations: JsonField>? = null + private var toolMessages: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(choice: Choice) = apply { + finishReason = choice.finishReason + index = choice.index + logprobs = choice.logprobs + message = choice.message + toolAuthorizations = choice.toolAuthorizations.map { it.toMutableList() } + toolMessages = choice.toolMessages.map { it.toMutableList() } + additionalProperties = choice.additionalProperties.toMutableMap() + } + + fun finishReason(finishReason: String) = finishReason(JsonField.of(finishReason)) + + /** + * Sets [Builder.finishReason] to an arbitrary JSON value. + * + * You should usually call [Builder.finishReason] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun finishReason(finishReason: JsonField) = apply { + this.finishReason = finishReason + } + + fun index(index: Long) = index(JsonField.of(index)) + + /** + * Sets [Builder.index] to an arbitrary JSON value. + * + * You should usually call [Builder.index] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun index(index: JsonField) = apply { this.index = index } + + fun logprobs(logprobs: JsonValue) = apply { this.logprobs = logprobs } + + fun message(message: ChatMessage) = message(JsonField.of(message)) + + /** + * Sets [Builder.message] to an arbitrary JSON value. + * + * You should usually call [Builder.message] with a well-typed [ChatMessage] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun message(message: JsonField) = apply { this.message = message } + + fun toolAuthorizations(toolAuthorizations: List) = + toolAuthorizations(JsonField.of(toolAuthorizations)) + + /** + * Sets [Builder.toolAuthorizations] to an arbitrary JSON value. + * + * You should usually call [Builder.toolAuthorizations] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun toolAuthorizations(toolAuthorizations: JsonField>) = apply { + this.toolAuthorizations = toolAuthorizations.map { it.toMutableList() } + } + + /** + * Adds a single [AuthorizationResponse] to [toolAuthorizations]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addToolAuthorization(toolAuthorization: AuthorizationResponse) = apply { + toolAuthorizations = + (toolAuthorizations ?: JsonField.of(mutableListOf())).also { + checkKnown("toolAuthorizations", it).add(toolAuthorization) + } + } + + fun toolMessages(toolMessages: List) = toolMessages(JsonField.of(toolMessages)) + + /** + * Sets [Builder.toolMessages] to an arbitrary JSON value. + * + * You should usually call [Builder.toolMessages] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun toolMessages(toolMessages: JsonField>) = apply { + this.toolMessages = toolMessages.map { it.toMutableList() } + } + + /** + * Adds a single [ChatMessage] to [toolMessages]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addToolMessage(toolMessage: ChatMessage) = apply { + toolMessages = + (toolMessages ?: JsonField.of(mutableListOf())).also { + checkKnown("toolMessages", it).add(toolMessage) + } + } + + 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 [Choice]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Choice = + Choice( + finishReason, + index, + logprobs, + message, + (toolAuthorizations ?: JsonMissing.of()).map { it.toImmutable() }, + (toolMessages ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Choice = apply { + if (validated) { + return@apply + } + + finishReason() + index() + message().ifPresent { it.validate() } + toolAuthorizations().ifPresent { it.forEach { it.validate() } } + toolMessages().ifPresent { it.forEach { it.validate() } } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (finishReason.asKnown().isPresent) 1 else 0) + + (if (index.asKnown().isPresent) 1 else 0) + + (message.asKnown().getOrNull()?.validity() ?: 0) + + (toolAuthorizations.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (toolMessages.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Choice && + finishReason == other.finishReason && + index == other.index && + logprobs == other.logprobs && + message == other.message && + toolAuthorizations == other.toolAuthorizations && + toolMessages == other.toolMessages && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + finishReason, + index, + logprobs, + message, + toolAuthorizations, + toolMessages, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Choice{finishReason=$finishReason, index=$index, logprobs=$logprobs, message=$message, toolAuthorizations=$toolAuthorizations, toolMessages=$toolMessages, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/chat/Usage.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/chat/Usage.kt new file mode 100644 index 0000000..2166b90 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/chat/Usage.kt @@ -0,0 +1,234 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.chat + +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 dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional + +class Usage +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val completionTokens: JsonField, + private val promptTokens: JsonField, + private val totalTokens: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("completion_tokens") + @ExcludeMissing + completionTokens: JsonField = JsonMissing.of(), + @JsonProperty("prompt_tokens") + @ExcludeMissing + promptTokens: JsonField = JsonMissing.of(), + @JsonProperty("total_tokens") + @ExcludeMissing + totalTokens: JsonField = JsonMissing.of(), + ) : this(completionTokens, promptTokens, totalTokens, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun completionTokens(): Optional = completionTokens.getOptional("completion_tokens") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun promptTokens(): Optional = promptTokens.getOptional("prompt_tokens") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun totalTokens(): Optional = totalTokens.getOptional("total_tokens") + + /** + * Returns the raw JSON value of [completionTokens]. + * + * Unlike [completionTokens], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("completion_tokens") + @ExcludeMissing + fun _completionTokens(): JsonField = completionTokens + + /** + * Returns the raw JSON value of [promptTokens]. + * + * Unlike [promptTokens], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("prompt_tokens") + @ExcludeMissing + fun _promptTokens(): JsonField = promptTokens + + /** + * Returns the raw JSON value of [totalTokens]. + * + * Unlike [totalTokens], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("total_tokens") @ExcludeMissing fun _totalTokens(): JsonField = totalTokens + + @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 [Usage]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Usage]. */ + class Builder internal constructor() { + + private var completionTokens: JsonField = JsonMissing.of() + private var promptTokens: JsonField = JsonMissing.of() + private var totalTokens: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(usage: Usage) = apply { + completionTokens = usage.completionTokens + promptTokens = usage.promptTokens + totalTokens = usage.totalTokens + additionalProperties = usage.additionalProperties.toMutableMap() + } + + fun completionTokens(completionTokens: Long) = + completionTokens(JsonField.of(completionTokens)) + + /** + * Sets [Builder.completionTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.completionTokens] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun completionTokens(completionTokens: JsonField) = apply { + this.completionTokens = completionTokens + } + + fun promptTokens(promptTokens: Long) = promptTokens(JsonField.of(promptTokens)) + + /** + * Sets [Builder.promptTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.promptTokens] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun promptTokens(promptTokens: JsonField) = apply { this.promptTokens = promptTokens } + + fun totalTokens(totalTokens: Long) = totalTokens(JsonField.of(totalTokens)) + + /** + * Sets [Builder.totalTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.totalTokens] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun totalTokens(totalTokens: JsonField) = apply { this.totalTokens = totalTokens } + + 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 [Usage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Usage = + Usage(completionTokens, promptTokens, totalTokens, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Usage = apply { + if (validated) { + return@apply + } + + completionTokens() + promptTokens() + totalTokens() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (completionTokens.asKnown().isPresent) 1 else 0) + + (if (promptTokens.asKnown().isPresent) 1 else 0) + + (if (totalTokens.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Usage && + completionTokens == other.completionTokens && + promptTokens == other.promptTokens && + totalTokens == other.totalTokens && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(completionTokens, promptTokens, totalTokens, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Usage{completionTokens=$completionTokens, promptTokens=$promptTokens, totalTokens=$totalTokens, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ChatCompletionCreateParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/chat/completions/CompletionCreateParams.kt similarity index 75% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/ChatCompletionCreateParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/chat/completions/CompletionCreateParams.kt index 5ca16cb..857830c 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ChatCompletionCreateParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/chat/completions/CompletionCreateParams.kt @@ -1,17 +1,17 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.chat.completions import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params import dev.arcade.core.checkRequired import dev.arcade.core.http.Headers import dev.arcade.core.http.QueryParams +import dev.arcade.models.chat.ChatRequest import java.util.Objects /** Interact with language models via OpenAI's chat completions API */ -class ChatCompletionCreateParams +class CompletionCreateParams private constructor( private val chatRequest: ChatRequest, private val additionalHeaders: Headers, @@ -22,25 +22,28 @@ private constructor( fun _additionalBodyProperties(): Map = chatRequest._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): ChatRequest = chatRequest - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [CompletionCreateParams]. + * + * The following fields are required: + * ```java + * .chatRequest() + * ``` + */ @JvmStatic fun builder() = Builder() } - /** A builder for [ChatCompletionCreateParams]. */ - @NoAutoDetect + /** A builder for [CompletionCreateParams]. */ class Builder internal constructor() { private var chatRequest: ChatRequest? = null @@ -48,10 +51,10 @@ private constructor( private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @JvmSynthetic - internal fun from(chatCompletionCreateParams: ChatCompletionCreateParams) = apply { - chatRequest = chatCompletionCreateParams.chatRequest - additionalHeaders = chatCompletionCreateParams.additionalHeaders.toBuilder() - additionalQueryParams = chatCompletionCreateParams.additionalQueryParams.toBuilder() + internal fun from(completionCreateParams: CompletionCreateParams) = apply { + chatRequest = completionCreateParams.chatRequest + additionalHeaders = completionCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = completionCreateParams.additionalQueryParams.toBuilder() } fun chatRequest(chatRequest: ChatRequest) = apply { this.chatRequest = chatRequest } @@ -154,24 +157,46 @@ private constructor( additionalQueryParams.removeAll(keys) } - fun build(): ChatCompletionCreateParams = - ChatCompletionCreateParams( + /** + * Returns an immutable instance of [CompletionCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .chatRequest() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): CompletionCreateParams = + CompletionCreateParams( checkRequired("chatRequest", chatRequest), additionalHeaders.build(), additionalQueryParams.build(), ) } + fun _body(): ChatRequest = chatRequest + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is ChatCompletionCreateParams && chatRequest == other.chatRequest && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is CompletionCreateParams && + chatRequest == other.chatRequest && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(chatRequest, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(chatRequest, additionalHeaders, additionalQueryParams) override fun toString() = - "ChatCompletionCreateParams{chatRequest=$chatRequest, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" + "CompletionCreateParams{chatRequest=$chatRequest, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/HealthCheckParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/health/HealthCheckParams.kt similarity index 87% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/HealthCheckParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/health/HealthCheckParams.kt index 8f15329..48d9aee 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/HealthCheckParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/health/HealthCheckParams.kt @@ -1,8 +1,7 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.health -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params import dev.arcade.core.http.Headers import dev.arcade.core.http.QueryParams @@ -15,23 +14,23 @@ private constructor( 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 - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): HealthCheckParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [HealthCheckParams]. */ @JvmStatic fun builder() = Builder() } /** A builder for [HealthCheckParams]. */ - @NoAutoDetect class Builder internal constructor() { private var additionalHeaders: Headers.Builder = Headers.builder() @@ -141,19 +140,30 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [HealthCheckParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): HealthCheckParams = HealthCheckParams(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 /* spotless:off */ other is HealthCheckParams && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is HealthCheckParams && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(additionalHeaders, additionalQueryParams) override fun toString() = "HealthCheckParams{additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/health/HealthSchema.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/health/HealthSchema.kt new file mode 100644 index 0000000..27720dd --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/health/HealthSchema.kt @@ -0,0 +1,187 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.health + +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 dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional + +class HealthSchema +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val healthy: JsonField, + private val reason: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("healthy") @ExcludeMissing healthy: JsonField = JsonMissing.of(), + @JsonProperty("reason") @ExcludeMissing reason: JsonField = JsonMissing.of(), + ) : this(healthy, reason, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun healthy(): Optional = healthy.getOptional("healthy") + + /** + * Optional: explains why unhealthy + * + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun reason(): Optional = reason.getOptional("reason") + + /** + * Returns the raw JSON value of [healthy]. + * + * Unlike [healthy], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("healthy") @ExcludeMissing fun _healthy(): JsonField = healthy + + /** + * 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 [HealthSchema]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [HealthSchema]. */ + class Builder internal constructor() { + + private var healthy: JsonField = JsonMissing.of() + private var reason: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(healthSchema: HealthSchema) = apply { + healthy = healthSchema.healthy + reason = healthSchema.reason + additionalProperties = healthSchema.additionalProperties.toMutableMap() + } + + fun healthy(healthy: Boolean) = healthy(JsonField.of(healthy)) + + /** + * Sets [Builder.healthy] to an arbitrary JSON value. + * + * You should usually call [Builder.healthy] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun healthy(healthy: JsonField) = apply { this.healthy = healthy } + + /** Optional: explains why unhealthy */ + 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 [HealthSchema]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): HealthSchema = + HealthSchema(healthy, reason, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): HealthSchema = apply { + if (validated) { + return@apply + } + + healthy() + reason() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (healthy.asKnown().isPresent) 1 else 0) + (if (reason.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is HealthSchema && + healthy == other.healthy && + reason == other.reason && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(healthy, reason, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "HealthSchema{healthy=$healthy, reason=$reason, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/AuthorizeToolRequest.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/AuthorizeToolRequest.kt new file mode 100644 index 0000000..4842ecd --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/AuthorizeToolRequest.kt @@ -0,0 +1,282 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.tools + +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 dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.core.checkRequired +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional + +class AuthorizeToolRequest +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val toolName: JsonField, + private val nextUri: JsonField, + private val toolVersion: JsonField, + private val userId: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("tool_name") @ExcludeMissing toolName: JsonField = JsonMissing.of(), + @JsonProperty("next_uri") @ExcludeMissing nextUri: JsonField = JsonMissing.of(), + @JsonProperty("tool_version") + @ExcludeMissing + toolVersion: JsonField = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + ) : this(toolName, nextUri, toolVersion, userId, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException 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 toolName(): String = toolName.getRequired("tool_name") + + /** + * Optional: if provided, the user will be redirected to this URI after authorization + * + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun nextUri(): Optional = nextUri.getOptional("next_uri") + + /** + * Optional: if not provided, any version is used + * + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun toolVersion(): Optional = toolVersion.getOptional("tool_version") + + /** + * Required only when calling with an API key + * + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun userId(): Optional = userId.getOptional("user_id") + + /** + * Returns the raw JSON value of [toolName]. + * + * Unlike [toolName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tool_name") @ExcludeMissing fun _toolName(): JsonField = toolName + + /** + * Returns the raw JSON value of [nextUri]. + * + * Unlike [nextUri], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("next_uri") @ExcludeMissing fun _nextUri(): JsonField = nextUri + + /** + * Returns the raw JSON value of [toolVersion]. + * + * Unlike [toolVersion], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tool_version") + @ExcludeMissing + fun _toolVersion(): JsonField = toolVersion + + /** + * Returns the raw JSON value of [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + + @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 [AuthorizeToolRequest]. + * + * The following fields are required: + * ```java + * .toolName() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AuthorizeToolRequest]. */ + class Builder internal constructor() { + + private var toolName: JsonField? = null + private var nextUri: JsonField = JsonMissing.of() + private var toolVersion: JsonField = JsonMissing.of() + private var userId: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(authorizeToolRequest: AuthorizeToolRequest) = apply { + toolName = authorizeToolRequest.toolName + nextUri = authorizeToolRequest.nextUri + toolVersion = authorizeToolRequest.toolVersion + userId = authorizeToolRequest.userId + additionalProperties = authorizeToolRequest.additionalProperties.toMutableMap() + } + + fun toolName(toolName: String) = toolName(JsonField.of(toolName)) + + /** + * Sets [Builder.toolName] to an arbitrary JSON value. + * + * You should usually call [Builder.toolName] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun toolName(toolName: JsonField) = apply { this.toolName = toolName } + + /** Optional: if provided, the user will be redirected to this URI after authorization */ + fun nextUri(nextUri: String) = nextUri(JsonField.of(nextUri)) + + /** + * Sets [Builder.nextUri] to an arbitrary JSON value. + * + * You should usually call [Builder.nextUri] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun nextUri(nextUri: JsonField) = apply { this.nextUri = nextUri } + + /** Optional: if not provided, any version is used */ + fun toolVersion(toolVersion: String) = toolVersion(JsonField.of(toolVersion)) + + /** + * Sets [Builder.toolVersion] to an arbitrary JSON value. + * + * You should usually call [Builder.toolVersion] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun toolVersion(toolVersion: JsonField) = apply { this.toolVersion = toolVersion } + + /** Required only when calling with an API key */ + fun userId(userId: String) = userId(JsonField.of(userId)) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun userId(userId: JsonField) = apply { this.userId = userId } + + 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 [AuthorizeToolRequest]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .toolName() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AuthorizeToolRequest = + AuthorizeToolRequest( + checkRequired("toolName", toolName), + nextUri, + toolVersion, + userId, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): AuthorizeToolRequest = apply { + if (validated) { + return@apply + } + + toolName() + nextUri() + toolVersion() + userId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (toolName.asKnown().isPresent) 1 else 0) + + (if (nextUri.asKnown().isPresent) 1 else 0) + + (if (toolVersion.asKnown().isPresent) 1 else 0) + + (if (userId.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AuthorizeToolRequest && + toolName == other.toolName && + nextUri == other.nextUri && + toolVersion == other.toolVersion && + userId == other.userId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(toolName, nextUri, toolVersion, userId, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AuthorizeToolRequest{toolName=$toolName, nextUri=$nextUri, toolVersion=$toolVersion, userId=$userId, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ExecuteToolRequest.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ExecuteToolRequest.kt new file mode 100644 index 0000000..487040d --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ExecuteToolRequest.kt @@ -0,0 +1,483 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.tools + +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 dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.core.checkRequired +import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class ExecuteToolRequest +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val toolName: JsonField, + private val includeErrorStacktrace: JsonField, + private val input: JsonField, + private val runAt: JsonField, + private val toolVersion: JsonField, + private val userId: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("tool_name") @ExcludeMissing toolName: JsonField = JsonMissing.of(), + @JsonProperty("include_error_stacktrace") + @ExcludeMissing + includeErrorStacktrace: JsonField = JsonMissing.of(), + @JsonProperty("input") @ExcludeMissing input: JsonField = JsonMissing.of(), + @JsonProperty("run_at") @ExcludeMissing runAt: JsonField = JsonMissing.of(), + @JsonProperty("tool_version") + @ExcludeMissing + toolVersion: JsonField = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + ) : this(toolName, includeErrorStacktrace, input, runAt, toolVersion, userId, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException 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 toolName(): String = toolName.getRequired("tool_name") + + /** + * Whether to include the error stacktrace in the response. If not provided, the error + * stacktrace is not included. + * + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun includeErrorStacktrace(): Optional = + includeErrorStacktrace.getOptional("include_error_stacktrace") + + /** + * JSON input to the tool, if any + * + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun input(): Optional = input.getOptional("input") + + /** + * The time at which the tool should be run (optional). If not provided, the tool is run + * immediately. Format ISO 8601: YYYY-MM-DDTHH:MM:SS + * + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun runAt(): Optional = runAt.getOptional("run_at") + + /** + * The tool version to use (optional). If not provided, any version is used + * + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun toolVersion(): Optional = toolVersion.getOptional("tool_version") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun userId(): Optional = userId.getOptional("user_id") + + /** + * Returns the raw JSON value of [toolName]. + * + * Unlike [toolName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tool_name") @ExcludeMissing fun _toolName(): JsonField = toolName + + /** + * Returns the raw JSON value of [includeErrorStacktrace]. + * + * Unlike [includeErrorStacktrace], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("include_error_stacktrace") + @ExcludeMissing + fun _includeErrorStacktrace(): JsonField = includeErrorStacktrace + + /** + * 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 [runAt]. + * + * Unlike [runAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("run_at") @ExcludeMissing fun _runAt(): JsonField = runAt + + /** + * Returns the raw JSON value of [toolVersion]. + * + * Unlike [toolVersion], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tool_version") + @ExcludeMissing + fun _toolVersion(): JsonField = toolVersion + + /** + * Returns the raw JSON value of [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + + @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 [ExecuteToolRequest]. + * + * The following fields are required: + * ```java + * .toolName() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ExecuteToolRequest]. */ + class Builder internal constructor() { + + private var toolName: JsonField? = null + private var includeErrorStacktrace: JsonField = JsonMissing.of() + private var input: JsonField = JsonMissing.of() + private var runAt: JsonField = JsonMissing.of() + private var toolVersion: JsonField = JsonMissing.of() + private var userId: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(executeToolRequest: ExecuteToolRequest) = apply { + toolName = executeToolRequest.toolName + includeErrorStacktrace = executeToolRequest.includeErrorStacktrace + input = executeToolRequest.input + runAt = executeToolRequest.runAt + toolVersion = executeToolRequest.toolVersion + userId = executeToolRequest.userId + additionalProperties = executeToolRequest.additionalProperties.toMutableMap() + } + + fun toolName(toolName: String) = toolName(JsonField.of(toolName)) + + /** + * Sets [Builder.toolName] to an arbitrary JSON value. + * + * You should usually call [Builder.toolName] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun toolName(toolName: JsonField) = apply { this.toolName = toolName } + + /** + * Whether to include the error stacktrace in the response. If not provided, the error + * stacktrace is not included. + */ + fun includeErrorStacktrace(includeErrorStacktrace: Boolean) = + includeErrorStacktrace(JsonField.of(includeErrorStacktrace)) + + /** + * Sets [Builder.includeErrorStacktrace] to an arbitrary JSON value. + * + * You should usually call [Builder.includeErrorStacktrace] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun includeErrorStacktrace(includeErrorStacktrace: JsonField) = apply { + this.includeErrorStacktrace = includeErrorStacktrace + } + + /** JSON input to the tool, if any */ + fun input(input: Input) = input(JsonField.of(input)) + + /** JSON input to the tool, if any */ + fun input(input: Map) = input(Input.from(input)) + + /** + * Sets [Builder.input] to an arbitrary JSON value. + * + * You should usually call [Builder.input] with a well-typed [Input] 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 } + + /** + * The time at which the tool should be run (optional). If not provided, the tool is run + * immediately. Format ISO 8601: YYYY-MM-DDTHH:MM:SS + */ + fun runAt(runAt: String) = runAt(JsonField.of(runAt)) + + /** + * Sets [Builder.runAt] to an arbitrary JSON value. + * + * You should usually call [Builder.runAt] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun runAt(runAt: JsonField) = apply { this.runAt = runAt } + + /** The tool version to use (optional). If not provided, any version is used */ + fun toolVersion(toolVersion: String) = toolVersion(JsonField.of(toolVersion)) + + /** + * Sets [Builder.toolVersion] to an arbitrary JSON value. + * + * You should usually call [Builder.toolVersion] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun toolVersion(toolVersion: JsonField) = apply { this.toolVersion = toolVersion } + + fun userId(userId: String) = userId(JsonField.of(userId)) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun userId(userId: JsonField) = apply { this.userId = userId } + + 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 [ExecuteToolRequest]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .toolName() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ExecuteToolRequest = + ExecuteToolRequest( + checkRequired("toolName", toolName), + includeErrorStacktrace, + input, + runAt, + toolVersion, + userId, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ExecuteToolRequest = apply { + if (validated) { + return@apply + } + + toolName() + includeErrorStacktrace() + input().ifPresent { it.validate() } + runAt() + toolVersion() + userId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (toolName.asKnown().isPresent) 1 else 0) + + (if (includeErrorStacktrace.asKnown().isPresent) 1 else 0) + + (input.asKnown().getOrNull()?.validity() ?: 0) + + (if (runAt.asKnown().isPresent) 1 else 0) + + (if (toolVersion.asKnown().isPresent) 1 else 0) + + (if (userId.asKnown().isPresent) 1 else 0) + + /** JSON input to the tool, if any */ + class Input + @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 [Input]. */ + @JvmStatic fun builder() = Builder() + + /** Converts a Map of input objects to an [Input] Map. */ + @JvmStatic + fun from(input: Map) = + Input(input.mapValues { (_, value) -> JsonValue.from(value) }) + } + + /** A builder for [Input]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(input: Input) = apply { + additionalProperties = input.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 [Input]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Input = Input(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Input = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 Input && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Input{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ExecuteToolRequest && + toolName == other.toolName && + includeErrorStacktrace == other.includeErrorStacktrace && + input == other.input && + runAt == other.runAt && + toolVersion == other.toolVersion && + userId == other.userId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + toolName, + includeErrorStacktrace, + input, + runAt, + toolVersion, + userId, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ExecuteToolRequest{toolName=$toolName, includeErrorStacktrace=$includeErrorStacktrace, input=$input, runAt=$runAt, toolVersion=$toolVersion, userId=$userId, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ExecuteToolResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ExecuteToolResponse.kt new file mode 100644 index 0000000..eb5c67b --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ExecuteToolResponse.kt @@ -0,0 +1,1857 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.tools + +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 dev.arcade.core.Enum +import dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonArray +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonObject +import dev.arcade.core.JsonValue +import dev.arcade.core.checkKnown +import dev.arcade.core.checkRequired +import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import dev.arcade.models.AuthorizationResponse +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class ExecuteToolResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val id: JsonField, + private val duration: JsonField, + private val executionId: JsonField, + private val executionType: JsonField, + private val finishedAt: JsonField, + private val output: JsonField, + private val runAt: JsonField, + private val status: JsonField, + private val success: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("duration") @ExcludeMissing duration: JsonField = JsonMissing.of(), + @JsonProperty("execution_id") + @ExcludeMissing + executionId: JsonField = JsonMissing.of(), + @JsonProperty("execution_type") + @ExcludeMissing + executionType: JsonField = JsonMissing.of(), + @JsonProperty("finished_at") + @ExcludeMissing + finishedAt: JsonField = JsonMissing.of(), + @JsonProperty("output") @ExcludeMissing output: JsonField = JsonMissing.of(), + @JsonProperty("run_at") @ExcludeMissing runAt: JsonField = JsonMissing.of(), + @JsonProperty("status") @ExcludeMissing status: JsonField = JsonMissing.of(), + @JsonProperty("success") @ExcludeMissing success: JsonField = JsonMissing.of(), + ) : this( + id, + duration, + executionId, + executionType, + finishedAt, + output, + runAt, + status, + success, + mutableMapOf(), + ) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws ArcadeInvalidDataException 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 ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun executionId(): Optional = executionId.getOptional("execution_id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun executionType(): Optional = executionType.getOptional("execution_type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun finishedAt(): Optional = finishedAt.getOptional("finished_at") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun output(): Optional = output.getOptional("output") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun runAt(): Optional = runAt.getOptional("run_at") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun status(): Optional = status.getOptional("status") + + /** + * Whether the request was successful. For immediately-executed requests, this will be true if + * the tool call succeeded. For scheduled requests, this will be true if the request was + * scheduled successfully. + * + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun success(): Optional = success.getOptional("success") + + /** + * 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 [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 [executionId]. + * + * Unlike [executionId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("execution_id") + @ExcludeMissing + fun _executionId(): JsonField = executionId + + /** + * Returns the raw JSON value of [executionType]. + * + * Unlike [executionType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("execution_type") + @ExcludeMissing + fun _executionType(): JsonField = executionType + + /** + * Returns the raw JSON value of [finishedAt]. + * + * Unlike [finishedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("finished_at") @ExcludeMissing fun _finishedAt(): JsonField = finishedAt + + /** + * 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 + + /** + * Returns the raw JSON value of [runAt]. + * + * Unlike [runAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("run_at") @ExcludeMissing fun _runAt(): JsonField = runAt + + /** + * 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 [success]. + * + * Unlike [success], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("success") @ExcludeMissing fun _success(): JsonField = success + + @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 [ExecuteToolResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ExecuteToolResponse]. */ + class Builder internal constructor() { + + private var id: JsonField = JsonMissing.of() + private var duration: JsonField = JsonMissing.of() + private var executionId: JsonField = JsonMissing.of() + private var executionType: JsonField = JsonMissing.of() + private var finishedAt: JsonField = JsonMissing.of() + private var output: JsonField = JsonMissing.of() + private var runAt: JsonField = JsonMissing.of() + private var status: JsonField = JsonMissing.of() + private var success: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(executeToolResponse: ExecuteToolResponse) = apply { + id = executeToolResponse.id + duration = executeToolResponse.duration + executionId = executeToolResponse.executionId + executionType = executeToolResponse.executionType + finishedAt = executeToolResponse.finishedAt + output = executeToolResponse.output + runAt = executeToolResponse.runAt + status = executeToolResponse.status + success = executeToolResponse.success + additionalProperties = executeToolResponse.additionalProperties.toMutableMap() + } + + 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 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 } + + fun executionId(executionId: String) = executionId(JsonField.of(executionId)) + + /** + * Sets [Builder.executionId] to an arbitrary JSON value. + * + * You should usually call [Builder.executionId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun executionId(executionId: JsonField) = apply { this.executionId = executionId } + + fun executionType(executionType: String) = executionType(JsonField.of(executionType)) + + /** + * Sets [Builder.executionType] to an arbitrary JSON value. + * + * You should usually call [Builder.executionType] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun executionType(executionType: JsonField) = apply { + this.executionType = executionType + } + + fun finishedAt(finishedAt: String) = finishedAt(JsonField.of(finishedAt)) + + /** + * Sets [Builder.finishedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.finishedAt] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun finishedAt(finishedAt: JsonField) = apply { this.finishedAt = finishedAt } + + 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 runAt(runAt: String) = runAt(JsonField.of(runAt)) + + /** + * Sets [Builder.runAt] to an arbitrary JSON value. + * + * You should usually call [Builder.runAt] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun runAt(runAt: JsonField) = apply { this.runAt = runAt } + + fun status(status: String) = status(JsonField.of(status)) + + /** + * Sets [Builder.status] to an arbitrary JSON value. + * + * You should usually call [Builder.status] with a well-typed [String] 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 } + + /** + * Whether the request was successful. For immediately-executed requests, this will be true + * if the tool call succeeded. For scheduled requests, this will be true if the request was + * scheduled successfully. + */ + fun success(success: Boolean) = success(JsonField.of(success)) + + /** + * Sets [Builder.success] to an arbitrary JSON value. + * + * You should usually call [Builder.success] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun success(success: JsonField) = apply { this.success = success } + + 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 [ExecuteToolResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ExecuteToolResponse = + ExecuteToolResponse( + id, + duration, + executionId, + executionType, + finishedAt, + output, + runAt, + status, + success, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ExecuteToolResponse = apply { + if (validated) { + return@apply + } + + id() + duration() + executionId() + executionType() + finishedAt() + output().ifPresent { it.validate() } + runAt() + status() + success() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (duration.asKnown().isPresent) 1 else 0) + + (if (executionId.asKnown().isPresent) 1 else 0) + + (if (executionType.asKnown().isPresent) 1 else 0) + + (if (finishedAt.asKnown().isPresent) 1 else 0) + + (output.asKnown().getOrNull()?.validity() ?: 0) + + (if (runAt.asKnown().isPresent) 1 else 0) + + (if (status.asKnown().isPresent) 1 else 0) + + (if (success.asKnown().isPresent) 1 else 0) + + class Output + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val authorization: JsonField, + private val error: JsonField, + private val logs: JsonField>, + private val value: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("authorization") + @ExcludeMissing + authorization: JsonField = JsonMissing.of(), + @JsonProperty("error") @ExcludeMissing error: JsonField = JsonMissing.of(), + @JsonProperty("logs") @ExcludeMissing logs: JsonField> = JsonMissing.of(), + @JsonProperty("value") @ExcludeMissing value: JsonValue = JsonMissing.of(), + ) : this(authorization, error, logs, value, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun authorization(): Optional = + authorization.getOptional("authorization") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun error(): Optional = error.getOptional("error") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun logs(): Optional> = logs.getOptional("logs") + + /** + * This arbitrary value can be deserialized into a custom type using the `convert` method: + * ```java + * MyClass myObject = output.value().convert(MyClass.class); + * ``` + */ + @JsonProperty("value") @ExcludeMissing fun _value(): JsonValue = value + + // ------------------------------------------------------------------------- + // Start of manually added code + // ------------------------------------------------------------------------- + + /** + * Returns an [Optional] containing the output value as a `Map`, or an + * empty [Optional] if the value is not a JSON object. + * + * Example usage: + * ```java + * Map result = response.output() + * .flatMap(Output::valueAsObject) + * .orElse(Map.of()); + * ``` + */ + fun valueAsObject(): Optional> = + when (value) { + is JsonObject -> Optional.of(value.values) + else -> Optional.empty() + } + + /** + * Returns the output value as a `Map`, or an empty map if the value is + * not a JSON object. + * + * Example usage: + * ```java + * Map result = output.valueAsObjectOrEmpty(); + * ``` + */ + fun valueAsObjectOrEmpty(): Map = + when (value) { + is JsonObject -> value.values + else -> emptyMap() + } + + /** + * Returns an [Optional] containing the output value as a `List`, or an empty + * [Optional] if the value is not a JSON array. + * + * Example usage: + * ```java + * List items = response.output() + * .flatMap(Output::valueAsArray) + * .orElse(List.of()); + * ``` + */ + fun valueAsArray(): Optional> = + when (value) { + is JsonArray -> Optional.of(value.values) + else -> Optional.empty() + } + + /** + * Returns the output value as a `List`, or an empty list if the value is not a + * JSON array. + * + * Example usage: + * ```java + * List items = output.valueAsArrayOrEmpty(); + * ``` + */ + fun valueAsArrayOrEmpty(): List = + when (value) { + is JsonArray -> value.values + else -> emptyList() + } + + // ------------------------------------------------------------------------- + // End of manually added code + // ------------------------------------------------------------------------- + + /** + * Returns the raw JSON value of [authorization]. + * + * Unlike [authorization], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("authorization") + @ExcludeMissing + fun _authorization(): JsonField = authorization + + /** + * 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 [logs]. + * + * Unlike [logs], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("logs") @ExcludeMissing fun _logs(): JsonField> = logs + + @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]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Output]. */ + class Builder internal constructor() { + + private var authorization: JsonField = JsonMissing.of() + private var error: JsonField = JsonMissing.of() + private var logs: JsonField>? = null + private var value: JsonValue = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(output: Output) = apply { + authorization = output.authorization + error = output.error + logs = output.logs.map { it.toMutableList() } + value = output.value + additionalProperties = output.additionalProperties.toMutableMap() + } + + fun authorization(authorization: AuthorizationResponse) = + authorization(JsonField.of(authorization)) + + /** + * Sets [Builder.authorization] to an arbitrary JSON value. + * + * You should usually call [Builder.authorization] with a well-typed + * [AuthorizationResponse] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun authorization(authorization: JsonField) = apply { + this.authorization = authorization + } + + 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 logs(logs: List) = logs(JsonField.of(logs)) + + /** + * Sets [Builder.logs] to an arbitrary JSON value. + * + * You should usually call [Builder.logs] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun logs(logs: JsonField>) = apply { + this.logs = logs.map { it.toMutableList() } + } + + /** + * Adds a single [Log] to [logs]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addLog(log: Log) = apply { + logs = + (logs ?: JsonField.of(mutableListOf())).also { checkKnown("logs", it).add(log) } + } + + fun value(value: JsonValue) = 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 [Output]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Output = + Output( + authorization, + error, + (logs ?: JsonMissing.of()).map { it.toImmutable() }, + value, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Output = apply { + if (validated) { + return@apply + } + + authorization().ifPresent { it.validate() } + error().ifPresent { it.validate() } + logs().ifPresent { it.forEach { it.validate() } } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (authorization.asKnown().getOrNull()?.validity() ?: 0) + + (error.asKnown().getOrNull()?.validity() ?: 0) + + (logs.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + class Error + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val canRetry: JsonField, + private val kind: JsonField, + private val message: JsonField, + private val additionalPromptContent: JsonField, + private val developerMessage: JsonField, + private val extra: JsonField, + private val retryAfterMs: JsonField, + private val stacktrace: JsonField, + private val statusCode: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("can_retry") + @ExcludeMissing + canRetry: JsonField = JsonMissing.of(), + @JsonProperty("kind") @ExcludeMissing kind: JsonField = JsonMissing.of(), + @JsonProperty("message") + @ExcludeMissing + message: JsonField = JsonMissing.of(), + @JsonProperty("additional_prompt_content") + @ExcludeMissing + additionalPromptContent: JsonField = JsonMissing.of(), + @JsonProperty("developer_message") + @ExcludeMissing + developerMessage: JsonField = JsonMissing.of(), + @JsonProperty("extra") @ExcludeMissing extra: JsonField = JsonMissing.of(), + @JsonProperty("retry_after_ms") + @ExcludeMissing + retryAfterMs: JsonField = JsonMissing.of(), + @JsonProperty("stacktrace") + @ExcludeMissing + stacktrace: JsonField = JsonMissing.of(), + @JsonProperty("status_code") + @ExcludeMissing + statusCode: JsonField = JsonMissing.of(), + ) : this( + canRetry, + kind, + message, + additionalPromptContent, + developerMessage, + extra, + retryAfterMs, + stacktrace, + statusCode, + mutableMapOf(), + ) + + /** + * @throws ArcadeInvalidDataException 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 canRetry(): Boolean = canRetry.getRequired("can_retry") + + /** + * @throws ArcadeInvalidDataException 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 kind(): Kind = kind.getRequired("kind") + + /** + * @throws ArcadeInvalidDataException 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 message(): String = message.getRequired("message") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun additionalPromptContent(): Optional = + additionalPromptContent.getOptional("additional_prompt_content") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun developerMessage(): Optional = + developerMessage.getOptional("developer_message") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun extra(): Optional = extra.getOptional("extra") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun retryAfterMs(): Optional = retryAfterMs.getOptional("retry_after_ms") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun stacktrace(): Optional = stacktrace.getOptional("stacktrace") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun statusCode(): Optional = statusCode.getOptional("status_code") + + /** + * Returns the raw JSON value of [canRetry]. + * + * Unlike [canRetry], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("can_retry") + @ExcludeMissing + fun _canRetry(): JsonField = canRetry + + /** + * Returns the raw JSON value of [kind]. + * + * Unlike [kind], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("kind") @ExcludeMissing fun _kind(): JsonField = kind + + /** + * Returns the raw JSON value of [message]. + * + * Unlike [message], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("message") @ExcludeMissing fun _message(): JsonField = message + + /** + * Returns the raw JSON value of [additionalPromptContent]. + * + * Unlike [additionalPromptContent], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("additional_prompt_content") + @ExcludeMissing + fun _additionalPromptContent(): JsonField = additionalPromptContent + + /** + * Returns the raw JSON value of [developerMessage]. + * + * Unlike [developerMessage], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("developer_message") + @ExcludeMissing + fun _developerMessage(): JsonField = developerMessage + + /** + * Returns the raw JSON value of [extra]. + * + * Unlike [extra], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("extra") @ExcludeMissing fun _extra(): JsonField = extra + + /** + * Returns the raw JSON value of [retryAfterMs]. + * + * Unlike [retryAfterMs], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("retry_after_ms") + @ExcludeMissing + fun _retryAfterMs(): JsonField = retryAfterMs + + /** + * Returns the raw JSON value of [stacktrace]. + * + * Unlike [stacktrace], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("stacktrace") + @ExcludeMissing + fun _stacktrace(): JsonField = stacktrace + + /** + * Returns the raw JSON value of [statusCode]. + * + * Unlike [statusCode], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("status_code") + @ExcludeMissing + fun _statusCode(): JsonField = statusCode + + @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 + * .canRetry() + * .kind() + * .message() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Error]. */ + class Builder internal constructor() { + + private var canRetry: JsonField? = null + private var kind: JsonField? = null + private var message: JsonField? = null + private var additionalPromptContent: JsonField = JsonMissing.of() + private var developerMessage: JsonField = JsonMissing.of() + private var extra: JsonField = JsonMissing.of() + private var retryAfterMs: JsonField = JsonMissing.of() + private var stacktrace: JsonField = JsonMissing.of() + private var statusCode: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(error: Error) = apply { + canRetry = error.canRetry + kind = error.kind + message = error.message + additionalPromptContent = error.additionalPromptContent + developerMessage = error.developerMessage + extra = error.extra + retryAfterMs = error.retryAfterMs + stacktrace = error.stacktrace + statusCode = error.statusCode + additionalProperties = error.additionalProperties.toMutableMap() + } + + fun canRetry(canRetry: Boolean) = canRetry(JsonField.of(canRetry)) + + /** + * Sets [Builder.canRetry] to an arbitrary JSON value. + * + * You should usually call [Builder.canRetry] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun canRetry(canRetry: JsonField) = apply { this.canRetry = canRetry } + + fun kind(kind: Kind) = kind(JsonField.of(kind)) + + /** + * Sets [Builder.kind] to an arbitrary JSON value. + * + * You should usually call [Builder.kind] with a well-typed [Kind] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun kind(kind: JsonField) = apply { this.kind = kind } + + fun message(message: String) = message(JsonField.of(message)) + + /** + * Sets [Builder.message] to an arbitrary JSON value. + * + * You should usually call [Builder.message] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun message(message: JsonField) = apply { this.message = message } + + fun additionalPromptContent(additionalPromptContent: String) = + additionalPromptContent(JsonField.of(additionalPromptContent)) + + /** + * Sets [Builder.additionalPromptContent] to an arbitrary JSON value. + * + * You should usually call [Builder.additionalPromptContent] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun additionalPromptContent(additionalPromptContent: JsonField) = apply { + this.additionalPromptContent = additionalPromptContent + } + + fun developerMessage(developerMessage: String) = + developerMessage(JsonField.of(developerMessage)) + + /** + * Sets [Builder.developerMessage] to an arbitrary JSON value. + * + * You should usually call [Builder.developerMessage] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun developerMessage(developerMessage: JsonField) = apply { + this.developerMessage = developerMessage + } + + fun extra(extra: Extra) = extra(JsonField.of(extra)) + + /** + * Sets [Builder.extra] to an arbitrary JSON value. + * + * You should usually call [Builder.extra] with a well-typed [Extra] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun extra(extra: JsonField) = apply { this.extra = extra } + + fun retryAfterMs(retryAfterMs: Long) = retryAfterMs(JsonField.of(retryAfterMs)) + + /** + * Sets [Builder.retryAfterMs] to an arbitrary JSON value. + * + * You should usually call [Builder.retryAfterMs] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun retryAfterMs(retryAfterMs: JsonField) = apply { + this.retryAfterMs = retryAfterMs + } + + fun stacktrace(stacktrace: String) = stacktrace(JsonField.of(stacktrace)) + + /** + * Sets [Builder.stacktrace] to an arbitrary JSON value. + * + * You should usually call [Builder.stacktrace] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun stacktrace(stacktrace: JsonField) = apply { + this.stacktrace = stacktrace + } + + fun statusCode(statusCode: Long) = statusCode(JsonField.of(statusCode)) + + /** + * Sets [Builder.statusCode] to an arbitrary JSON value. + * + * You should usually call [Builder.statusCode] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun statusCode(statusCode: JsonField) = apply { this.statusCode = statusCode } + + 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 + * .canRetry() + * .kind() + * .message() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Error = + Error( + checkRequired("canRetry", canRetry), + checkRequired("kind", kind), + checkRequired("message", message), + additionalPromptContent, + developerMessage, + extra, + retryAfterMs, + stacktrace, + statusCode, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Error = apply { + if (validated) { + return@apply + } + + canRetry() + kind().validate() + message() + additionalPromptContent() + developerMessage() + extra().ifPresent { it.validate() } + retryAfterMs() + stacktrace() + statusCode() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (canRetry.asKnown().isPresent) 1 else 0) + + (kind.asKnown().getOrNull()?.validity() ?: 0) + + (if (message.asKnown().isPresent) 1 else 0) + + (if (additionalPromptContent.asKnown().isPresent) 1 else 0) + + (if (developerMessage.asKnown().isPresent) 1 else 0) + + (extra.asKnown().getOrNull()?.validity() ?: 0) + + (if (retryAfterMs.asKnown().isPresent) 1 else 0) + + (if (stacktrace.asKnown().isPresent) 1 else 0) + + (if (statusCode.asKnown().isPresent) 1 else 0) + + class Kind @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 TOOLKIT_LOAD_FAILED = of("TOOLKIT_LOAD_FAILED") + + @JvmField + val TOOL_DEFINITION_BAD_DEFINITION = of("TOOL_DEFINITION_BAD_DEFINITION") + + @JvmField + val TOOL_DEFINITION_BAD_INPUT_SCHEMA = of("TOOL_DEFINITION_BAD_INPUT_SCHEMA") + + @JvmField + val TOOL_DEFINITION_BAD_OUTPUT_SCHEMA = of("TOOL_DEFINITION_BAD_OUTPUT_SCHEMA") + + @JvmField val TOOL_REQUIREMENTS_NOT_MET = of("TOOL_REQUIREMENTS_NOT_MET") + + @JvmField val TOOL_RUNTIME_BAD_INPUT_VALUE = of("TOOL_RUNTIME_BAD_INPUT_VALUE") + + @JvmField + val TOOL_RUNTIME_BAD_OUTPUT_VALUE = of("TOOL_RUNTIME_BAD_OUTPUT_VALUE") + + @JvmField val TOOL_RUNTIME_RETRY = of("TOOL_RUNTIME_RETRY") + + @JvmField + val TOOL_RUNTIME_CONTEXT_REQUIRED = of("TOOL_RUNTIME_CONTEXT_REQUIRED") + + @JvmField val TOOL_RUNTIME_FATAL = of("TOOL_RUNTIME_FATAL") + + @JvmField val CONTEXT_CHECK_FAILED = of("CONTEXT_CHECK_FAILED") + + @JvmField val CONTEXT_DENIED = of("CONTEXT_DENIED") + + @JvmField val UPSTREAM_RUNTIME_BAD_REQUEST = of("UPSTREAM_RUNTIME_BAD_REQUEST") + + @JvmField val UPSTREAM_RUNTIME_AUTH_ERROR = of("UPSTREAM_RUNTIME_AUTH_ERROR") + + @JvmField val UPSTREAM_RUNTIME_NOT_FOUND = of("UPSTREAM_RUNTIME_NOT_FOUND") + + @JvmField + val UPSTREAM_RUNTIME_VALIDATION_ERROR = of("UPSTREAM_RUNTIME_VALIDATION_ERROR") + + @JvmField val UPSTREAM_RUNTIME_RATE_LIMIT = of("UPSTREAM_RUNTIME_RATE_LIMIT") + + @JvmField + val UPSTREAM_RUNTIME_SERVER_ERROR = of("UPSTREAM_RUNTIME_SERVER_ERROR") + + @JvmField val UPSTREAM_RUNTIME_UNMAPPED = of("UPSTREAM_RUNTIME_UNMAPPED") + + @JvmField val UNKNOWN = of("UNKNOWN") + + @JvmStatic fun of(value: String) = Kind(JsonField.of(value)) + } + + /** An enum containing [Kind]'s known values. */ + enum class Known { + TOOLKIT_LOAD_FAILED, + TOOL_DEFINITION_BAD_DEFINITION, + TOOL_DEFINITION_BAD_INPUT_SCHEMA, + TOOL_DEFINITION_BAD_OUTPUT_SCHEMA, + TOOL_REQUIREMENTS_NOT_MET, + TOOL_RUNTIME_BAD_INPUT_VALUE, + TOOL_RUNTIME_BAD_OUTPUT_VALUE, + TOOL_RUNTIME_RETRY, + TOOL_RUNTIME_CONTEXT_REQUIRED, + TOOL_RUNTIME_FATAL, + CONTEXT_CHECK_FAILED, + CONTEXT_DENIED, + UPSTREAM_RUNTIME_BAD_REQUEST, + UPSTREAM_RUNTIME_AUTH_ERROR, + UPSTREAM_RUNTIME_NOT_FOUND, + UPSTREAM_RUNTIME_VALIDATION_ERROR, + UPSTREAM_RUNTIME_RATE_LIMIT, + UPSTREAM_RUNTIME_SERVER_ERROR, + UPSTREAM_RUNTIME_UNMAPPED, + UNKNOWN, + } + + /** + * An enum containing [Kind]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Kind] 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 { + TOOLKIT_LOAD_FAILED, + TOOL_DEFINITION_BAD_DEFINITION, + TOOL_DEFINITION_BAD_INPUT_SCHEMA, + TOOL_DEFINITION_BAD_OUTPUT_SCHEMA, + TOOL_REQUIREMENTS_NOT_MET, + TOOL_RUNTIME_BAD_INPUT_VALUE, + TOOL_RUNTIME_BAD_OUTPUT_VALUE, + TOOL_RUNTIME_RETRY, + TOOL_RUNTIME_CONTEXT_REQUIRED, + TOOL_RUNTIME_FATAL, + CONTEXT_CHECK_FAILED, + CONTEXT_DENIED, + UPSTREAM_RUNTIME_BAD_REQUEST, + UPSTREAM_RUNTIME_AUTH_ERROR, + UPSTREAM_RUNTIME_NOT_FOUND, + UPSTREAM_RUNTIME_VALIDATION_ERROR, + UPSTREAM_RUNTIME_RATE_LIMIT, + UPSTREAM_RUNTIME_SERVER_ERROR, + UPSTREAM_RUNTIME_UNMAPPED, + UNKNOWN, + /** + * An enum member indicating that [Kind] 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) { + TOOLKIT_LOAD_FAILED -> Value.TOOLKIT_LOAD_FAILED + TOOL_DEFINITION_BAD_DEFINITION -> Value.TOOL_DEFINITION_BAD_DEFINITION + TOOL_DEFINITION_BAD_INPUT_SCHEMA -> Value.TOOL_DEFINITION_BAD_INPUT_SCHEMA + TOOL_DEFINITION_BAD_OUTPUT_SCHEMA -> Value.TOOL_DEFINITION_BAD_OUTPUT_SCHEMA + TOOL_REQUIREMENTS_NOT_MET -> Value.TOOL_REQUIREMENTS_NOT_MET + TOOL_RUNTIME_BAD_INPUT_VALUE -> Value.TOOL_RUNTIME_BAD_INPUT_VALUE + TOOL_RUNTIME_BAD_OUTPUT_VALUE -> Value.TOOL_RUNTIME_BAD_OUTPUT_VALUE + TOOL_RUNTIME_RETRY -> Value.TOOL_RUNTIME_RETRY + TOOL_RUNTIME_CONTEXT_REQUIRED -> Value.TOOL_RUNTIME_CONTEXT_REQUIRED + TOOL_RUNTIME_FATAL -> Value.TOOL_RUNTIME_FATAL + CONTEXT_CHECK_FAILED -> Value.CONTEXT_CHECK_FAILED + CONTEXT_DENIED -> Value.CONTEXT_DENIED + UPSTREAM_RUNTIME_BAD_REQUEST -> Value.UPSTREAM_RUNTIME_BAD_REQUEST + UPSTREAM_RUNTIME_AUTH_ERROR -> Value.UPSTREAM_RUNTIME_AUTH_ERROR + UPSTREAM_RUNTIME_NOT_FOUND -> Value.UPSTREAM_RUNTIME_NOT_FOUND + UPSTREAM_RUNTIME_VALIDATION_ERROR -> Value.UPSTREAM_RUNTIME_VALIDATION_ERROR + UPSTREAM_RUNTIME_RATE_LIMIT -> Value.UPSTREAM_RUNTIME_RATE_LIMIT + UPSTREAM_RUNTIME_SERVER_ERROR -> Value.UPSTREAM_RUNTIME_SERVER_ERROR + UPSTREAM_RUNTIME_UNMAPPED -> Value.UPSTREAM_RUNTIME_UNMAPPED + UNKNOWN -> Value.UNKNOWN + 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 ArcadeInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + TOOLKIT_LOAD_FAILED -> Known.TOOLKIT_LOAD_FAILED + TOOL_DEFINITION_BAD_DEFINITION -> Known.TOOL_DEFINITION_BAD_DEFINITION + TOOL_DEFINITION_BAD_INPUT_SCHEMA -> Known.TOOL_DEFINITION_BAD_INPUT_SCHEMA + TOOL_DEFINITION_BAD_OUTPUT_SCHEMA -> Known.TOOL_DEFINITION_BAD_OUTPUT_SCHEMA + TOOL_REQUIREMENTS_NOT_MET -> Known.TOOL_REQUIREMENTS_NOT_MET + TOOL_RUNTIME_BAD_INPUT_VALUE -> Known.TOOL_RUNTIME_BAD_INPUT_VALUE + TOOL_RUNTIME_BAD_OUTPUT_VALUE -> Known.TOOL_RUNTIME_BAD_OUTPUT_VALUE + TOOL_RUNTIME_RETRY -> Known.TOOL_RUNTIME_RETRY + TOOL_RUNTIME_CONTEXT_REQUIRED -> Known.TOOL_RUNTIME_CONTEXT_REQUIRED + TOOL_RUNTIME_FATAL -> Known.TOOL_RUNTIME_FATAL + CONTEXT_CHECK_FAILED -> Known.CONTEXT_CHECK_FAILED + CONTEXT_DENIED -> Known.CONTEXT_DENIED + UPSTREAM_RUNTIME_BAD_REQUEST -> Known.UPSTREAM_RUNTIME_BAD_REQUEST + UPSTREAM_RUNTIME_AUTH_ERROR -> Known.UPSTREAM_RUNTIME_AUTH_ERROR + UPSTREAM_RUNTIME_NOT_FOUND -> Known.UPSTREAM_RUNTIME_NOT_FOUND + UPSTREAM_RUNTIME_VALIDATION_ERROR -> Known.UPSTREAM_RUNTIME_VALIDATION_ERROR + UPSTREAM_RUNTIME_RATE_LIMIT -> Known.UPSTREAM_RUNTIME_RATE_LIMIT + UPSTREAM_RUNTIME_SERVER_ERROR -> Known.UPSTREAM_RUNTIME_SERVER_ERROR + UPSTREAM_RUNTIME_UNMAPPED -> Known.UPSTREAM_RUNTIME_UNMAPPED + UNKNOWN -> Known.UNKNOWN + else -> throw ArcadeInvalidDataException("Unknown Kind: $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 ArcadeInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ArcadeInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Kind = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 Kind && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class Extra + @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 [Extra]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Extra]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(extra: Extra) = apply { + additionalProperties = extra.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 [Extra]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Extra = Extra(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Extra = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 Extra && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Extra{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Error && + canRetry == other.canRetry && + kind == other.kind && + message == other.message && + additionalPromptContent == other.additionalPromptContent && + developerMessage == other.developerMessage && + extra == other.extra && + retryAfterMs == other.retryAfterMs && + stacktrace == other.stacktrace && + statusCode == other.statusCode && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + canRetry, + kind, + message, + additionalPromptContent, + developerMessage, + extra, + retryAfterMs, + stacktrace, + statusCode, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Error{canRetry=$canRetry, kind=$kind, message=$message, additionalPromptContent=$additionalPromptContent, developerMessage=$developerMessage, extra=$extra, retryAfterMs=$retryAfterMs, stacktrace=$stacktrace, statusCode=$statusCode, additionalProperties=$additionalProperties}" + } + + class Log + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val level: JsonField, + private val message: JsonField, + private val subtype: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("level") @ExcludeMissing level: JsonField = JsonMissing.of(), + @JsonProperty("message") + @ExcludeMissing + message: JsonField = JsonMissing.of(), + @JsonProperty("subtype") + @ExcludeMissing + subtype: JsonField = JsonMissing.of(), + ) : this(level, message, subtype, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException 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 level(): String = level.getRequired("level") + + /** + * @throws ArcadeInvalidDataException 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 message(): String = message.getRequired("message") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun subtype(): Optional = subtype.getOptional("subtype") + + /** + * Returns the raw JSON value of [level]. + * + * Unlike [level], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("level") @ExcludeMissing fun _level(): JsonField = level + + /** + * Returns the raw JSON value of [message]. + * + * Unlike [message], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("message") @ExcludeMissing fun _message(): JsonField = message + + /** + * Returns the raw JSON value of [subtype]. + * + * Unlike [subtype], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("subtype") @ExcludeMissing fun _subtype(): JsonField = subtype + + @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 [Log]. + * + * The following fields are required: + * ```java + * .level() + * .message() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Log]. */ + class Builder internal constructor() { + + private var level: JsonField? = null + private var message: JsonField? = null + private var subtype: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(log: Log) = apply { + level = log.level + message = log.message + subtype = log.subtype + additionalProperties = log.additionalProperties.toMutableMap() + } + + fun level(level: String) = level(JsonField.of(level)) + + /** + * Sets [Builder.level] to an arbitrary JSON value. + * + * You should usually call [Builder.level] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun level(level: JsonField) = apply { this.level = level } + + fun message(message: String) = message(JsonField.of(message)) + + /** + * Sets [Builder.message] to an arbitrary JSON value. + * + * You should usually call [Builder.message] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun message(message: JsonField) = apply { this.message = message } + + fun subtype(subtype: String) = subtype(JsonField.of(subtype)) + + /** + * Sets [Builder.subtype] to an arbitrary JSON value. + * + * You should usually call [Builder.subtype] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun subtype(subtype: JsonField) = apply { this.subtype = subtype } + + 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 [Log]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .level() + * .message() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Log = + Log( + checkRequired("level", level), + checkRequired("message", message), + subtype, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Log = apply { + if (validated) { + return@apply + } + + level() + message() + subtype() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (level.asKnown().isPresent) 1 else 0) + + (if (message.asKnown().isPresent) 1 else 0) + + (if (subtype.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Log && + level == other.level && + message == other.message && + subtype == other.subtype && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(level, message, subtype, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Log{level=$level, message=$message, subtype=$subtype, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Output && + authorization == other.authorization && + error == other.error && + logs == other.logs && + value == other.value && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(authorization, error, logs, value, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Output{authorization=$authorization, error=$error, logs=$logs, value=$value, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ExecuteToolResponse && + id == other.id && + duration == other.duration && + executionId == other.executionId && + executionType == other.executionType && + finishedAt == other.finishedAt && + output == other.output && + runAt == other.runAt && + status == other.status && + success == other.success && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + duration, + executionId, + executionType, + finishedAt, + output, + runAt, + status, + success, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ExecuteToolResponse{id=$id, duration=$duration, executionId=$executionId, executionType=$executionType, finishedAt=$finishedAt, output=$output, runAt=$runAt, status=$status, success=$success, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolAuthorizeParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolAuthorizeParams.kt similarity index 83% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/ToolAuthorizeParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolAuthorizeParams.kt index 30c1d20..3e42a8b 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolAuthorizeParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolAuthorizeParams.kt @@ -1,9 +1,8 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.tools import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params import dev.arcade.core.checkRequired import dev.arcade.core.http.Headers @@ -23,25 +22,28 @@ private constructor( fun _additionalBodyProperties(): Map = authorizeToolRequest._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): AuthorizeToolRequest = authorizeToolRequest - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [ToolAuthorizeParams]. + * + * The following fields are required: + * ```java + * .authorizeToolRequest() + * ``` + */ @JvmStatic fun builder() = Builder() } /** A builder for [ToolAuthorizeParams]. */ - @NoAutoDetect class Builder internal constructor() { private var authorizeToolRequest: AuthorizeToolRequest? = null @@ -157,6 +159,18 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [ToolAuthorizeParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .authorizeToolRequest() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): ToolAuthorizeParams = ToolAuthorizeParams( checkRequired("authorizeToolRequest", authorizeToolRequest), @@ -165,15 +179,25 @@ private constructor( ) } + fun _body(): AuthorizeToolRequest = authorizeToolRequest + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is ToolAuthorizeParams && authorizeToolRequest == other.authorizeToolRequest && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is ToolAuthorizeParams && + authorizeToolRequest == other.authorizeToolRequest && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(authorizeToolRequest, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(authorizeToolRequest, additionalHeaders, additionalQueryParams) override fun toString() = "ToolAuthorizeParams{authorizeToolRequest=$authorizeToolRequest, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolDefinition.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolDefinition.kt new file mode 100644 index 0000000..7be442a --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolDefinition.kt @@ -0,0 +1,3697 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.tools + +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 dev.arcade.core.Enum +import dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.core.checkKnown +import dev.arcade.core.checkRequired +import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class ToolDefinition +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val fullyQualifiedName: JsonField, + private val input: JsonField, + private val name: JsonField, + private val qualifiedName: JsonField, + private val toolkit: JsonField, + private val description: JsonField, + private val formattedSchema: JsonField, + private val metadata: JsonField, + private val output: JsonField, + private val requirements: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("fully_qualified_name") + @ExcludeMissing + fullyQualifiedName: JsonField = JsonMissing.of(), + @JsonProperty("input") @ExcludeMissing input: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("qualified_name") + @ExcludeMissing + qualifiedName: JsonField = JsonMissing.of(), + @JsonProperty("toolkit") @ExcludeMissing toolkit: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("formatted_schema") + @ExcludeMissing + formattedSchema: JsonField = JsonMissing.of(), + @JsonProperty("metadata") @ExcludeMissing metadata: JsonField = JsonMissing.of(), + @JsonProperty("output") @ExcludeMissing output: JsonField = JsonMissing.of(), + @JsonProperty("requirements") + @ExcludeMissing + requirements: JsonField = JsonMissing.of(), + ) : this( + fullyQualifiedName, + input, + name, + qualifiedName, + toolkit, + description, + formattedSchema, + metadata, + output, + requirements, + mutableMapOf(), + ) + + /** + * @throws ArcadeInvalidDataException 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 fullyQualifiedName(): String = fullyQualifiedName.getRequired("fully_qualified_name") + + /** + * @throws ArcadeInvalidDataException 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(): Input = input.getRequired("input") + + /** + * @throws ArcadeInvalidDataException 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 ArcadeInvalidDataException 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 qualifiedName(): String = qualifiedName.getRequired("qualified_name") + + /** + * @throws ArcadeInvalidDataException 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 toolkit(): Toolkit = toolkit.getRequired("toolkit") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun formattedSchema(): Optional = + formattedSchema.getOptional("formatted_schema") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun output(): Optional = output.getOptional("output") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun requirements(): Optional = requirements.getOptional("requirements") + + /** + * Returns the raw JSON value of [fullyQualifiedName]. + * + * Unlike [fullyQualifiedName], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("fully_qualified_name") + @ExcludeMissing + fun _fullyQualifiedName(): JsonField = fullyQualifiedName + + /** + * 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 [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 [qualifiedName]. + * + * Unlike [qualifiedName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("qualified_name") + @ExcludeMissing + fun _qualifiedName(): JsonField = qualifiedName + + /** + * Returns the raw JSON value of [toolkit]. + * + * Unlike [toolkit], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("toolkit") @ExcludeMissing fun _toolkit(): JsonField = toolkit + + /** + * 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 [formattedSchema]. + * + * Unlike [formattedSchema], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("formatted_schema") + @ExcludeMissing + fun _formattedSchema(): JsonField = formattedSchema + + /** + * 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 [output]. + * + * Unlike [output], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("output") @ExcludeMissing fun _output(): JsonField = output + + /** + * Returns the raw JSON value of [requirements]. + * + * Unlike [requirements], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("requirements") + @ExcludeMissing + fun _requirements(): JsonField = requirements + + @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 [ToolDefinition]. + * + * The following fields are required: + * ```java + * .fullyQualifiedName() + * .input() + * .name() + * .qualifiedName() + * .toolkit() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ToolDefinition]. */ + class Builder internal constructor() { + + private var fullyQualifiedName: JsonField? = null + private var input: JsonField? = null + private var name: JsonField? = null + private var qualifiedName: JsonField? = null + private var toolkit: JsonField? = null + private var description: JsonField = JsonMissing.of() + private var formattedSchema: JsonField = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var output: JsonField = JsonMissing.of() + private var requirements: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(toolDefinition: ToolDefinition) = apply { + fullyQualifiedName = toolDefinition.fullyQualifiedName + input = toolDefinition.input + name = toolDefinition.name + qualifiedName = toolDefinition.qualifiedName + toolkit = toolDefinition.toolkit + description = toolDefinition.description + formattedSchema = toolDefinition.formattedSchema + metadata = toolDefinition.metadata + output = toolDefinition.output + requirements = toolDefinition.requirements + additionalProperties = toolDefinition.additionalProperties.toMutableMap() + } + + fun fullyQualifiedName(fullyQualifiedName: String) = + fullyQualifiedName(JsonField.of(fullyQualifiedName)) + + /** + * Sets [Builder.fullyQualifiedName] to an arbitrary JSON value. + * + * You should usually call [Builder.fullyQualifiedName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun fullyQualifiedName(fullyQualifiedName: JsonField) = apply { + this.fullyQualifiedName = fullyQualifiedName + } + + fun input(input: Input) = input(JsonField.of(input)) + + /** + * Sets [Builder.input] to an arbitrary JSON value. + * + * You should usually call [Builder.input] with a well-typed [Input] 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 } + + 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 qualifiedName(qualifiedName: String) = qualifiedName(JsonField.of(qualifiedName)) + + /** + * Sets [Builder.qualifiedName] to an arbitrary JSON value. + * + * You should usually call [Builder.qualifiedName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun qualifiedName(qualifiedName: JsonField) = apply { + this.qualifiedName = qualifiedName + } + + fun toolkit(toolkit: Toolkit) = toolkit(JsonField.of(toolkit)) + + /** + * Sets [Builder.toolkit] to an arbitrary JSON value. + * + * You should usually call [Builder.toolkit] with a well-typed [Toolkit] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun toolkit(toolkit: JsonField) = apply { this.toolkit = toolkit } + + 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 } + + fun formattedSchema(formattedSchema: FormattedSchema) = + formattedSchema(JsonField.of(formattedSchema)) + + /** + * Sets [Builder.formattedSchema] to an arbitrary JSON value. + * + * You should usually call [Builder.formattedSchema] with a well-typed [FormattedSchema] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun formattedSchema(formattedSchema: JsonField) = apply { + this.formattedSchema = formattedSchema + } + + 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 } + + 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 requirements(requirements: Requirements) = requirements(JsonField.of(requirements)) + + /** + * Sets [Builder.requirements] to an arbitrary JSON value. + * + * You should usually call [Builder.requirements] with a well-typed [Requirements] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun requirements(requirements: JsonField) = apply { + this.requirements = requirements + } + + 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 [ToolDefinition]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .fullyQualifiedName() + * .input() + * .name() + * .qualifiedName() + * .toolkit() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ToolDefinition = + ToolDefinition( + checkRequired("fullyQualifiedName", fullyQualifiedName), + checkRequired("input", input), + checkRequired("name", name), + checkRequired("qualifiedName", qualifiedName), + checkRequired("toolkit", toolkit), + description, + formattedSchema, + metadata, + output, + requirements, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ToolDefinition = apply { + if (validated) { + return@apply + } + + fullyQualifiedName() + input().validate() + name() + qualifiedName() + toolkit().validate() + description() + formattedSchema().ifPresent { it.validate() } + metadata().ifPresent { it.validate() } + output().ifPresent { it.validate() } + requirements().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (fullyQualifiedName.asKnown().isPresent) 1 else 0) + + (input.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (qualifiedName.asKnown().isPresent) 1 else 0) + + (toolkit.asKnown().getOrNull()?.validity() ?: 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (formattedSchema.asKnown().getOrNull()?.validity() ?: 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (output.asKnown().getOrNull()?.validity() ?: 0) + + (requirements.asKnown().getOrNull()?.validity() ?: 0) + + class Input + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val parameters: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("parameters") + @ExcludeMissing + parameters: JsonField> = JsonMissing.of() + ) : this(parameters, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun parameters(): Optional> = parameters.getOptional("parameters") + + /** + * Returns the raw JSON value of [parameters]. + * + * Unlike [parameters], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("parameters") + @ExcludeMissing + fun _parameters(): JsonField> = parameters + + @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 [Input]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Input]. */ + class Builder internal constructor() { + + private var parameters: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(input: Input) = apply { + parameters = input.parameters.map { it.toMutableList() } + additionalProperties = input.additionalProperties.toMutableMap() + } + + fun parameters(parameters: List) = parameters(JsonField.of(parameters)) + + /** + * Sets [Builder.parameters] to an arbitrary JSON value. + * + * You should usually call [Builder.parameters] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun parameters(parameters: JsonField>) = apply { + this.parameters = parameters.map { it.toMutableList() } + } + + /** + * Adds a single [Parameter] to [parameters]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addParameter(parameter: Parameter) = apply { + parameters = + (parameters ?: JsonField.of(mutableListOf())).also { + checkKnown("parameters", it).add(parameter) + } + } + + 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 [Input]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Input = + Input( + (parameters ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Input = apply { + if (validated) { + return@apply + } + + parameters().ifPresent { it.forEach { it.validate() } } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (parameters.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + class Parameter + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val name: JsonField, + private val valueSchema: JsonField, + private val description: JsonField, + private val inferrable: JsonField, + private val required: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("value_schema") + @ExcludeMissing + valueSchema: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("inferrable") + @ExcludeMissing + inferrable: JsonField = JsonMissing.of(), + @JsonProperty("required") + @ExcludeMissing + required: JsonField = JsonMissing.of(), + ) : this(name, valueSchema, description, inferrable, required, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException 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 ArcadeInvalidDataException 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 valueSchema(): ValueSchema = valueSchema.getRequired("value_schema") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun inferrable(): Optional = inferrable.getOptional("inferrable") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun required(): Optional = required.getOptional("required") + + /** + * 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 [valueSchema]. + * + * Unlike [valueSchema], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("value_schema") + @ExcludeMissing + fun _valueSchema(): JsonField = valueSchema + + /** + * 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 [inferrable]. + * + * Unlike [inferrable], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("inferrable") + @ExcludeMissing + fun _inferrable(): JsonField = inferrable + + /** + * Returns the raw JSON value of [required]. + * + * Unlike [required], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("required") @ExcludeMissing fun _required(): JsonField = required + + @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 [Parameter]. + * + * The following fields are required: + * ```java + * .name() + * .valueSchema() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Parameter]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var valueSchema: JsonField? = null + private var description: JsonField = JsonMissing.of() + private var inferrable: JsonField = JsonMissing.of() + private var required: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(parameter: Parameter) = apply { + name = parameter.name + valueSchema = parameter.valueSchema + description = parameter.description + inferrable = parameter.inferrable + required = parameter.required + additionalProperties = parameter.additionalProperties.toMutableMap() + } + + 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 valueSchema(valueSchema: ValueSchema) = valueSchema(JsonField.of(valueSchema)) + + /** + * Sets [Builder.valueSchema] to an arbitrary JSON value. + * + * You should usually call [Builder.valueSchema] with a well-typed [ValueSchema] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun valueSchema(valueSchema: JsonField) = apply { + this.valueSchema = valueSchema + } + + 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 + } + + fun inferrable(inferrable: Boolean) = inferrable(JsonField.of(inferrable)) + + /** + * Sets [Builder.inferrable] to an arbitrary JSON value. + * + * You should usually call [Builder.inferrable] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun inferrable(inferrable: JsonField) = apply { + this.inferrable = inferrable + } + + fun required(required: Boolean) = required(JsonField.of(required)) + + /** + * Sets [Builder.required] to an arbitrary JSON value. + * + * You should usually call [Builder.required] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun required(required: JsonField) = apply { this.required = required } + + 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 [Parameter]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * .valueSchema() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Parameter = + Parameter( + checkRequired("name", name), + checkRequired("valueSchema", valueSchema), + description, + inferrable, + required, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Parameter = apply { + if (validated) { + return@apply + } + + name() + valueSchema().validate() + description() + inferrable() + required() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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) + + (valueSchema.asKnown().getOrNull()?.validity() ?: 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (if (inferrable.asKnown().isPresent) 1 else 0) + + (if (required.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Parameter && + name == other.name && + valueSchema == other.valueSchema && + description == other.description && + inferrable == other.inferrable && + required == other.required && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + name, + valueSchema, + description, + inferrable, + required, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Parameter{name=$name, valueSchema=$valueSchema, description=$description, inferrable=$inferrable, required=$required, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Input && + parameters == other.parameters && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(parameters, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Input{parameters=$parameters, additionalProperties=$additionalProperties}" + } + + class Toolkit + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val name: JsonField, + private val description: JsonField, + private val version: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("version") @ExcludeMissing version: JsonField = JsonMissing.of(), + ) : this(name, description, version, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException 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 ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun version(): Optional = version.getOptional("version") + + /** + * 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 [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 [version]. + * + * Unlike [version], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("version") @ExcludeMissing fun _version(): JsonField = version + + @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 [Toolkit]. + * + * The following fields are required: + * ```java + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Toolkit]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var description: JsonField = JsonMissing.of() + private var version: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(toolkit: Toolkit) = apply { + name = toolkit.name + description = toolkit.description + version = toolkit.version + additionalProperties = toolkit.additionalProperties.toMutableMap() + } + + 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 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 + } + + fun version(version: String) = version(JsonField.of(version)) + + /** + * Sets [Builder.version] to an arbitrary JSON value. + * + * You should usually call [Builder.version] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun version(version: JsonField) = apply { this.version = version } + + 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 [Toolkit]. + * + * 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(): Toolkit = + Toolkit( + checkRequired("name", name), + description, + version, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Toolkit = apply { + if (validated) { + return@apply + } + + name() + description() + version() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (description.asKnown().isPresent) 1 else 0) + + (if (version.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Toolkit && + name == other.name && + description == other.description && + version == other.version && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(name, description, version, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Toolkit{name=$name, description=$description, version=$version, additionalProperties=$additionalProperties}" + } + + class FormattedSchema + @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 [FormattedSchema]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FormattedSchema]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(formattedSchema: FormattedSchema) = apply { + additionalProperties = formattedSchema.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 [FormattedSchema]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): FormattedSchema = FormattedSchema(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): FormattedSchema = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 FormattedSchema && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "FormattedSchema{additionalProperties=$additionalProperties}" + } + + class Metadata + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val behavior: JsonField, + private val classification: JsonField, + private val extras: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("behavior") + @ExcludeMissing + behavior: JsonField = JsonMissing.of(), + @JsonProperty("classification") + @ExcludeMissing + classification: JsonField = JsonMissing.of(), + @JsonProperty("extras") @ExcludeMissing extras: JsonField = JsonMissing.of(), + ) : this(behavior, classification, extras, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun behavior(): Optional = behavior.getOptional("behavior") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun classification(): Optional = + classification.getOptional("classification") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun extras(): Optional = extras.getOptional("extras") + + /** + * Returns the raw JSON value of [behavior]. + * + * Unlike [behavior], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("behavior") @ExcludeMissing fun _behavior(): JsonField = behavior + + /** + * Returns the raw JSON value of [classification]. + * + * Unlike [classification], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("classification") + @ExcludeMissing + fun _classification(): JsonField = classification + + /** + * Returns the raw JSON value of [extras]. + * + * Unlike [extras], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("extras") @ExcludeMissing fun _extras(): JsonField = extras + + @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 behavior: JsonField = JsonMissing.of() + private var classification: JsonField = JsonMissing.of() + private var extras: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + behavior = metadata.behavior + classification = metadata.classification + extras = metadata.extras + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + fun behavior(behavior: Behavior) = behavior(JsonField.of(behavior)) + + /** + * Sets [Builder.behavior] to an arbitrary JSON value. + * + * You should usually call [Builder.behavior] with a well-typed [Behavior] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun behavior(behavior: JsonField) = apply { this.behavior = behavior } + + fun classification(classification: Classification) = + classification(JsonField.of(classification)) + + /** + * Sets [Builder.classification] to an arbitrary JSON value. + * + * You should usually call [Builder.classification] with a well-typed [Classification] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun classification(classification: JsonField) = apply { + this.classification = classification + } + + fun extras(extras: Extras) = extras(JsonField.of(extras)) + + /** + * Sets [Builder.extras] to an arbitrary JSON value. + * + * You should usually call [Builder.extras] with a well-typed [Extras] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun extras(extras: JsonField) = apply { this.extras = extras } + + 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(behavior, classification, extras, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + behavior().ifPresent { it.validate() } + classification().ifPresent { it.validate() } + extras().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (behavior.asKnown().getOrNull()?.validity() ?: 0) + + (classification.asKnown().getOrNull()?.validity() ?: 0) + + (extras.asKnown().getOrNull()?.validity() ?: 0) + + class Behavior + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val destructive: JsonField, + private val idempotent: JsonField, + private val openWorld: JsonField, + private val operations: JsonField>, + private val readOnly: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("destructive") + @ExcludeMissing + destructive: JsonField = JsonMissing.of(), + @JsonProperty("idempotent") + @ExcludeMissing + idempotent: JsonField = JsonMissing.of(), + @JsonProperty("open_world") + @ExcludeMissing + openWorld: JsonField = JsonMissing.of(), + @JsonProperty("operations") + @ExcludeMissing + operations: JsonField> = JsonMissing.of(), + @JsonProperty("read_only") + @ExcludeMissing + readOnly: JsonField = JsonMissing.of(), + ) : this(destructive, idempotent, openWorld, operations, readOnly, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun destructive(): Optional = destructive.getOptional("destructive") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun idempotent(): Optional = idempotent.getOptional("idempotent") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun openWorld(): Optional = openWorld.getOptional("open_world") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun operations(): Optional> = operations.getOptional("operations") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun readOnly(): Optional = readOnly.getOptional("read_only") + + /** + * Returns the raw JSON value of [destructive]. + * + * Unlike [destructive], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("destructive") + @ExcludeMissing + fun _destructive(): JsonField = destructive + + /** + * Returns the raw JSON value of [idempotent]. + * + * Unlike [idempotent], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("idempotent") + @ExcludeMissing + fun _idempotent(): JsonField = idempotent + + /** + * Returns the raw JSON value of [openWorld]. + * + * Unlike [openWorld], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("open_world") + @ExcludeMissing + fun _openWorld(): JsonField = openWorld + + /** + * Returns the raw JSON value of [operations]. + * + * Unlike [operations], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("operations") + @ExcludeMissing + fun _operations(): JsonField> = operations + + /** + * Returns the raw JSON value of [readOnly]. + * + * Unlike [readOnly], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("read_only") + @ExcludeMissing + fun _readOnly(): JsonField = readOnly + + @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 [Behavior]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Behavior]. */ + class Builder internal constructor() { + + private var destructive: JsonField = JsonMissing.of() + private var idempotent: JsonField = JsonMissing.of() + private var openWorld: JsonField = JsonMissing.of() + private var operations: JsonField>? = null + private var readOnly: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(behavior: Behavior) = apply { + destructive = behavior.destructive + idempotent = behavior.idempotent + openWorld = behavior.openWorld + operations = behavior.operations.map { it.toMutableList() } + readOnly = behavior.readOnly + additionalProperties = behavior.additionalProperties.toMutableMap() + } + + fun destructive(destructive: Boolean) = destructive(JsonField.of(destructive)) + + /** + * Sets [Builder.destructive] to an arbitrary JSON value. + * + * You should usually call [Builder.destructive] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun destructive(destructive: JsonField) = apply { + this.destructive = destructive + } + + fun idempotent(idempotent: Boolean) = idempotent(JsonField.of(idempotent)) + + /** + * Sets [Builder.idempotent] to an arbitrary JSON value. + * + * You should usually call [Builder.idempotent] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun idempotent(idempotent: JsonField) = apply { + this.idempotent = idempotent + } + + fun openWorld(openWorld: Boolean) = openWorld(JsonField.of(openWorld)) + + /** + * Sets [Builder.openWorld] to an arbitrary JSON value. + * + * You should usually call [Builder.openWorld] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun openWorld(openWorld: JsonField) = apply { this.openWorld = openWorld } + + fun operations(operations: List) = operations(JsonField.of(operations)) + + /** + * Sets [Builder.operations] to an arbitrary JSON value. + * + * You should usually call [Builder.operations] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun operations(operations: JsonField>) = apply { + this.operations = operations.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [operations]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addOperation(operation: String) = apply { + operations = + (operations ?: JsonField.of(mutableListOf())).also { + checkKnown("operations", it).add(operation) + } + } + + fun readOnly(readOnly: Boolean) = readOnly(JsonField.of(readOnly)) + + /** + * Sets [Builder.readOnly] to an arbitrary JSON value. + * + * You should usually call [Builder.readOnly] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun readOnly(readOnly: JsonField) = apply { this.readOnly = readOnly } + + 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 [Behavior]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Behavior = + Behavior( + destructive, + idempotent, + openWorld, + (operations ?: JsonMissing.of()).map { it.toImmutable() }, + readOnly, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Behavior = apply { + if (validated) { + return@apply + } + + destructive() + idempotent() + openWorld() + operations() + readOnly() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (destructive.asKnown().isPresent) 1 else 0) + + (if (idempotent.asKnown().isPresent) 1 else 0) + + (if (openWorld.asKnown().isPresent) 1 else 0) + + (operations.asKnown().getOrNull()?.size ?: 0) + + (if (readOnly.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Behavior && + destructive == other.destructive && + idempotent == other.idempotent && + openWorld == other.openWorld && + operations == other.operations && + readOnly == other.readOnly && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + destructive, + idempotent, + openWorld, + operations, + readOnly, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Behavior{destructive=$destructive, idempotent=$idempotent, openWorld=$openWorld, operations=$operations, readOnly=$readOnly, additionalProperties=$additionalProperties}" + } + + class Classification + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val serviceDomains: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("service_domains") + @ExcludeMissing + serviceDomains: JsonField> = JsonMissing.of() + ) : this(serviceDomains, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun serviceDomains(): Optional> = + serviceDomains.getOptional("service_domains") + + /** + * Returns the raw JSON value of [serviceDomains]. + * + * Unlike [serviceDomains], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("service_domains") + @ExcludeMissing + fun _serviceDomains(): JsonField> = serviceDomains + + @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 [Classification]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Classification]. */ + class Builder internal constructor() { + + private var serviceDomains: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(classification: Classification) = apply { + serviceDomains = classification.serviceDomains.map { it.toMutableList() } + additionalProperties = classification.additionalProperties.toMutableMap() + } + + fun serviceDomains(serviceDomains: List) = + serviceDomains(JsonField.of(serviceDomains)) + + /** + * Sets [Builder.serviceDomains] to an arbitrary JSON value. + * + * You should usually call [Builder.serviceDomains] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun serviceDomains(serviceDomains: JsonField>) = apply { + this.serviceDomains = serviceDomains.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [serviceDomains]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addServiceDomain(serviceDomain: String) = apply { + serviceDomains = + (serviceDomains ?: JsonField.of(mutableListOf())).also { + checkKnown("serviceDomains", it).add(serviceDomain) + } + } + + 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 [Classification]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Classification = + Classification( + (serviceDomains ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Classification = apply { + if (validated) { + return@apply + } + + serviceDomains() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (serviceDomains.asKnown().getOrNull()?.size ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Classification && + serviceDomains == other.serviceDomains && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(serviceDomains, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Classification{serviceDomains=$serviceDomains, additionalProperties=$additionalProperties}" + } + + class Extras + @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 [Extras]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Extras]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(extras: Extras) = apply { + additionalProperties = extras.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 [Extras]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Extras = Extras(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Extras = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 Extras && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Extras{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Metadata && + behavior == other.behavior && + classification == other.classification && + extras == other.extras && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(behavior, classification, extras, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Metadata{behavior=$behavior, classification=$classification, extras=$extras, additionalProperties=$additionalProperties}" + } + + class Output + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val availableModes: JsonField>, + private val description: JsonField, + private val valueSchema: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("available_modes") + @ExcludeMissing + availableModes: JsonField> = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("value_schema") + @ExcludeMissing + valueSchema: JsonField = JsonMissing.of(), + ) : this(availableModes, description, valueSchema, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun availableModes(): Optional> = availableModes.getOptional("available_modes") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun valueSchema(): Optional = valueSchema.getOptional("value_schema") + + /** + * Returns the raw JSON value of [availableModes]. + * + * Unlike [availableModes], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("available_modes") + @ExcludeMissing + fun _availableModes(): JsonField> = availableModes + + /** + * 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 [valueSchema]. + * + * Unlike [valueSchema], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("value_schema") + @ExcludeMissing + fun _valueSchema(): JsonField = valueSchema + + @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]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Output]. */ + class Builder internal constructor() { + + private var availableModes: JsonField>? = null + private var description: JsonField = JsonMissing.of() + private var valueSchema: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(output: Output) = apply { + availableModes = output.availableModes.map { it.toMutableList() } + description = output.description + valueSchema = output.valueSchema + additionalProperties = output.additionalProperties.toMutableMap() + } + + fun availableModes(availableModes: List) = + availableModes(JsonField.of(availableModes)) + + /** + * Sets [Builder.availableModes] to an arbitrary JSON value. + * + * You should usually call [Builder.availableModes] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun availableModes(availableModes: JsonField>) = apply { + this.availableModes = availableModes.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [availableModes]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAvailableMode(availableMode: String) = apply { + availableModes = + (availableModes ?: JsonField.of(mutableListOf())).also { + checkKnown("availableModes", it).add(availableMode) + } + } + + 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 + } + + fun valueSchema(valueSchema: ValueSchema) = valueSchema(JsonField.of(valueSchema)) + + /** + * Sets [Builder.valueSchema] to an arbitrary JSON value. + * + * You should usually call [Builder.valueSchema] with a well-typed [ValueSchema] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun valueSchema(valueSchema: JsonField) = apply { + this.valueSchema = valueSchema + } + + 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. + */ + fun build(): Output = + Output( + (availableModes ?: JsonMissing.of()).map { it.toImmutable() }, + description, + valueSchema, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Output = apply { + if (validated) { + return@apply + } + + availableModes() + description() + valueSchema().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (availableModes.asKnown().getOrNull()?.size ?: 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (valueSchema.asKnown().getOrNull()?.validity() ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Output && + availableModes == other.availableModes && + description == other.description && + valueSchema == other.valueSchema && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(availableModes, description, valueSchema, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Output{availableModes=$availableModes, description=$description, valueSchema=$valueSchema, additionalProperties=$additionalProperties}" + } + + class Requirements + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val authorization: JsonField, + private val met: JsonField, + private val secrets: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("authorization") + @ExcludeMissing + authorization: JsonField = JsonMissing.of(), + @JsonProperty("met") @ExcludeMissing met: JsonField = JsonMissing.of(), + @JsonProperty("secrets") + @ExcludeMissing + secrets: JsonField> = JsonMissing.of(), + ) : this(authorization, met, secrets, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun authorization(): Optional = authorization.getOptional("authorization") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun met(): Optional = met.getOptional("met") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun secrets(): Optional> = secrets.getOptional("secrets") + + /** + * Returns the raw JSON value of [authorization]. + * + * Unlike [authorization], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("authorization") + @ExcludeMissing + fun _authorization(): JsonField = authorization + + /** + * Returns the raw JSON value of [met]. + * + * Unlike [met], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("met") @ExcludeMissing fun _met(): JsonField = met + + /** + * Returns the raw JSON value of [secrets]. + * + * Unlike [secrets], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("secrets") @ExcludeMissing fun _secrets(): JsonField> = secrets + + @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 [Requirements]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Requirements]. */ + class Builder internal constructor() { + + private var authorization: JsonField = JsonMissing.of() + private var met: JsonField = JsonMissing.of() + private var secrets: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(requirements: Requirements) = apply { + authorization = requirements.authorization + met = requirements.met + secrets = requirements.secrets.map { it.toMutableList() } + additionalProperties = requirements.additionalProperties.toMutableMap() + } + + fun authorization(authorization: Authorization) = + authorization(JsonField.of(authorization)) + + /** + * Sets [Builder.authorization] to an arbitrary JSON value. + * + * You should usually call [Builder.authorization] with a well-typed [Authorization] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun authorization(authorization: JsonField) = apply { + this.authorization = authorization + } + + fun met(met: Boolean) = met(JsonField.of(met)) + + /** + * Sets [Builder.met] to an arbitrary JSON value. + * + * You should usually call [Builder.met] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun met(met: JsonField) = apply { this.met = met } + + fun secrets(secrets: List) = secrets(JsonField.of(secrets)) + + /** + * Sets [Builder.secrets] to an arbitrary JSON value. + * + * You should usually call [Builder.secrets] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun secrets(secrets: JsonField>) = apply { + this.secrets = secrets.map { it.toMutableList() } + } + + /** + * Adds a single [Secret] to [secrets]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addSecret(secret: Secret) = apply { + secrets = + (secrets ?: JsonField.of(mutableListOf())).also { + checkKnown("secrets", it).add(secret) + } + } + + 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 [Requirements]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Requirements = + Requirements( + authorization, + met, + (secrets ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Requirements = apply { + if (validated) { + return@apply + } + + authorization().ifPresent { it.validate() } + met() + secrets().ifPresent { it.forEach { it.validate() } } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (authorization.asKnown().getOrNull()?.validity() ?: 0) + + (if (met.asKnown().isPresent) 1 else 0) + + (secrets.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + class Authorization + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val id: JsonField, + private val oauth2: JsonField, + private val providerId: JsonField, + private val providerType: JsonField, + private val status: JsonField, + private val statusReason: JsonField, + private val tokenStatus: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("oauth2") + @ExcludeMissing + oauth2: JsonField = JsonMissing.of(), + @JsonProperty("provider_id") + @ExcludeMissing + providerId: JsonField = JsonMissing.of(), + @JsonProperty("provider_type") + @ExcludeMissing + providerType: JsonField = JsonMissing.of(), + @JsonProperty("status") + @ExcludeMissing + status: JsonField = JsonMissing.of(), + @JsonProperty("status_reason") + @ExcludeMissing + statusReason: JsonField = JsonMissing.of(), + @JsonProperty("token_status") + @ExcludeMissing + tokenStatus: JsonField = JsonMissing.of(), + ) : this( + id, + oauth2, + providerId, + providerType, + status, + statusReason, + tokenStatus, + mutableMapOf(), + ) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun oauth2(): Optional = oauth2.getOptional("oauth2") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun providerId(): Optional = providerId.getOptional("provider_id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun providerType(): Optional = providerType.getOptional("provider_type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun status(): Optional = status.getOptional("status") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun statusReason(): Optional = statusReason.getOptional("status_reason") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun tokenStatus(): Optional = tokenStatus.getOptional("token_status") + + /** + * 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 [oauth2]. + * + * Unlike [oauth2], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("oauth2") @ExcludeMissing fun _oauth2(): JsonField = oauth2 + + /** + * Returns the raw JSON value of [providerId]. + * + * Unlike [providerId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("provider_id") + @ExcludeMissing + fun _providerId(): JsonField = providerId + + /** + * Returns the raw JSON value of [providerType]. + * + * Unlike [providerType], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("provider_type") + @ExcludeMissing + fun _providerType(): JsonField = providerType + + /** + * 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 [statusReason]. + * + * Unlike [statusReason], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("status_reason") + @ExcludeMissing + fun _statusReason(): JsonField = statusReason + + /** + * Returns the raw JSON value of [tokenStatus]. + * + * Unlike [tokenStatus], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("token_status") + @ExcludeMissing + fun _tokenStatus(): JsonField = tokenStatus + + @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 [Authorization]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Authorization]. */ + class Builder internal constructor() { + + private var id: JsonField = JsonMissing.of() + private var oauth2: JsonField = JsonMissing.of() + private var providerId: JsonField = JsonMissing.of() + private var providerType: JsonField = JsonMissing.of() + private var status: JsonField = JsonMissing.of() + private var statusReason: JsonField = JsonMissing.of() + private var tokenStatus: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(authorization: Authorization) = apply { + id = authorization.id + oauth2 = authorization.oauth2 + providerId = authorization.providerId + providerType = authorization.providerType + status = authorization.status + statusReason = authorization.statusReason + tokenStatus = authorization.tokenStatus + additionalProperties = authorization.additionalProperties.toMutableMap() + } + + 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 oauth2(oauth2: Oauth2) = oauth2(JsonField.of(oauth2)) + + /** + * Sets [Builder.oauth2] to an arbitrary JSON value. + * + * You should usually call [Builder.oauth2] with a well-typed [Oauth2] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun oauth2(oauth2: JsonField) = apply { this.oauth2 = oauth2 } + + fun providerId(providerId: String) = providerId(JsonField.of(providerId)) + + /** + * Sets [Builder.providerId] to an arbitrary JSON value. + * + * You should usually call [Builder.providerId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun providerId(providerId: JsonField) = apply { + this.providerId = providerId + } + + fun providerType(providerType: String) = providerType(JsonField.of(providerType)) + + /** + * Sets [Builder.providerType] to an arbitrary JSON value. + * + * You should usually call [Builder.providerType] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun providerType(providerType: JsonField) = apply { + this.providerType = providerType + } + + 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 statusReason(statusReason: String) = statusReason(JsonField.of(statusReason)) + + /** + * Sets [Builder.statusReason] to an arbitrary JSON value. + * + * You should usually call [Builder.statusReason] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun statusReason(statusReason: JsonField) = apply { + this.statusReason = statusReason + } + + fun tokenStatus(tokenStatus: TokenStatus) = tokenStatus(JsonField.of(tokenStatus)) + + /** + * Sets [Builder.tokenStatus] to an arbitrary JSON value. + * + * You should usually call [Builder.tokenStatus] with a well-typed [TokenStatus] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun tokenStatus(tokenStatus: JsonField) = apply { + this.tokenStatus = tokenStatus + } + + 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 [Authorization]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Authorization = + Authorization( + id, + oauth2, + providerId, + providerType, + status, + statusReason, + tokenStatus, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Authorization = apply { + if (validated) { + return@apply + } + + id() + oauth2().ifPresent { it.validate() } + providerId() + providerType() + status().ifPresent { it.validate() } + statusReason() + tokenStatus().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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) + + (oauth2.asKnown().getOrNull()?.validity() ?: 0) + + (if (providerId.asKnown().isPresent) 1 else 0) + + (if (providerType.asKnown().isPresent) 1 else 0) + + (status.asKnown().getOrNull()?.validity() ?: 0) + + (if (statusReason.asKnown().isPresent) 1 else 0) + + (tokenStatus.asKnown().getOrNull()?.validity() ?: 0) + + class Oauth2 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val scopes: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("scopes") + @ExcludeMissing + scopes: JsonField> = JsonMissing.of() + ) : this(scopes, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun scopes(): Optional> = scopes.getOptional("scopes") + + /** + * Returns the raw JSON value of [scopes]. + * + * Unlike [scopes], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("scopes") + @ExcludeMissing + fun _scopes(): JsonField> = scopes + + @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 [Oauth2]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Oauth2]. */ + class Builder internal constructor() { + + private var scopes: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(oauth2: Oauth2) = apply { + scopes = oauth2.scopes.map { it.toMutableList() } + additionalProperties = oauth2.additionalProperties.toMutableMap() + } + + fun scopes(scopes: List) = scopes(JsonField.of(scopes)) + + /** + * Sets [Builder.scopes] to an arbitrary JSON value. + * + * You should usually call [Builder.scopes] with a well-typed `List` + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun scopes(scopes: JsonField>) = apply { + this.scopes = scopes.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [scopes]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addScope(scope: String) = apply { + scopes = + (scopes ?: JsonField.of(mutableListOf())).also { + checkKnown("scopes", it).add(scope) + } + } + + 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 [Oauth2]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Oauth2 = + Oauth2( + (scopes ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Oauth2 = apply { + if (validated) { + return@apply + } + + scopes() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (scopes.asKnown().getOrNull()?.size ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Oauth2 && + scopes == other.scopes && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(scopes, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Oauth2{scopes=$scopes, additionalProperties=$additionalProperties}" + } + + 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 ACTIVE = of("active") + + @JvmField val INACTIVE = of("inactive") + + @JvmStatic fun of(value: String) = Status(JsonField.of(value)) + } + + /** An enum containing [Status]'s known values. */ + enum class Known { + ACTIVE, + INACTIVE, + } + + /** + * 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 { + ACTIVE, + INACTIVE, + /** + * 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) { + ACTIVE -> Value.ACTIVE + INACTIVE -> Value.INACTIVE + 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 ArcadeInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + ACTIVE -> Known.ACTIVE + INACTIVE -> Known.INACTIVE + else -> throw ArcadeInvalidDataException("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 ArcadeInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ArcadeInvalidDataException("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: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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() + } + + class TokenStatus + @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 NOT_STARTED = of("not_started") + + @JvmField val PENDING = of("pending") + + @JvmField val COMPLETED = of("completed") + + @JvmField val FAILED = of("failed") + + @JvmStatic fun of(value: String) = TokenStatus(JsonField.of(value)) + } + + /** An enum containing [TokenStatus]'s known values. */ + enum class Known { + NOT_STARTED, + PENDING, + COMPLETED, + FAILED, + } + + /** + * An enum containing [TokenStatus]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [TokenStatus] 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 { + NOT_STARTED, + PENDING, + COMPLETED, + FAILED, + /** + * An enum member indicating that [TokenStatus] 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) { + NOT_STARTED -> Value.NOT_STARTED + PENDING -> Value.PENDING + COMPLETED -> Value.COMPLETED + 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 ArcadeInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + NOT_STARTED -> Known.NOT_STARTED + PENDING -> Known.PENDING + COMPLETED -> Known.COMPLETED + FAILED -> Known.FAILED + else -> throw ArcadeInvalidDataException("Unknown TokenStatus: $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 ArcadeInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ArcadeInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): TokenStatus = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 TokenStatus && 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 Authorization && + id == other.id && + oauth2 == other.oauth2 && + providerId == other.providerId && + providerType == other.providerType && + status == other.status && + statusReason == other.statusReason && + tokenStatus == other.tokenStatus && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + oauth2, + providerId, + providerType, + status, + statusReason, + tokenStatus, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Authorization{id=$id, oauth2=$oauth2, providerId=$providerId, providerType=$providerType, status=$status, statusReason=$statusReason, tokenStatus=$tokenStatus, additionalProperties=$additionalProperties}" + } + + class Secret + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val key: JsonField, + private val met: JsonField, + private val statusReason: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("key") @ExcludeMissing key: JsonField = JsonMissing.of(), + @JsonProperty("met") @ExcludeMissing met: JsonField = JsonMissing.of(), + @JsonProperty("status_reason") + @ExcludeMissing + statusReason: JsonField = JsonMissing.of(), + ) : this(key, met, statusReason, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException 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 key(): String = key.getRequired("key") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun met(): Optional = met.getOptional("met") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun statusReason(): Optional = statusReason.getOptional("status_reason") + + /** + * Returns the raw JSON value of [key]. + * + * Unlike [key], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("key") @ExcludeMissing fun _key(): JsonField = key + + /** + * Returns the raw JSON value of [met]. + * + * Unlike [met], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("met") @ExcludeMissing fun _met(): JsonField = met + + /** + * Returns the raw JSON value of [statusReason]. + * + * Unlike [statusReason], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("status_reason") + @ExcludeMissing + fun _statusReason(): JsonField = statusReason + + @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 [Secret]. + * + * The following fields are required: + * ```java + * .key() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Secret]. */ + class Builder internal constructor() { + + private var key: JsonField? = null + private var met: JsonField = JsonMissing.of() + private var statusReason: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(secret: Secret) = apply { + key = secret.key + met = secret.met + statusReason = secret.statusReason + additionalProperties = secret.additionalProperties.toMutableMap() + } + + fun key(key: String) = key(JsonField.of(key)) + + /** + * Sets [Builder.key] to an arbitrary JSON value. + * + * You should usually call [Builder.key] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun key(key: JsonField) = apply { this.key = key } + + fun met(met: Boolean) = met(JsonField.of(met)) + + /** + * Sets [Builder.met] to an arbitrary JSON value. + * + * You should usually call [Builder.met] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun met(met: JsonField) = apply { this.met = met } + + fun statusReason(statusReason: String) = statusReason(JsonField.of(statusReason)) + + /** + * Sets [Builder.statusReason] to an arbitrary JSON value. + * + * You should usually call [Builder.statusReason] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun statusReason(statusReason: JsonField) = apply { + this.statusReason = statusReason + } + + 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 [Secret]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .key() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Secret = + Secret( + checkRequired("key", key), + met, + statusReason, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Secret = apply { + if (validated) { + return@apply + } + + key() + met() + statusReason() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (key.asKnown().isPresent) 1 else 0) + + (if (met.asKnown().isPresent) 1 else 0) + + (if (statusReason.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Secret && + key == other.key && + met == other.met && + statusReason == other.statusReason && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(key, met, statusReason, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Secret{key=$key, met=$met, statusReason=$statusReason, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Requirements && + authorization == other.authorization && + met == other.met && + secrets == other.secrets && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(authorization, met, secrets, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Requirements{authorization=$authorization, met=$met, secrets=$secrets, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ToolDefinition && + fullyQualifiedName == other.fullyQualifiedName && + input == other.input && + name == other.name && + qualifiedName == other.qualifiedName && + toolkit == other.toolkit && + description == other.description && + formattedSchema == other.formattedSchema && + metadata == other.metadata && + output == other.output && + requirements == other.requirements && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + fullyQualifiedName, + input, + name, + qualifiedName, + toolkit, + description, + formattedSchema, + metadata, + output, + requirements, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ToolDefinition{fullyQualifiedName=$fullyQualifiedName, input=$input, name=$name, qualifiedName=$qualifiedName, toolkit=$toolkit, description=$description, formattedSchema=$formattedSchema, metadata=$metadata, output=$output, requirements=$requirements, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolExecuteParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolExecuteParams.kt similarity index 84% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/ToolExecuteParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolExecuteParams.kt index 135159f..e267f4c 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolExecuteParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolExecuteParams.kt @@ -1,9 +1,8 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.tools import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params import dev.arcade.core.checkRequired import dev.arcade.core.http.Headers @@ -23,25 +22,28 @@ private constructor( fun _additionalBodyProperties(): Map = executeToolRequest._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): ExecuteToolRequest = executeToolRequest - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [ToolExecuteParams]. + * + * The following fields are required: + * ```java + * .executeToolRequest() + * ``` + */ @JvmStatic fun builder() = Builder() } /** A builder for [ToolExecuteParams]. */ - @NoAutoDetect class Builder internal constructor() { private var executeToolRequest: ExecuteToolRequest? = null @@ -157,6 +159,18 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [ToolExecuteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .executeToolRequest() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): ToolExecuteParams = ToolExecuteParams( checkRequired("executeToolRequest", executeToolRequest), @@ -165,15 +179,25 @@ private constructor( ) } + fun _body(): ExecuteToolRequest = executeToolRequest + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is ToolExecuteParams && executeToolRequest == other.executeToolRequest && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is ToolExecuteParams && + executeToolRequest == other.executeToolRequest && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(executeToolRequest, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(executeToolRequest, additionalHeaders, additionalQueryParams) override fun toString() = "ToolExecuteParams{executeToolRequest=$executeToolRequest, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolExecution.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolExecution.kt new file mode 100644 index 0000000..f03513d --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolExecution.kt @@ -0,0 +1,562 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.tools + +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 dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional + +class ToolExecution +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val id: JsonField, + private val createdAt: JsonField, + private val executionStatus: JsonField, + private val executionType: JsonField, + private val finishedAt: JsonField, + private val runAt: JsonField, + private val startedAt: JsonField, + private val toolName: JsonField, + private val toolkitName: JsonField, + private val toolkitVersion: JsonField, + private val updatedAt: JsonField, + private val userId: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("created_at") @ExcludeMissing createdAt: JsonField = JsonMissing.of(), + @JsonProperty("execution_status") + @ExcludeMissing + executionStatus: JsonField = JsonMissing.of(), + @JsonProperty("execution_type") + @ExcludeMissing + executionType: JsonField = JsonMissing.of(), + @JsonProperty("finished_at") + @ExcludeMissing + finishedAt: JsonField = JsonMissing.of(), + @JsonProperty("run_at") @ExcludeMissing runAt: JsonField = JsonMissing.of(), + @JsonProperty("started_at") @ExcludeMissing startedAt: JsonField = JsonMissing.of(), + @JsonProperty("tool_name") @ExcludeMissing toolName: JsonField = JsonMissing.of(), + @JsonProperty("toolkit_name") + @ExcludeMissing + toolkitName: JsonField = JsonMissing.of(), + @JsonProperty("toolkit_version") + @ExcludeMissing + toolkitVersion: JsonField = JsonMissing.of(), + @JsonProperty("updated_at") @ExcludeMissing updatedAt: JsonField = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + ) : this( + id, + createdAt, + executionStatus, + executionType, + finishedAt, + runAt, + startedAt, + toolName, + toolkitName, + toolkitVersion, + updatedAt, + userId, + mutableMapOf(), + ) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun createdAt(): Optional = createdAt.getOptional("created_at") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun executionStatus(): Optional = executionStatus.getOptional("execution_status") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun executionType(): Optional = executionType.getOptional("execution_type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun finishedAt(): Optional = finishedAt.getOptional("finished_at") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun runAt(): Optional = runAt.getOptional("run_at") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun startedAt(): Optional = startedAt.getOptional("started_at") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun toolName(): Optional = toolName.getOptional("tool_name") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun toolkitName(): Optional = toolkitName.getOptional("toolkit_name") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun toolkitVersion(): Optional = toolkitVersion.getOptional("toolkit_version") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun updatedAt(): Optional = updatedAt.getOptional("updated_at") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun userId(): Optional = userId.getOptional("user_id") + + /** + * 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 [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 [executionStatus]. + * + * Unlike [executionStatus], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("execution_status") + @ExcludeMissing + fun _executionStatus(): JsonField = executionStatus + + /** + * Returns the raw JSON value of [executionType]. + * + * Unlike [executionType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("execution_type") + @ExcludeMissing + fun _executionType(): JsonField = executionType + + /** + * Returns the raw JSON value of [finishedAt]. + * + * Unlike [finishedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("finished_at") @ExcludeMissing fun _finishedAt(): JsonField = finishedAt + + /** + * Returns the raw JSON value of [runAt]. + * + * Unlike [runAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("run_at") @ExcludeMissing fun _runAt(): JsonField = runAt + + /** + * Returns the raw JSON value of [startedAt]. + * + * Unlike [startedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("started_at") @ExcludeMissing fun _startedAt(): JsonField = startedAt + + /** + * Returns the raw JSON value of [toolName]. + * + * Unlike [toolName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tool_name") @ExcludeMissing fun _toolName(): JsonField = toolName + + /** + * Returns the raw JSON value of [toolkitName]. + * + * Unlike [toolkitName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("toolkit_name") + @ExcludeMissing + fun _toolkitName(): JsonField = toolkitName + + /** + * Returns the raw JSON value of [toolkitVersion]. + * + * Unlike [toolkitVersion], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("toolkit_version") + @ExcludeMissing + fun _toolkitVersion(): JsonField = toolkitVersion + + /** + * Returns the raw JSON value of [updatedAt]. + * + * Unlike [updatedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("updated_at") @ExcludeMissing fun _updatedAt(): JsonField = updatedAt + + /** + * Returns the raw JSON value of [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + + @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 [ToolExecution]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ToolExecution]. */ + class Builder internal constructor() { + + private var id: JsonField = JsonMissing.of() + private var createdAt: JsonField = JsonMissing.of() + private var executionStatus: JsonField = JsonMissing.of() + private var executionType: JsonField = JsonMissing.of() + private var finishedAt: JsonField = JsonMissing.of() + private var runAt: JsonField = JsonMissing.of() + private var startedAt: JsonField = JsonMissing.of() + private var toolName: JsonField = JsonMissing.of() + private var toolkitName: JsonField = JsonMissing.of() + private var toolkitVersion: JsonField = JsonMissing.of() + private var updatedAt: JsonField = JsonMissing.of() + private var userId: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(toolExecution: ToolExecution) = apply { + id = toolExecution.id + createdAt = toolExecution.createdAt + executionStatus = toolExecution.executionStatus + executionType = toolExecution.executionType + finishedAt = toolExecution.finishedAt + runAt = toolExecution.runAt + startedAt = toolExecution.startedAt + toolName = toolExecution.toolName + toolkitName = toolExecution.toolkitName + toolkitVersion = toolExecution.toolkitVersion + updatedAt = toolExecution.updatedAt + userId = toolExecution.userId + additionalProperties = toolExecution.additionalProperties.toMutableMap() + } + + 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 createdAt(createdAt: String) = createdAt(JsonField.of(createdAt)) + + /** + * Sets [Builder.createdAt] to an arbitrary JSON value. + * + * You should usually call [Builder.createdAt] with a well-typed [String] 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 executionStatus(executionStatus: String) = + executionStatus(JsonField.of(executionStatus)) + + /** + * Sets [Builder.executionStatus] to an arbitrary JSON value. + * + * You should usually call [Builder.executionStatus] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun executionStatus(executionStatus: JsonField) = apply { + this.executionStatus = executionStatus + } + + fun executionType(executionType: String) = executionType(JsonField.of(executionType)) + + /** + * Sets [Builder.executionType] to an arbitrary JSON value. + * + * You should usually call [Builder.executionType] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun executionType(executionType: JsonField) = apply { + this.executionType = executionType + } + + fun finishedAt(finishedAt: String) = finishedAt(JsonField.of(finishedAt)) + + /** + * Sets [Builder.finishedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.finishedAt] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun finishedAt(finishedAt: JsonField) = apply { this.finishedAt = finishedAt } + + fun runAt(runAt: String) = runAt(JsonField.of(runAt)) + + /** + * Sets [Builder.runAt] to an arbitrary JSON value. + * + * You should usually call [Builder.runAt] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun runAt(runAt: JsonField) = apply { this.runAt = runAt } + + fun startedAt(startedAt: String) = startedAt(JsonField.of(startedAt)) + + /** + * Sets [Builder.startedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.startedAt] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun startedAt(startedAt: JsonField) = apply { this.startedAt = startedAt } + + fun toolName(toolName: String) = toolName(JsonField.of(toolName)) + + /** + * Sets [Builder.toolName] to an arbitrary JSON value. + * + * You should usually call [Builder.toolName] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun toolName(toolName: JsonField) = apply { this.toolName = toolName } + + fun toolkitName(toolkitName: String) = toolkitName(JsonField.of(toolkitName)) + + /** + * Sets [Builder.toolkitName] to an arbitrary JSON value. + * + * You should usually call [Builder.toolkitName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun toolkitName(toolkitName: JsonField) = apply { this.toolkitName = toolkitName } + + fun toolkitVersion(toolkitVersion: String) = toolkitVersion(JsonField.of(toolkitVersion)) + + /** + * Sets [Builder.toolkitVersion] to an arbitrary JSON value. + * + * You should usually call [Builder.toolkitVersion] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun toolkitVersion(toolkitVersion: JsonField) = apply { + this.toolkitVersion = toolkitVersion + } + + fun updatedAt(updatedAt: String) = updatedAt(JsonField.of(updatedAt)) + + /** + * Sets [Builder.updatedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.updatedAt] with a well-typed [String] 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 userId(userId: String) = userId(JsonField.of(userId)) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun userId(userId: JsonField) = apply { this.userId = userId } + + 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 [ToolExecution]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ToolExecution = + ToolExecution( + id, + createdAt, + executionStatus, + executionType, + finishedAt, + runAt, + startedAt, + toolName, + toolkitName, + toolkitVersion, + updatedAt, + userId, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ToolExecution = apply { + if (validated) { + return@apply + } + + id() + createdAt() + executionStatus() + executionType() + finishedAt() + runAt() + startedAt() + toolName() + toolkitName() + toolkitVersion() + updatedAt() + userId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (createdAt.asKnown().isPresent) 1 else 0) + + (if (executionStatus.asKnown().isPresent) 1 else 0) + + (if (executionType.asKnown().isPresent) 1 else 0) + + (if (finishedAt.asKnown().isPresent) 1 else 0) + + (if (runAt.asKnown().isPresent) 1 else 0) + + (if (startedAt.asKnown().isPresent) 1 else 0) + + (if (toolName.asKnown().isPresent) 1 else 0) + + (if (toolkitName.asKnown().isPresent) 1 else 0) + + (if (toolkitVersion.asKnown().isPresent) 1 else 0) + + (if (updatedAt.asKnown().isPresent) 1 else 0) + + (if (userId.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ToolExecution && + id == other.id && + createdAt == other.createdAt && + executionStatus == other.executionStatus && + executionType == other.executionType && + finishedAt == other.finishedAt && + runAt == other.runAt && + startedAt == other.startedAt && + toolName == other.toolName && + toolkitName == other.toolkitName && + toolkitVersion == other.toolkitVersion && + updatedAt == other.updatedAt && + userId == other.userId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + createdAt, + executionStatus, + executionType, + finishedAt, + runAt, + startedAt, + toolName, + toolkitName, + toolkitVersion, + updatedAt, + userId, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ToolExecution{id=$id, createdAt=$createdAt, executionStatus=$executionStatus, executionType=$executionType, finishedAt=$finishedAt, runAt=$runAt, startedAt=$startedAt, toolName=$toolName, toolkitName=$toolkitName, toolkitVersion=$toolkitVersion, updatedAt=$updatedAt, userId=$userId, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolExecutionAttempt.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolExecutionAttempt.kt similarity index 50% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/ToolExecutionAttempt.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolExecutionAttempt.kt index 64a13b1..fd3dbb5 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolExecutionAttempt.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolExecutionAttempt.kt @@ -1,6 +1,6 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.tools import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter @@ -11,88 +11,139 @@ import dev.arcade.core.ExcludeMissing import dev.arcade.core.JsonField import dev.arcade.core.JsonMissing import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect +import dev.arcade.core.checkKnown import dev.arcade.core.checkRequired -import dev.arcade.core.immutableEmptyMap import dev.arcade.core.toImmutable import dev.arcade.errors.ArcadeInvalidDataException +import dev.arcade.models.AuthorizationResponse +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class ToolExecutionAttempt -@JsonCreator +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("finished_at") - @ExcludeMissing - private val finishedAt: JsonField = JsonMissing.of(), - @JsonProperty("output") - @ExcludeMissing - private val output: JsonField = JsonMissing.of(), - @JsonProperty("started_at") - @ExcludeMissing - private val startedAt: JsonField = JsonMissing.of(), - @JsonProperty("success") - @ExcludeMissing - private val success: JsonField = JsonMissing.of(), - @JsonProperty("system_error_message") - @ExcludeMissing - private val systemErrorMessage: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val finishedAt: JsonField, + private val output: JsonField, + private val startedAt: JsonField, + private val success: JsonField, + private val systemErrorMessage: JsonField, + private val additionalProperties: MutableMap, ) { - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - fun finishedAt(): Optional = Optional.ofNullable(finishedAt.getNullable("finished_at")) - - fun output(): Optional = Optional.ofNullable(output.getNullable("output")) - - fun startedAt(): Optional = Optional.ofNullable(startedAt.getNullable("started_at")) - - fun success(): Optional = Optional.ofNullable(success.getNullable("success")) - + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("finished_at") + @ExcludeMissing + finishedAt: JsonField = JsonMissing.of(), + @JsonProperty("output") @ExcludeMissing output: JsonField = JsonMissing.of(), + @JsonProperty("started_at") @ExcludeMissing startedAt: JsonField = JsonMissing.of(), + @JsonProperty("success") @ExcludeMissing success: JsonField = JsonMissing.of(), + @JsonProperty("system_error_message") + @ExcludeMissing + systemErrorMessage: JsonField = JsonMissing.of(), + ) : this(id, finishedAt, output, startedAt, success, systemErrorMessage, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun finishedAt(): Optional = finishedAt.getOptional("finished_at") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun output(): Optional = output.getOptional("output") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun startedAt(): Optional = startedAt.getOptional("started_at") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun success(): Optional = success.getOptional("success") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun systemErrorMessage(): Optional = - Optional.ofNullable(systemErrorMessage.getNullable("system_error_message")) + systemErrorMessage.getOptional("system_error_message") + /** + * 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 [finishedAt]. + * + * Unlike [finishedAt], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("finished_at") @ExcludeMissing fun _finishedAt(): JsonField = finishedAt + /** + * 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 + /** + * Returns the raw JSON value of [startedAt]. + * + * Unlike [startedAt], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("started_at") @ExcludeMissing fun _startedAt(): JsonField = startedAt + /** + * Returns the raw JSON value of [success]. + * + * Unlike [success], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("success") @ExcludeMissing fun _success(): JsonField = success + /** + * Returns the raw JSON value of [systemErrorMessage]. + * + * Unlike [systemErrorMessage], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("system_error_message") @ExcludeMissing fun _systemErrorMessage(): JsonField = systemErrorMessage + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ToolExecutionAttempt = apply { - if (validated) { - return@apply - } - - id() - finishedAt() - output().ifPresent { it.validate() } - startedAt() - success() - systemErrorMessage() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [ToolExecutionAttempt]. */ @JvmStatic fun builder() = Builder() } @@ -120,27 +171,66 @@ private constructor( 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 finishedAt(finishedAt: String) = finishedAt(JsonField.of(finishedAt)) + /** + * Sets [Builder.finishedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.finishedAt] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun finishedAt(finishedAt: JsonField) = apply { this.finishedAt = finishedAt } 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 startedAt(startedAt: String) = startedAt(JsonField.of(startedAt)) + /** + * Sets [Builder.startedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.startedAt] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun startedAt(startedAt: JsonField) = apply { this.startedAt = startedAt } fun success(success: Boolean) = success(JsonField.of(success)) + /** + * Sets [Builder.success] to an arbitrary JSON value. + * + * You should usually call [Builder.success] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun success(success: JsonField) = apply { this.success = success } fun systemErrorMessage(systemErrorMessage: String) = systemErrorMessage(JsonField.of(systemErrorMessage)) + /** + * Sets [Builder.systemErrorMessage] to an arbitrary JSON value. + * + * You should usually call [Builder.systemErrorMessage] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun systemErrorMessage(systemErrorMessage: JsonField) = apply { this.systemErrorMessage = systemErrorMessage } @@ -164,6 +254,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [ToolExecutionAttempt]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): ToolExecutionAttempt = ToolExecutionAttempt( id, @@ -172,66 +267,134 @@ private constructor( startedAt, success, systemErrorMessage, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): ToolExecutionAttempt = apply { + if (validated) { + return@apply + } + + id() + finishedAt() + output().ifPresent { it.validate() } + startedAt() + success() + systemErrorMessage() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (finishedAt.asKnown().isPresent) 1 else 0) + + (output.asKnown().getOrNull()?.validity() ?: 0) + + (if (startedAt.asKnown().isPresent) 1 else 0) + + (if (success.asKnown().isPresent) 1 else 0) + + (if (systemErrorMessage.asKnown().isPresent) 1 else 0) + class Output - @JsonCreator + @JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( - @JsonProperty("authorization") - @ExcludeMissing - private val authorization: JsonField = JsonMissing.of(), - @JsonProperty("error") - @ExcludeMissing - private val error: JsonField = JsonMissing.of(), - @JsonProperty("logs") - @ExcludeMissing - private val logs: JsonField> = JsonMissing.of(), - @JsonProperty("value") @ExcludeMissing private val value: JsonValue = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val authorization: JsonField, + private val error: JsonField, + private val logs: JsonField>, + private val value: JsonValue, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("authorization") + @ExcludeMissing + authorization: JsonField = JsonMissing.of(), + @JsonProperty("error") @ExcludeMissing error: JsonField = JsonMissing.of(), + @JsonProperty("logs") @ExcludeMissing logs: JsonField> = JsonMissing.of(), + @JsonProperty("value") @ExcludeMissing value: JsonValue = JsonMissing.of(), + ) : this(authorization, error, logs, value, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun authorization(): Optional = - Optional.ofNullable(authorization.getNullable("authorization")) - - fun error(): Optional = Optional.ofNullable(error.getNullable("error")) - - fun logs(): Optional> = Optional.ofNullable(logs.getNullable("logs")) - + authorization.getOptional("authorization") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun error(): Optional = error.getOptional("error") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun logs(): Optional> = logs.getOptional("logs") + + /** + * This arbitrary value can be deserialized into a custom type using the `convert` method: + * ```java + * MyClass myObject = output.value().convert(MyClass.class); + * ``` + */ @JsonProperty("value") @ExcludeMissing fun _value(): JsonValue = value + /** + * Returns the raw JSON value of [authorization]. + * + * Unlike [authorization], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("authorization") @ExcludeMissing fun _authorization(): JsonField = authorization + /** + * 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 [logs]. + * + * Unlike [logs], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("logs") @ExcludeMissing fun _logs(): JsonField> = logs + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Output = apply { - if (validated) { - return@apply - } - - authorization().ifPresent { it.validate() } - error().ifPresent { it.validate() } - logs().ifPresent { it.forEach { it.validate() } } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Output]. */ @JvmStatic fun builder() = Builder() } @@ -256,31 +419,49 @@ private constructor( fun authorization(authorization: AuthorizationResponse) = authorization(JsonField.of(authorization)) + /** + * Sets [Builder.authorization] to an arbitrary JSON value. + * + * You should usually call [Builder.authorization] with a well-typed + * [AuthorizationResponse] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun authorization(authorization: JsonField) = apply { this.authorization = authorization } 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 logs(logs: List) = logs(JsonField.of(logs)) + /** + * Sets [Builder.logs] to an arbitrary JSON value. + * + * You should usually call [Builder.logs] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun logs(logs: JsonField>) = apply { this.logs = logs.map { it.toMutableList() } } + /** + * Adds a single [Log] to [logs]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addLog(log: Log) = apply { logs = - (logs ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(log) - } + (logs ?: JsonField.of(mutableListOf())).also { checkKnown("logs", it).add(log) } } fun value(value: JsonValue) = apply { this.value = value } @@ -304,133 +485,271 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Output]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Output = Output( authorization, error, (logs ?: JsonMissing.of()).map { it.toImmutable() }, value, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): Output = apply { + if (validated) { + return@apply + } + + authorization().ifPresent { it.validate() } + error().ifPresent { it.validate() } + logs().ifPresent { it.forEach { it.validate() } } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (authorization.asKnown().getOrNull()?.validity() ?: 0) + + (error.asKnown().getOrNull()?.validity() ?: 0) + + (logs.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + class Error - @JsonCreator + @JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( - @JsonProperty("can_retry") - @ExcludeMissing - private val canRetry: JsonField = JsonMissing.of(), - @JsonProperty("kind") - @ExcludeMissing - private val kind: JsonField = JsonMissing.of(), - @JsonProperty("message") - @ExcludeMissing - private val message: JsonField = JsonMissing.of(), - @JsonProperty("additional_prompt_content") - @ExcludeMissing - private val additionalPromptContent: JsonField = JsonMissing.of(), - @JsonProperty("developer_message") - @ExcludeMissing - private val developerMessage: JsonField = JsonMissing.of(), - @JsonProperty("extra") - @ExcludeMissing - private val extra: JsonField = JsonMissing.of(), - @JsonProperty("retry_after_ms") - @ExcludeMissing - private val retryAfterMs: JsonField = JsonMissing.of(), - @JsonProperty("stacktrace") - @ExcludeMissing - private val stacktrace: JsonField = JsonMissing.of(), - @JsonProperty("status_code") - @ExcludeMissing - private val statusCode: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val canRetry: JsonField, + private val kind: JsonField, + private val message: JsonField, + private val additionalPromptContent: JsonField, + private val developerMessage: JsonField, + private val extra: JsonField, + private val retryAfterMs: JsonField, + private val stacktrace: JsonField, + private val statusCode: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("can_retry") + @ExcludeMissing + canRetry: JsonField = JsonMissing.of(), + @JsonProperty("kind") @ExcludeMissing kind: JsonField = JsonMissing.of(), + @JsonProperty("message") + @ExcludeMissing + message: JsonField = JsonMissing.of(), + @JsonProperty("additional_prompt_content") + @ExcludeMissing + additionalPromptContent: JsonField = JsonMissing.of(), + @JsonProperty("developer_message") + @ExcludeMissing + developerMessage: JsonField = JsonMissing.of(), + @JsonProperty("extra") @ExcludeMissing extra: JsonField = JsonMissing.of(), + @JsonProperty("retry_after_ms") + @ExcludeMissing + retryAfterMs: JsonField = JsonMissing.of(), + @JsonProperty("stacktrace") + @ExcludeMissing + stacktrace: JsonField = JsonMissing.of(), + @JsonProperty("status_code") + @ExcludeMissing + statusCode: JsonField = JsonMissing.of(), + ) : this( + canRetry, + kind, + message, + additionalPromptContent, + developerMessage, + extra, + retryAfterMs, + stacktrace, + statusCode, + mutableMapOf(), + ) + + /** + * @throws ArcadeInvalidDataException 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 canRetry(): Boolean = canRetry.getRequired("can_retry") + /** + * @throws ArcadeInvalidDataException 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 kind(): Kind = kind.getRequired("kind") + /** + * @throws ArcadeInvalidDataException 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 message(): String = message.getRequired("message") + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ fun additionalPromptContent(): Optional = - Optional.ofNullable( - additionalPromptContent.getNullable("additional_prompt_content") - ) + additionalPromptContent.getOptional("additional_prompt_content") + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ fun developerMessage(): Optional = - Optional.ofNullable(developerMessage.getNullable("developer_message")) - - fun extra(): Optional = Optional.ofNullable(extra.getNullable("extra")) - - fun retryAfterMs(): Optional = - Optional.ofNullable(retryAfterMs.getNullable("retry_after_ms")) - - fun stacktrace(): Optional = - Optional.ofNullable(stacktrace.getNullable("stacktrace")) - - fun statusCode(): Optional = - Optional.ofNullable(statusCode.getNullable("status_code")) - + developerMessage.getOptional("developer_message") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun extra(): Optional = extra.getOptional("extra") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun retryAfterMs(): Optional = retryAfterMs.getOptional("retry_after_ms") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun stacktrace(): Optional = stacktrace.getOptional("stacktrace") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun statusCode(): Optional = statusCode.getOptional("status_code") + + /** + * Returns the raw JSON value of [canRetry]. + * + * Unlike [canRetry], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("can_retry") @ExcludeMissing fun _canRetry(): JsonField = canRetry + /** + * Returns the raw JSON value of [kind]. + * + * Unlike [kind], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("kind") @ExcludeMissing fun _kind(): JsonField = kind + /** + * Returns the raw JSON value of [message]. + * + * Unlike [message], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("message") @ExcludeMissing fun _message(): JsonField = message + /** + * Returns the raw JSON value of [additionalPromptContent]. + * + * Unlike [additionalPromptContent], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("additional_prompt_content") @ExcludeMissing fun _additionalPromptContent(): JsonField = additionalPromptContent + /** + * Returns the raw JSON value of [developerMessage]. + * + * Unlike [developerMessage], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("developer_message") @ExcludeMissing fun _developerMessage(): JsonField = developerMessage + /** + * Returns the raw JSON value of [extra]. + * + * Unlike [extra], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("extra") @ExcludeMissing fun _extra(): JsonField = extra + /** + * Returns the raw JSON value of [retryAfterMs]. + * + * Unlike [retryAfterMs], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("retry_after_ms") @ExcludeMissing fun _retryAfterMs(): JsonField = retryAfterMs + /** + * Returns the raw JSON value of [stacktrace]. + * + * Unlike [stacktrace], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("stacktrace") @ExcludeMissing fun _stacktrace(): JsonField = stacktrace + /** + * Returns the raw JSON value of [statusCode]. + * + * Unlike [statusCode], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("status_code") @ExcludeMissing fun _statusCode(): JsonField = statusCode + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Error = apply { - if (validated) { - return@apply - } - - canRetry() - kind() - message() - additionalPromptContent() - developerMessage() - extra().ifPresent { it.validate() } - retryAfterMs() - stacktrace() - statusCode() - validated = true - } + 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 + * .canRetry() + * .kind() + * .message() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -464,19 +783,47 @@ private constructor( fun canRetry(canRetry: Boolean) = canRetry(JsonField.of(canRetry)) + /** + * Sets [Builder.canRetry] to an arbitrary JSON value. + * + * You should usually call [Builder.canRetry] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun canRetry(canRetry: JsonField) = apply { this.canRetry = canRetry } fun kind(kind: Kind) = kind(JsonField.of(kind)) + /** + * Sets [Builder.kind] to an arbitrary JSON value. + * + * You should usually call [Builder.kind] with a well-typed [Kind] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun kind(kind: JsonField) = apply { this.kind = kind } fun message(message: String) = message(JsonField.of(message)) + /** + * Sets [Builder.message] to an arbitrary JSON value. + * + * You should usually call [Builder.message] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun message(message: JsonField) = apply { this.message = message } fun additionalPromptContent(additionalPromptContent: String) = additionalPromptContent(JsonField.of(additionalPromptContent)) + /** + * Sets [Builder.additionalPromptContent] to an arbitrary JSON value. + * + * You should usually call [Builder.additionalPromptContent] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun additionalPromptContent(additionalPromptContent: JsonField) = apply { this.additionalPromptContent = additionalPromptContent } @@ -484,28 +831,63 @@ private constructor( fun developerMessage(developerMessage: String) = developerMessage(JsonField.of(developerMessage)) + /** + * Sets [Builder.developerMessage] to an arbitrary JSON value. + * + * You should usually call [Builder.developerMessage] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ fun developerMessage(developerMessage: JsonField) = apply { this.developerMessage = developerMessage } fun extra(extra: Extra) = extra(JsonField.of(extra)) + /** + * Sets [Builder.extra] to an arbitrary JSON value. + * + * You should usually call [Builder.extra] with a well-typed [Extra] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun extra(extra: JsonField) = apply { this.extra = extra } fun retryAfterMs(retryAfterMs: Long) = retryAfterMs(JsonField.of(retryAfterMs)) + /** + * Sets [Builder.retryAfterMs] to an arbitrary JSON value. + * + * You should usually call [Builder.retryAfterMs] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun retryAfterMs(retryAfterMs: JsonField) = apply { this.retryAfterMs = retryAfterMs } fun stacktrace(stacktrace: String) = stacktrace(JsonField.of(stacktrace)) + /** + * Sets [Builder.stacktrace] to an arbitrary JSON value. + * + * You should usually call [Builder.stacktrace] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun stacktrace(stacktrace: JsonField) = apply { this.stacktrace = stacktrace } fun statusCode(statusCode: Long) = statusCode(JsonField.of(statusCode)) + /** + * Sets [Builder.statusCode] to an arbitrary JSON value. + * + * You should usually call [Builder.statusCode] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun statusCode(statusCode: JsonField) = apply { this.statusCode = statusCode } fun additionalProperties(additionalProperties: Map) = apply { @@ -530,6 +912,20 @@ private constructor( 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 + * .canRetry() + * .kind() + * .message() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): Error = Error( checkRequired("canRetry", canRetry), @@ -541,10 +937,55 @@ private constructor( retryAfterMs, stacktrace, statusCode, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Error = apply { + if (validated) { + return@apply + } + + canRetry() + kind().validate() + message() + additionalPromptContent() + developerMessage() + extra().ifPresent { it.validate() } + retryAfterMs() + stacktrace() + statusCode() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (canRetry.asKnown().isPresent) 1 else 0) + + (kind.asKnown().getOrNull()?.validity() ?: 0) + + (if (message.asKnown().isPresent) 1 else 0) + + (if (additionalPromptContent.asKnown().isPresent) 1 else 0) + + (if (developerMessage.asKnown().isPresent) 1 else 0) + + (extra.asKnown().getOrNull()?.validity() ?: 0) + + (if (retryAfterMs.asKnown().isPresent) 1 else 0) + + (if (stacktrace.asKnown().isPresent) 1 else 0) + + (if (statusCode.asKnown().isPresent) 1 else 0) + class Kind @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -585,6 +1026,10 @@ private constructor( @JvmField val TOOL_RUNTIME_FATAL = of("TOOL_RUNTIME_FATAL") + @JvmField val CONTEXT_CHECK_FAILED = of("CONTEXT_CHECK_FAILED") + + @JvmField val CONTEXT_DENIED = of("CONTEXT_DENIED") + @JvmField val UPSTREAM_RUNTIME_BAD_REQUEST = of("UPSTREAM_RUNTIME_BAD_REQUEST") @JvmField val UPSTREAM_RUNTIME_AUTH_ERROR = of("UPSTREAM_RUNTIME_AUTH_ERROR") @@ -618,6 +1063,8 @@ private constructor( TOOL_RUNTIME_RETRY, TOOL_RUNTIME_CONTEXT_REQUIRED, TOOL_RUNTIME_FATAL, + CONTEXT_CHECK_FAILED, + CONTEXT_DENIED, UPSTREAM_RUNTIME_BAD_REQUEST, UPSTREAM_RUNTIME_AUTH_ERROR, UPSTREAM_RUNTIME_NOT_FOUND, @@ -648,6 +1095,8 @@ private constructor( TOOL_RUNTIME_RETRY, TOOL_RUNTIME_CONTEXT_REQUIRED, TOOL_RUNTIME_FATAL, + CONTEXT_CHECK_FAILED, + CONTEXT_DENIED, UPSTREAM_RUNTIME_BAD_REQUEST, UPSTREAM_RUNTIME_AUTH_ERROR, UPSTREAM_RUNTIME_NOT_FOUND, @@ -681,6 +1130,8 @@ private constructor( TOOL_RUNTIME_RETRY -> Value.TOOL_RUNTIME_RETRY TOOL_RUNTIME_CONTEXT_REQUIRED -> Value.TOOL_RUNTIME_CONTEXT_REQUIRED TOOL_RUNTIME_FATAL -> Value.TOOL_RUNTIME_FATAL + CONTEXT_CHECK_FAILED -> Value.CONTEXT_CHECK_FAILED + CONTEXT_DENIED -> Value.CONTEXT_DENIED UPSTREAM_RUNTIME_BAD_REQUEST -> Value.UPSTREAM_RUNTIME_BAD_REQUEST UPSTREAM_RUNTIME_AUTH_ERROR -> Value.UPSTREAM_RUNTIME_AUTH_ERROR UPSTREAM_RUNTIME_NOT_FOUND -> Value.UPSTREAM_RUNTIME_NOT_FOUND @@ -713,6 +1164,8 @@ private constructor( TOOL_RUNTIME_RETRY -> Known.TOOL_RUNTIME_RETRY TOOL_RUNTIME_CONTEXT_REQUIRED -> Known.TOOL_RUNTIME_CONTEXT_REQUIRED TOOL_RUNTIME_FATAL -> Known.TOOL_RUNTIME_FATAL + CONTEXT_CHECK_FAILED -> Known.CONTEXT_CHECK_FAILED + CONTEXT_DENIED -> Known.CONTEXT_DENIED UPSTREAM_RUNTIME_BAD_REQUEST -> Known.UPSTREAM_RUNTIME_BAD_REQUEST UPSTREAM_RUNTIME_AUTH_ERROR -> Known.UPSTREAM_RUNTIME_AUTH_ERROR UPSTREAM_RUNTIME_NOT_FOUND -> Known.UPSTREAM_RUNTIME_NOT_FOUND @@ -738,12 +1191,39 @@ private constructor( ArcadeInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Kind = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 /* spotless:off */ other is Kind && value == other.value /* spotless:on */ + return other is Kind && value == other.value } override fun hashCode() = value.hashCode() @@ -751,32 +1231,22 @@ private constructor( override fun toString() = value.toString() } - @NoAutoDetect class Extra @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Extra = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Extra]. */ @JvmStatic fun builder() = Builder() } @@ -812,20 +1282,53 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Extra]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Extra = Extra(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): Extra = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 /* spotless:off */ other is Extra && additionalProperties == other.additionalProperties /* spotless:on */ + return other is Extra && additionalProperties == other.additionalProperties } - /* spotless:off */ private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ override fun hashCode(): Int = hashCode @@ -837,12 +1340,33 @@ private constructor( return true } - return /* spotless:off */ other is Error && canRetry == other.canRetry && kind == other.kind && message == other.message && additionalPromptContent == other.additionalPromptContent && developerMessage == other.developerMessage && extra == other.extra && retryAfterMs == other.retryAfterMs && stacktrace == other.stacktrace && statusCode == other.statusCode && additionalProperties == other.additionalProperties /* spotless:on */ + return other is Error && + canRetry == other.canRetry && + kind == other.kind && + message == other.message && + additionalPromptContent == other.additionalPromptContent && + developerMessage == other.developerMessage && + extra == other.extra && + retryAfterMs == other.retryAfterMs && + stacktrace == other.stacktrace && + statusCode == other.statusCode && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(canRetry, kind, message, additionalPromptContent, developerMessage, extra, retryAfterMs, stacktrace, statusCode, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash( + canRetry, + kind, + message, + additionalPromptContent, + developerMessage, + extra, + retryAfterMs, + stacktrace, + statusCode, + additionalProperties, + ) + } override fun hashCode(): Int = hashCode @@ -850,56 +1374,90 @@ private constructor( "Error{canRetry=$canRetry, kind=$kind, message=$message, additionalPromptContent=$additionalPromptContent, developerMessage=$developerMessage, extra=$extra, retryAfterMs=$retryAfterMs, stacktrace=$stacktrace, statusCode=$statusCode, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Log - @JsonCreator + @JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( - @JsonProperty("level") - @ExcludeMissing - private val level: JsonField = JsonMissing.of(), - @JsonProperty("message") - @ExcludeMissing - private val message: JsonField = JsonMissing.of(), - @JsonProperty("subtype") - @ExcludeMissing - private val subtype: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val level: JsonField, + private val message: JsonField, + private val subtype: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("level") @ExcludeMissing level: JsonField = JsonMissing.of(), + @JsonProperty("message") + @ExcludeMissing + message: JsonField = JsonMissing.of(), + @JsonProperty("subtype") + @ExcludeMissing + subtype: JsonField = JsonMissing.of(), + ) : this(level, message, subtype, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException 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 level(): String = level.getRequired("level") + /** + * @throws ArcadeInvalidDataException 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 message(): String = message.getRequired("message") - fun subtype(): Optional = Optional.ofNullable(subtype.getNullable("subtype")) - + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun subtype(): Optional = subtype.getOptional("subtype") + + /** + * Returns the raw JSON value of [level]. + * + * Unlike [level], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("level") @ExcludeMissing fun _level(): JsonField = level + /** + * Returns the raw JSON value of [message]. + * + * Unlike [message], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("message") @ExcludeMissing fun _message(): JsonField = message + /** + * Returns the raw JSON value of [subtype]. + * + * Unlike [subtype], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("subtype") @ExcludeMissing fun _subtype(): JsonField = subtype + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Log = apply { - if (validated) { - return@apply - } - - level() - message() - subtype() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Log]. + * + * The following fields are required: + * ```java + * .level() + * .message() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -921,14 +1479,35 @@ private constructor( fun level(level: String) = level(JsonField.of(level)) + /** + * Sets [Builder.level] to an arbitrary JSON value. + * + * You should usually call [Builder.level] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun level(level: JsonField) = apply { this.level = level } fun message(message: String) = message(JsonField.of(message)) + /** + * Sets [Builder.message] to an arbitrary JSON value. + * + * You should usually call [Builder.message] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun message(message: JsonField) = apply { this.message = message } fun subtype(subtype: String) = subtype(JsonField.of(subtype)) + /** + * Sets [Builder.subtype] to an arbitrary JSON value. + * + * You should usually call [Builder.subtype] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun subtype(subtype: JsonField) = apply { this.subtype = subtype } fun additionalProperties(additionalProperties: Map) = apply { @@ -953,26 +1532,76 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Log]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .level() + * .message() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): Log = Log( checkRequired("level", level), checkRequired("message", message), subtype, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Log = apply { + if (validated) { + return@apply + } + + level() + message() + subtype() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (level.asKnown().isPresent) 1 else 0) + + (if (message.asKnown().isPresent) 1 else 0) + + (if (subtype.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is Log && level == other.level && message == other.message && subtype == other.subtype && additionalProperties == other.additionalProperties /* spotless:on */ + return other is Log && + level == other.level && + message == other.message && + subtype == other.subtype && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(level, message, subtype, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash(level, message, subtype, additionalProperties) + } override fun hashCode(): Int = hashCode @@ -985,12 +1614,17 @@ private constructor( return true } - return /* spotless:off */ other is Output && authorization == other.authorization && error == other.error && logs == other.logs && value == other.value && additionalProperties == other.additionalProperties /* spotless:on */ + return other is Output && + authorization == other.authorization && + error == other.error && + logs == other.logs && + value == other.value && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(authorization, error, logs, value, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash(authorization, error, logs, value, additionalProperties) + } override fun hashCode(): Int = hashCode @@ -1003,12 +1637,27 @@ private constructor( return true } - return /* spotless:off */ other is ToolExecutionAttempt && id == other.id && finishedAt == other.finishedAt && output == other.output && startedAt == other.startedAt && success == other.success && systemErrorMessage == other.systemErrorMessage && additionalProperties == other.additionalProperties /* spotless:on */ + return other is ToolExecutionAttempt && + id == other.id && + finishedAt == other.finishedAt && + output == other.output && + startedAt == other.startedAt && + success == other.success && + systemErrorMessage == other.systemErrorMessage && + additionalProperties == other.additionalProperties } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(id, finishedAt, output, startedAt, success, systemErrorMessage, additionalProperties) } - /* spotless:on */ + private val hashCode: Int by lazy { + Objects.hash( + id, + finishedAt, + output, + startedAt, + success, + systemErrorMessage, + additionalProperties, + ) + } override fun hashCode(): Int = hashCode diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolGetParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolGetParams.kt similarity index 78% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/ToolGetParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolGetParams.kt index 6f8acf2..f851a95 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolGetParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolGetParams.kt @@ -1,31 +1,30 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.tools import com.fasterxml.jackson.annotation.JsonCreator import dev.arcade.core.Enum import dev.arcade.core.JsonField -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params -import dev.arcade.core.checkRequired import dev.arcade.core.http.Headers import dev.arcade.core.http.QueryParams import dev.arcade.core.toImmutable import dev.arcade.errors.ArcadeInvalidDataException import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Returns the arcade tool specification for a specific tool */ class ToolGetParams private constructor( - private val name: String, + private val name: String?, private val includeFormat: List?, private val userId: String?, private val additionalHeaders: Headers, private val additionalQueryParams: QueryParams, ) : Params { - fun name(): String = name + fun name(): Optional = Optional.ofNullable(name) /** Comma separated tool formats that will be included in the response. */ fun includeFormat(): Optional> = Optional.ofNullable(includeFormat) @@ -33,38 +32,23 @@ private constructor( /** User ID */ fun userId(): Optional = Optional.ofNullable(userId) + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams { - val queryParams = QueryParams.builder() - this.includeFormat?.let { - queryParams.put("include_format", listOf(it.joinToString(separator = ","))) - } - this.userId?.let { queryParams.put("user_id", listOf(it.toString())) } - queryParams.putAll(additionalQueryParams) - return queryParams.build() - } - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> name - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): ToolGetParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [ToolGetParams]. */ @JvmStatic fun builder() = Builder() } /** A builder for [ToolGetParams]. */ - @NoAutoDetect class Builder internal constructor() { private var name: String? = null @@ -82,18 +66,25 @@ private constructor( additionalQueryParams = toolGetParams.additionalQueryParams.toBuilder() } - fun name(name: String) = apply { this.name = name } + fun name(name: String?) = apply { this.name = name } + + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) /** Comma separated tool formats that will be included in the response. */ fun includeFormat(includeFormat: List?) = apply { this.includeFormat = includeFormat?.toMutableList() } - /** Comma separated tool formats that will be included in the response. */ + /** Alias for calling [Builder.includeFormat] with `includeFormat.orElse(null)`. */ fun includeFormat(includeFormat: Optional>) = - includeFormat(includeFormat.orElse(null)) + includeFormat(includeFormat.getOrNull()) - /** Comma separated tool formats that will be included in the response. */ + /** + * Adds a single [IncludeFormat] to [Builder.includeFormat]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addIncludeFormat(includeFormat: IncludeFormat) = apply { this.includeFormat = (this.includeFormat ?: mutableListOf()).apply { add(includeFormat) } @@ -102,8 +93,8 @@ private constructor( /** User ID */ fun userId(userId: String?) = apply { this.userId = userId } - /** User ID */ - fun userId(userId: Optional) = userId(userId.orElse(null)) + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -203,9 +194,14 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [ToolGetParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): ToolGetParams = ToolGetParams( - checkRequired("name", name), + name, includeFormat?.toImmutable(), userId, additionalHeaders.build(), @@ -213,6 +209,23 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> name ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + includeFormat?.let { put("include_format", it.joinToString(",") { it.toString() }) } + userId?.let { put("user_id", it) } + putAll(additionalQueryParams) + } + .build() + class IncludeFormat @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -308,12 +321,39 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { ArcadeInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): IncludeFormat = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 /* spotless:off */ other is IncludeFormat && value == other.value /* spotless:on */ + return other is IncludeFormat && value == other.value } override fun hashCode() = value.hashCode() @@ -326,10 +366,16 @@ private constructor( return true } - return /* spotless:off */ other is ToolGetParams && name == other.name && includeFormat == other.includeFormat && userId == other.userId && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is ToolGetParams && + name == other.name && + includeFormat == other.includeFormat && + userId == other.userId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(name, includeFormat, userId, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(name, includeFormat, userId, additionalHeaders, additionalQueryParams) override fun toString() = "ToolGetParams{name=$name, includeFormat=$includeFormat, userId=$userId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolListPage.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolListPage.kt new file mode 100644 index 0000000..e75f593 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolListPage.kt @@ -0,0 +1,144 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.tools + +import dev.arcade.core.AutoPager +import dev.arcade.core.Page +import dev.arcade.core.checkRequired +import dev.arcade.services.blocking.ToolService +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrDefault +import kotlin.jvm.optionals.getOrNull + +/** @see ToolService.list */ +class ToolListPage +private constructor( + private val service: ToolService, + private val params: ToolListParams, + private val response: ToolListPageResponse, +) : Page { + + /** + * Delegates to [ToolListPageResponse], but gracefully handles missing data. + * + * @see ToolListPageResponse.items + */ + override fun items(): List = + response._items().getOptional("items").getOrNull() ?: emptyList() + + /** + * Delegates to [ToolListPageResponse], but gracefully handles missing data. + * + * @see ToolListPageResponse.totalCount + */ + fun totalCount(): Optional = response._totalCount().getOptional("total_count") + + /** + * Delegates to [ToolListPageResponse], but gracefully handles missing data. + * + * @see ToolListPageResponse.offset + */ + fun offset(): Optional = response._offset().getOptional("offset") + + override fun hasNextPage(): Boolean { + if (items().isEmpty()) { + return false + } + + val offset = offset().getOrDefault(0) + val totalCount = totalCount().getOrNull() + return totalCount == null || offset + items().size < totalCount + } + + fun nextPageParams(): ToolListParams { + val offset = offset().getOrDefault(0) + return params.toBuilder().offset(offset + items().size).build() + } + + override fun nextPage(): ToolListPage = service.list(nextPageParams()) + + fun autoPager(): AutoPager = AutoPager.from(this) + + /** The parameters that were used to request this page. */ + fun params(): ToolListParams = params + + /** The response that this page was parsed from. */ + fun response(): ToolListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ToolListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ToolListPage]. */ + class Builder internal constructor() { + + private var service: ToolService? = null + private var params: ToolListParams? = null + private var response: ToolListPageResponse? = null + + @JvmSynthetic + internal fun from(toolListPage: ToolListPage) = apply { + service = toolListPage.service + params = toolListPage.params + response = toolListPage.response + } + + fun service(service: ToolService) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: ToolListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: ToolListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [ToolListPage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ToolListPage = + ToolListPage( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ToolListPage && + service == other.service && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, params, response) + + override fun toString() = "ToolListPage{service=$service, params=$params, response=$response}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolListPageAsync.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolListPageAsync.kt new file mode 100644 index 0000000..7e03a5f --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolListPageAsync.kt @@ -0,0 +1,159 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.tools + +import dev.arcade.core.AutoPagerAsync +import dev.arcade.core.PageAsync +import dev.arcade.core.checkRequired +import dev.arcade.services.async.ToolServiceAsync +import java.util.Objects +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import kotlin.jvm.optionals.getOrDefault +import kotlin.jvm.optionals.getOrNull + +/** @see ToolServiceAsync.list */ +class ToolListPageAsync +private constructor( + private val service: ToolServiceAsync, + private val streamHandlerExecutor: Executor, + private val params: ToolListParams, + private val response: ToolListPageResponse, +) : PageAsync { + + /** + * Delegates to [ToolListPageResponse], but gracefully handles missing data. + * + * @see ToolListPageResponse.items + */ + override fun items(): List = + response._items().getOptional("items").getOrNull() ?: emptyList() + + /** + * Delegates to [ToolListPageResponse], but gracefully handles missing data. + * + * @see ToolListPageResponse.totalCount + */ + fun totalCount(): Optional = response._totalCount().getOptional("total_count") + + /** + * Delegates to [ToolListPageResponse], but gracefully handles missing data. + * + * @see ToolListPageResponse.offset + */ + fun offset(): Optional = response._offset().getOptional("offset") + + override fun hasNextPage(): Boolean { + if (items().isEmpty()) { + return false + } + + val offset = offset().getOrDefault(0) + val totalCount = totalCount().getOrNull() + return totalCount == null || offset + items().size < totalCount + } + + fun nextPageParams(): ToolListParams { + val offset = offset().getOrDefault(0) + return params.toBuilder().offset(offset + items().size).build() + } + + override fun nextPage(): CompletableFuture = service.list(nextPageParams()) + + fun autoPager(): AutoPagerAsync = + AutoPagerAsync.from(this, streamHandlerExecutor) + + /** The parameters that were used to request this page. */ + fun params(): ToolListParams = params + + /** The response that this page was parsed from. */ + fun response(): ToolListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ToolListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ToolListPageAsync]. */ + class Builder internal constructor() { + + private var service: ToolServiceAsync? = null + private var streamHandlerExecutor: Executor? = null + private var params: ToolListParams? = null + private var response: ToolListPageResponse? = null + + @JvmSynthetic + internal fun from(toolListPageAsync: ToolListPageAsync) = apply { + service = toolListPageAsync.service + streamHandlerExecutor = toolListPageAsync.streamHandlerExecutor + params = toolListPageAsync.params + response = toolListPageAsync.response + } + + fun service(service: ToolServiceAsync) = apply { this.service = service } + + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + this.streamHandlerExecutor = streamHandlerExecutor + } + + /** The parameters that were used to request this page. */ + fun params(params: ToolListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: ToolListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [ToolListPageAsync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ToolListPageAsync = + ToolListPageAsync( + checkRequired("service", service), + checkRequired("streamHandlerExecutor", streamHandlerExecutor), + checkRequired("params", params), + checkRequired("response", response), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ToolListPageAsync && + service == other.service && + streamHandlerExecutor == other.streamHandlerExecutor && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, streamHandlerExecutor, params, response) + + override fun toString() = + "ToolListPageAsync{service=$service, streamHandlerExecutor=$streamHandlerExecutor, params=$params, response=$response}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolListPageResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolListPageResponse.kt new file mode 100644 index 0000000..4910d9b --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolListPageResponse.kt @@ -0,0 +1,302 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.tools + +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 dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.core.checkKnown +import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class ToolListPageResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val items: JsonField>, + private val limit: JsonField, + private val offset: JsonField, + private val pageCount: JsonField, + private val totalCount: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("items") + @ExcludeMissing + items: JsonField> = JsonMissing.of(), + @JsonProperty("limit") @ExcludeMissing limit: JsonField = JsonMissing.of(), + @JsonProperty("offset") @ExcludeMissing offset: JsonField = JsonMissing.of(), + @JsonProperty("page_count") @ExcludeMissing pageCount: JsonField = JsonMissing.of(), + @JsonProperty("total_count") @ExcludeMissing totalCount: JsonField = JsonMissing.of(), + ) : this(items, limit, offset, pageCount, totalCount, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun items(): Optional> = items.getOptional("items") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun limit(): Optional = limit.getOptional("limit") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun offset(): Optional = offset.getOptional("offset") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun pageCount(): Optional = pageCount.getOptional("page_count") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun totalCount(): Optional = totalCount.getOptional("total_count") + + /** + * Returns the raw JSON value of [items]. + * + * Unlike [items], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("items") @ExcludeMissing fun _items(): JsonField> = items + + /** + * Returns the raw JSON value of [limit]. + * + * Unlike [limit], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("limit") @ExcludeMissing fun _limit(): JsonField = limit + + /** + * Returns the raw JSON value of [offset]. + * + * Unlike [offset], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("offset") @ExcludeMissing fun _offset(): JsonField = offset + + /** + * Returns the raw JSON value of [pageCount]. + * + * Unlike [pageCount], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("page_count") @ExcludeMissing fun _pageCount(): JsonField = pageCount + + /** + * Returns the raw JSON value of [totalCount]. + * + * Unlike [totalCount], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("total_count") @ExcludeMissing fun _totalCount(): JsonField = totalCount + + @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 [ToolListPageResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ToolListPageResponse]. */ + class Builder internal constructor() { + + private var items: JsonField>? = null + private var limit: JsonField = JsonMissing.of() + private var offset: JsonField = JsonMissing.of() + private var pageCount: JsonField = JsonMissing.of() + private var totalCount: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(toolListPageResponse: ToolListPageResponse) = apply { + items = toolListPageResponse.items.map { it.toMutableList() } + limit = toolListPageResponse.limit + offset = toolListPageResponse.offset + pageCount = toolListPageResponse.pageCount + totalCount = toolListPageResponse.totalCount + additionalProperties = toolListPageResponse.additionalProperties.toMutableMap() + } + + fun items(items: List) = items(JsonField.of(items)) + + /** + * Sets [Builder.items] to an arbitrary JSON value. + * + * You should usually call [Builder.items] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun items(items: JsonField>) = apply { + this.items = items.map { it.toMutableList() } + } + + /** + * Adds a single [ToolDefinition] to [items]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addItem(item: ToolDefinition) = apply { + items = + (items ?: JsonField.of(mutableListOf())).also { checkKnown("items", it).add(item) } + } + + fun limit(limit: Long) = limit(JsonField.of(limit)) + + /** + * Sets [Builder.limit] to an arbitrary JSON value. + * + * You should usually call [Builder.limit] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun limit(limit: JsonField) = apply { this.limit = limit } + + fun offset(offset: Long) = offset(JsonField.of(offset)) + + /** + * Sets [Builder.offset] to an arbitrary JSON value. + * + * You should usually call [Builder.offset] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun offset(offset: JsonField) = apply { this.offset = offset } + + fun pageCount(pageCount: Long) = pageCount(JsonField.of(pageCount)) + + /** + * Sets [Builder.pageCount] to an arbitrary JSON value. + * + * You should usually call [Builder.pageCount] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun pageCount(pageCount: JsonField) = apply { this.pageCount = pageCount } + + fun totalCount(totalCount: Long) = totalCount(JsonField.of(totalCount)) + + /** + * Sets [Builder.totalCount] to an arbitrary JSON value. + * + * You should usually call [Builder.totalCount] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun totalCount(totalCount: JsonField) = apply { this.totalCount = totalCount } + + 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 [ToolListPageResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ToolListPageResponse = + ToolListPageResponse( + (items ?: JsonMissing.of()).map { it.toImmutable() }, + limit, + offset, + pageCount, + totalCount, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ToolListPageResponse = apply { + if (validated) { + return@apply + } + + items().ifPresent { it.forEach { it.validate() } } + limit() + offset() + pageCount() + totalCount() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (items.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (limit.asKnown().isPresent) 1 else 0) + + (if (offset.asKnown().isPresent) 1 else 0) + + (if (pageCount.asKnown().isPresent) 1 else 0) + + (if (totalCount.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ToolListPageResponse && + items == other.items && + limit == other.limit && + offset == other.offset && + pageCount == other.pageCount && + totalCount == other.totalCount && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(items, limit, offset, pageCount, totalCount, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ToolListPageResponse{items=$items, limit=$limit, offset=$offset, pageCount=$pageCount, totalCount=$totalCount, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolListParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolListParams.kt similarity index 75% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/ToolListParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolListParams.kt index 788a274..f5c8025 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolListParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ToolListParams.kt @@ -1,11 +1,10 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.tools import com.fasterxml.jackson.annotation.JsonCreator import dev.arcade.core.Enum import dev.arcade.core.JsonField -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params import dev.arcade.core.http.Headers import dev.arcade.core.http.QueryParams @@ -13,6 +12,7 @@ import dev.arcade.core.toImmutable import dev.arcade.errors.ArcadeInvalidDataException import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Returns a page of tools from the engine configuration, optionally filtered by toolkit */ class ToolListParams @@ -45,37 +45,23 @@ private constructor( /** User ID */ fun userId(): Optional = Optional.ofNullable(userId) + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams { - val queryParams = QueryParams.builder() - this.includeAllVersions?.let { - queryParams.put("include_all_versions", listOf(it.toString())) - } - this.includeFormat?.let { - queryParams.put("include_format", listOf(it.joinToString(separator = ","))) - } - this.limit?.let { queryParams.put("limit", listOf(it.toString())) } - this.offset?.let { queryParams.put("offset", listOf(it.toString())) } - this.toolkit?.let { queryParams.put("toolkit", listOf(it.toString())) } - this.userId?.let { queryParams.put("user_id", listOf(it.toString())) } - queryParams.putAll(additionalQueryParams) - return queryParams.build() - } - fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): ToolListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [ToolListParams]. */ @JvmStatic fun builder() = Builder() } /** A builder for [ToolListParams]. */ - @NoAutoDetect class Builder internal constructor() { private var includeAllVersions: Boolean? = null @@ -104,25 +90,34 @@ private constructor( this.includeAllVersions = includeAllVersions } - /** Include all versions of each tool */ + /** + * Alias for [Builder.includeAllVersions]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun includeAllVersions(includeAllVersions: Boolean) = includeAllVersions(includeAllVersions as Boolean?) - /** Include all versions of each tool */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 + /** + * Alias for calling [Builder.includeAllVersions] with `includeAllVersions.orElse(null)`. + */ fun includeAllVersions(includeAllVersions: Optional) = - includeAllVersions(includeAllVersions.orElse(null) as Boolean?) + includeAllVersions(includeAllVersions.getOrNull()) /** Comma separated tool formats that will be included in the response. */ fun includeFormat(includeFormat: List?) = apply { this.includeFormat = includeFormat?.toMutableList() } - /** Comma separated tool formats that will be included in the response. */ + /** Alias for calling [Builder.includeFormat] with `includeFormat.orElse(null)`. */ fun includeFormat(includeFormat: Optional>) = - includeFormat(includeFormat.orElse(null)) + includeFormat(includeFormat.getOrNull()) - /** Comma separated tool formats that will be included in the response. */ + /** + * Adds a single [IncludeFormat] to [Builder.includeFormat]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addIncludeFormat(includeFormat: IncludeFormat) = apply { this.includeFormat = (this.includeFormat ?: mutableListOf()).apply { add(includeFormat) } @@ -131,34 +126,40 @@ private constructor( /** Number of items to return (default: 25, max: 100) */ fun limit(limit: Long?) = apply { this.limit = limit } - /** Number of items to return (default: 25, max: 100) */ + /** + * Alias for [Builder.limit]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun limit(limit: Long) = limit(limit as Long?) - /** Number of items to return (default: 25, max: 100) */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun limit(limit: Optional) = limit(limit.orElse(null) as Long?) + /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ + fun limit(limit: Optional) = limit(limit.getOrNull()) /** Offset from the start of the list (default: 0) */ fun offset(offset: Long?) = apply { this.offset = offset } - /** Offset from the start of the list (default: 0) */ + /** + * Alias for [Builder.offset]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun offset(offset: Long) = offset(offset as Long?) - /** Offset from the start of the list (default: 0) */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun offset(offset: Optional) = offset(offset.orElse(null) as Long?) + /** Alias for calling [Builder.offset] with `offset.orElse(null)`. */ + fun offset(offset: Optional) = offset(offset.getOrNull()) /** Toolkit name */ fun toolkit(toolkit: String?) = apply { this.toolkit = toolkit } - /** Toolkit name */ - fun toolkit(toolkit: Optional) = toolkit(toolkit.orElse(null)) + /** Alias for calling [Builder.toolkit] with `toolkit.orElse(null)`. */ + fun toolkit(toolkit: Optional) = toolkit(toolkit.getOrNull()) /** User ID */ fun userId(userId: String?) = apply { this.userId = userId } - /** User ID */ - fun userId(userId: Optional) = userId(userId.orElse(null)) + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -258,6 +259,11 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [ToolListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): ToolListParams = ToolListParams( includeAllVersions, @@ -271,6 +277,21 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + includeAllVersions?.let { put("include_all_versions", it.toString()) } + includeFormat?.let { put("include_format", it.joinToString(",") { it.toString() }) } + limit?.let { put("limit", it.toString()) } + offset?.let { put("offset", it.toString()) } + toolkit?.let { put("toolkit", it) } + userId?.let { put("user_id", it) } + putAll(additionalQueryParams) + } + .build() + class IncludeFormat @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -366,12 +387,39 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { ArcadeInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): IncludeFormat = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 /* spotless:off */ other is IncludeFormat && value == other.value /* spotless:on */ + return other is IncludeFormat && value == other.value } override fun hashCode() = value.hashCode() @@ -384,10 +432,28 @@ private constructor( return true } - return /* spotless:off */ other is ToolListParams && includeAllVersions == other.includeAllVersions && includeFormat == other.includeFormat && limit == other.limit && offset == other.offset && toolkit == other.toolkit && userId == other.userId && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is ToolListParams && + includeAllVersions == other.includeAllVersions && + includeFormat == other.includeFormat && + limit == other.limit && + offset == other.offset && + toolkit == other.toolkit && + userId == other.userId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(includeAllVersions, includeFormat, limit, offset, toolkit, userId, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash( + includeAllVersions, + includeFormat, + limit, + offset, + toolkit, + userId, + additionalHeaders, + additionalQueryParams, + ) override fun toString() = "ToolListParams{includeAllVersions=$includeAllVersions, includeFormat=$includeFormat, limit=$limit, offset=$offset, toolkit=$toolkit, userId=$userId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ValueSchema.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ValueSchema.kt new file mode 100644 index 0000000..06139a7 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/ValueSchema.kt @@ -0,0 +1,262 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.tools + +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 dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.core.checkKnown +import dev.arcade.core.checkRequired +import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class ValueSchema +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val valType: JsonField, + private val enum_: JsonField>, + private val innerValType: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("val_type") @ExcludeMissing valType: JsonField = JsonMissing.of(), + @JsonProperty("enum") @ExcludeMissing enum_: JsonField> = JsonMissing.of(), + @JsonProperty("inner_val_type") + @ExcludeMissing + innerValType: JsonField = JsonMissing.of(), + ) : this(valType, enum_, innerValType, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException 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 valType(): String = valType.getRequired("val_type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun enum_(): Optional> = enum_.getOptional("enum") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun innerValType(): Optional = innerValType.getOptional("inner_val_type") + + /** + * Returns the raw JSON value of [valType]. + * + * Unlike [valType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("val_type") @ExcludeMissing fun _valType(): JsonField = valType + + /** + * Returns the raw JSON value of [enum_]. + * + * Unlike [enum_], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("enum") @ExcludeMissing fun _enum_(): JsonField> = enum_ + + /** + * Returns the raw JSON value of [innerValType]. + * + * Unlike [innerValType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("inner_val_type") + @ExcludeMissing + fun _innerValType(): JsonField = innerValType + + @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 [ValueSchema]. + * + * The following fields are required: + * ```java + * .valType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ValueSchema]. */ + class Builder internal constructor() { + + private var valType: JsonField? = null + private var enum_: JsonField>? = null + private var innerValType: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(valueSchema: ValueSchema) = apply { + valType = valueSchema.valType + enum_ = valueSchema.enum_.map { it.toMutableList() } + innerValType = valueSchema.innerValType + additionalProperties = valueSchema.additionalProperties.toMutableMap() + } + + fun valType(valType: String) = valType(JsonField.of(valType)) + + /** + * Sets [Builder.valType] to an arbitrary JSON value. + * + * You should usually call [Builder.valType] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun valType(valType: JsonField) = apply { this.valType = valType } + + fun enum_(enum_: List) = enum_(JsonField.of(enum_)) + + /** + * Sets [Builder.enum_] to an arbitrary JSON value. + * + * You should usually call [Builder.enum_] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun enum_(enum_: JsonField>) = apply { + this.enum_ = enum_.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [Builder.enum_]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addEnum(enum_: String) = apply { + this.enum_ = + (this.enum_ ?: JsonField.of(mutableListOf())).also { + checkKnown("enum_", it).add(enum_) + } + } + + fun innerValType(innerValType: String) = innerValType(JsonField.of(innerValType)) + + /** + * Sets [Builder.innerValType] to an arbitrary JSON value. + * + * You should usually call [Builder.innerValType] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun innerValType(innerValType: JsonField) = apply { + this.innerValType = innerValType + } + + 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 [ValueSchema]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .valType() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ValueSchema = + ValueSchema( + checkRequired("valType", valType), + (enum_ ?: JsonMissing.of()).map { it.toImmutable() }, + innerValType, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ValueSchema = apply { + if (validated) { + return@apply + } + + valType() + enum_() + innerValType() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (valType.asKnown().isPresent) 1 else 0) + + (enum_.asKnown().getOrNull()?.size ?: 0) + + (if (innerValType.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ValueSchema && + valType == other.valType && + enum_ == other.enum_ && + innerValType == other.innerValType && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(valType, enum_, innerValType, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ValueSchema{valType=$valType, enum_=$enum_, innerValType=$innerValType, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolFormattedGetParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/formatted/FormattedGetParams.kt similarity index 68% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/ToolFormattedGetParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/tools/formatted/FormattedGetParams.kt index 8e89a4f..be7ee44 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolFormattedGetParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/formatted/FormattedGetParams.kt @@ -1,26 +1,25 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.tools.formatted -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params -import dev.arcade.core.checkRequired import dev.arcade.core.http.Headers import dev.arcade.core.http.QueryParams import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Returns the formatted tool specification for a specific tool, given a provider */ -class ToolFormattedGetParams +class FormattedGetParams private constructor( - private val name: String, + private val name: String?, private val format: String?, private val userId: String?, private val additionalHeaders: Headers, private val additionalQueryParams: QueryParams, ) : Params { - fun name(): String = name + fun name(): Optional = Optional.ofNullable(name) /** Provider format */ fun format(): Optional = Optional.ofNullable(format) @@ -28,36 +27,23 @@ private constructor( /** User ID */ fun userId(): Optional = Optional.ofNullable(userId) + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams { - val queryParams = QueryParams.builder() - this.format?.let { queryParams.put("format", listOf(it.toString())) } - this.userId?.let { queryParams.put("user_id", listOf(it.toString())) } - queryParams.putAll(additionalQueryParams) - return queryParams.build() - } - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> name - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): FormattedGetParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [FormattedGetParams]. */ @JvmStatic fun builder() = Builder() } - /** A builder for [ToolFormattedGetParams]. */ - @NoAutoDetect + /** A builder for [FormattedGetParams]. */ class Builder internal constructor() { private var name: String? = null @@ -67,27 +53,30 @@ private constructor( private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @JvmSynthetic - internal fun from(toolFormattedGetParams: ToolFormattedGetParams) = apply { - name = toolFormattedGetParams.name - format = toolFormattedGetParams.format - userId = toolFormattedGetParams.userId - additionalHeaders = toolFormattedGetParams.additionalHeaders.toBuilder() - additionalQueryParams = toolFormattedGetParams.additionalQueryParams.toBuilder() + internal fun from(formattedGetParams: FormattedGetParams) = apply { + name = formattedGetParams.name + format = formattedGetParams.format + userId = formattedGetParams.userId + additionalHeaders = formattedGetParams.additionalHeaders.toBuilder() + additionalQueryParams = formattedGetParams.additionalQueryParams.toBuilder() } - fun name(name: String) = apply { this.name = name } + fun name(name: String?) = apply { this.name = name } + + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) /** Provider format */ fun format(format: String?) = apply { this.format = format } - /** Provider format */ - fun format(format: Optional) = format(format.orElse(null)) + /** Alias for calling [Builder.format] with `format.orElse(null)`. */ + fun format(format: Optional) = format(format.getOrNull()) /** User ID */ fun userId(userId: String?) = apply { this.userId = userId } - /** User ID */ - fun userId(userId: Optional) = userId(userId.orElse(null)) + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -187,9 +176,14 @@ private constructor( additionalQueryParams.removeAll(keys) } - fun build(): ToolFormattedGetParams = - ToolFormattedGetParams( - checkRequired("name", name), + /** + * Returns an immutable instance of [FormattedGetParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): FormattedGetParams = + FormattedGetParams( + name, format, userId, additionalHeaders.build(), @@ -197,16 +191,39 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> name ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + format?.let { put("format", it) } + userId?.let { put("user_id", it) } + putAll(additionalQueryParams) + } + .build() + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is ToolFormattedGetParams && name == other.name && format == other.format && userId == other.userId && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is FormattedGetParams && + name == other.name && + format == other.format && + userId == other.userId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(name, format, userId, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(name, format, userId, additionalHeaders, additionalQueryParams) override fun toString() = - "ToolFormattedGetParams{name=$name, format=$format, userId=$userId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" + "FormattedGetParams{name=$name, format=$format, userId=$userId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolFormattedGetResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/formatted/FormattedGetResponse.kt similarity index 54% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/ToolFormattedGetResponse.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/tools/formatted/FormattedGetResponse.kt index c79308d..3ebb65e 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolFormattedGetResponse.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/formatted/FormattedGetResponse.kt @@ -1,53 +1,42 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.tools.formatted import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator import dev.arcade.core.ExcludeMissing import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException import java.util.Objects -@NoAutoDetect -class ToolFormattedGetResponse +class FormattedGetResponse @JsonCreator private constructor( - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): ToolFormattedGetResponse = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [FormattedGetResponse]. */ @JvmStatic fun builder() = Builder() } - /** A builder for [ToolFormattedGetResponse]. */ + /** A builder for [FormattedGetResponse]. */ class Builder internal constructor() { private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic - internal fun from(toolFormattedGetResponse: ToolFormattedGetResponse) = apply { - additionalProperties = toolFormattedGetResponse.additionalProperties.toMutableMap() + internal fun from(formattedGetResponse: FormattedGetResponse) = apply { + additionalProperties = formattedGetResponse.additionalProperties.toMutableMap() } fun additionalProperties(additionalProperties: Map) = apply { @@ -69,23 +58,52 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): ToolFormattedGetResponse = - ToolFormattedGetResponse(additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [FormattedGetResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): FormattedGetResponse = FormattedGetResponse(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): FormattedGetResponse = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 /* spotless:off */ other is ToolFormattedGetResponse && additionalProperties == other.additionalProperties /* spotless:on */ + return other is FormattedGetResponse && additionalProperties == other.additionalProperties } - /* spotless:off */ private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ override fun hashCode(): Int = hashCode - override fun toString() = "ToolFormattedGetResponse{additionalProperties=$additionalProperties}" + override fun toString() = "FormattedGetResponse{additionalProperties=$additionalProperties}" } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/formatted/FormattedListPage.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/formatted/FormattedListPage.kt new file mode 100644 index 0000000..06c1bed --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/formatted/FormattedListPage.kt @@ -0,0 +1,145 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.tools.formatted + +import dev.arcade.core.AutoPager +import dev.arcade.core.Page +import dev.arcade.core.checkRequired +import dev.arcade.services.blocking.tools.FormattedService +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrDefault +import kotlin.jvm.optionals.getOrNull + +/** @see FormattedService.list */ +class FormattedListPage +private constructor( + private val service: FormattedService, + private val params: FormattedListParams, + private val response: FormattedListPageResponse, +) : Page { + + /** + * Delegates to [FormattedListPageResponse], but gracefully handles missing data. + * + * @see FormattedListPageResponse.items + */ + override fun items(): List = + response._items().getOptional("items").getOrNull() ?: emptyList() + + /** + * Delegates to [FormattedListPageResponse], but gracefully handles missing data. + * + * @see FormattedListPageResponse.totalCount + */ + fun totalCount(): Optional = response._totalCount().getOptional("total_count") + + /** + * Delegates to [FormattedListPageResponse], but gracefully handles missing data. + * + * @see FormattedListPageResponse.offset + */ + fun offset(): Optional = response._offset().getOptional("offset") + + override fun hasNextPage(): Boolean { + if (items().isEmpty()) { + return false + } + + val offset = offset().getOrDefault(0) + val totalCount = totalCount().getOrNull() + return totalCount == null || offset + items().size < totalCount + } + + fun nextPageParams(): FormattedListParams { + val offset = offset().getOrDefault(0) + return params.toBuilder().offset(offset + items().size).build() + } + + override fun nextPage(): FormattedListPage = service.list(nextPageParams()) + + fun autoPager(): AutoPager = AutoPager.from(this) + + /** The parameters that were used to request this page. */ + fun params(): FormattedListParams = params + + /** The response that this page was parsed from. */ + fun response(): FormattedListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [FormattedListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FormattedListPage]. */ + class Builder internal constructor() { + + private var service: FormattedService? = null + private var params: FormattedListParams? = null + private var response: FormattedListPageResponse? = null + + @JvmSynthetic + internal fun from(formattedListPage: FormattedListPage) = apply { + service = formattedListPage.service + params = formattedListPage.params + response = formattedListPage.response + } + + fun service(service: FormattedService) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: FormattedListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: FormattedListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [FormattedListPage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): FormattedListPage = + FormattedListPage( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FormattedListPage && + service == other.service && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, params, response) + + override fun toString() = + "FormattedListPage{service=$service, params=$params, response=$response}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/formatted/FormattedListPageAsync.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/formatted/FormattedListPageAsync.kt new file mode 100644 index 0000000..73fa09e --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/formatted/FormattedListPageAsync.kt @@ -0,0 +1,160 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.tools.formatted + +import dev.arcade.core.AutoPagerAsync +import dev.arcade.core.PageAsync +import dev.arcade.core.checkRequired +import dev.arcade.services.async.tools.FormattedServiceAsync +import java.util.Objects +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import kotlin.jvm.optionals.getOrDefault +import kotlin.jvm.optionals.getOrNull + +/** @see FormattedServiceAsync.list */ +class FormattedListPageAsync +private constructor( + private val service: FormattedServiceAsync, + private val streamHandlerExecutor: Executor, + private val params: FormattedListParams, + private val response: FormattedListPageResponse, +) : PageAsync { + + /** + * Delegates to [FormattedListPageResponse], but gracefully handles missing data. + * + * @see FormattedListPageResponse.items + */ + override fun items(): List = + response._items().getOptional("items").getOrNull() ?: emptyList() + + /** + * Delegates to [FormattedListPageResponse], but gracefully handles missing data. + * + * @see FormattedListPageResponse.totalCount + */ + fun totalCount(): Optional = response._totalCount().getOptional("total_count") + + /** + * Delegates to [FormattedListPageResponse], but gracefully handles missing data. + * + * @see FormattedListPageResponse.offset + */ + fun offset(): Optional = response._offset().getOptional("offset") + + override fun hasNextPage(): Boolean { + if (items().isEmpty()) { + return false + } + + val offset = offset().getOrDefault(0) + val totalCount = totalCount().getOrNull() + return totalCount == null || offset + items().size < totalCount + } + + fun nextPageParams(): FormattedListParams { + val offset = offset().getOrDefault(0) + return params.toBuilder().offset(offset + items().size).build() + } + + override fun nextPage(): CompletableFuture = + service.list(nextPageParams()) + + fun autoPager(): AutoPagerAsync = + AutoPagerAsync.from(this, streamHandlerExecutor) + + /** The parameters that were used to request this page. */ + fun params(): FormattedListParams = params + + /** The response that this page was parsed from. */ + fun response(): FormattedListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [FormattedListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FormattedListPageAsync]. */ + class Builder internal constructor() { + + private var service: FormattedServiceAsync? = null + private var streamHandlerExecutor: Executor? = null + private var params: FormattedListParams? = null + private var response: FormattedListPageResponse? = null + + @JvmSynthetic + internal fun from(formattedListPageAsync: FormattedListPageAsync) = apply { + service = formattedListPageAsync.service + streamHandlerExecutor = formattedListPageAsync.streamHandlerExecutor + params = formattedListPageAsync.params + response = formattedListPageAsync.response + } + + fun service(service: FormattedServiceAsync) = apply { this.service = service } + + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + this.streamHandlerExecutor = streamHandlerExecutor + } + + /** The parameters that were used to request this page. */ + fun params(params: FormattedListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: FormattedListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [FormattedListPageAsync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): FormattedListPageAsync = + FormattedListPageAsync( + checkRequired("service", service), + checkRequired("streamHandlerExecutor", streamHandlerExecutor), + checkRequired("params", params), + checkRequired("response", response), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FormattedListPageAsync && + service == other.service && + streamHandlerExecutor == other.streamHandlerExecutor && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, streamHandlerExecutor, params, response) + + override fun toString() = + "FormattedListPageAsync{service=$service, streamHandlerExecutor=$streamHandlerExecutor, params=$params, response=$response}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/formatted/FormattedListPageResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/formatted/FormattedListPageResponse.kt new file mode 100644 index 0000000..0d6c9cb --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/formatted/FormattedListPageResponse.kt @@ -0,0 +1,306 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.tools.formatted + +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 dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.core.checkKnown +import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class FormattedListPageResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val items: JsonField>, + private val limit: JsonField, + private val offset: JsonField, + private val pageCount: JsonField, + private val totalCount: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("items") + @ExcludeMissing + items: JsonField> = JsonMissing.of(), + @JsonProperty("limit") @ExcludeMissing limit: JsonField = JsonMissing.of(), + @JsonProperty("offset") @ExcludeMissing offset: JsonField = JsonMissing.of(), + @JsonProperty("page_count") @ExcludeMissing pageCount: JsonField = JsonMissing.of(), + @JsonProperty("total_count") @ExcludeMissing totalCount: JsonField = JsonMissing.of(), + ) : this(items, limit, offset, pageCount, totalCount, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun items(): Optional> = items.getOptional("items") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun limit(): Optional = limit.getOptional("limit") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun offset(): Optional = offset.getOptional("offset") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun pageCount(): Optional = pageCount.getOptional("page_count") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun totalCount(): Optional = totalCount.getOptional("total_count") + + /** + * Returns the raw JSON value of [items]. + * + * Unlike [items], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("items") + @ExcludeMissing + fun _items(): JsonField> = items + + /** + * Returns the raw JSON value of [limit]. + * + * Unlike [limit], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("limit") @ExcludeMissing fun _limit(): JsonField = limit + + /** + * Returns the raw JSON value of [offset]. + * + * Unlike [offset], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("offset") @ExcludeMissing fun _offset(): JsonField = offset + + /** + * Returns the raw JSON value of [pageCount]. + * + * Unlike [pageCount], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("page_count") @ExcludeMissing fun _pageCount(): JsonField = pageCount + + /** + * Returns the raw JSON value of [totalCount]. + * + * Unlike [totalCount], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("total_count") @ExcludeMissing fun _totalCount(): JsonField = totalCount + + @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 [FormattedListPageResponse]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FormattedListPageResponse]. */ + class Builder internal constructor() { + + private var items: JsonField>? = null + private var limit: JsonField = JsonMissing.of() + private var offset: JsonField = JsonMissing.of() + private var pageCount: JsonField = JsonMissing.of() + private var totalCount: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(formattedListPageResponse: FormattedListPageResponse) = apply { + items = formattedListPageResponse.items.map { it.toMutableList() } + limit = formattedListPageResponse.limit + offset = formattedListPageResponse.offset + pageCount = formattedListPageResponse.pageCount + totalCount = formattedListPageResponse.totalCount + additionalProperties = formattedListPageResponse.additionalProperties.toMutableMap() + } + + fun items(items: List) = items(JsonField.of(items)) + + /** + * Sets [Builder.items] to an arbitrary JSON value. + * + * You should usually call [Builder.items] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun items(items: JsonField>) = apply { + this.items = items.map { it.toMutableList() } + } + + /** + * Adds a single [FormattedListResponse] to [items]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addItem(item: FormattedListResponse) = apply { + items = + (items ?: JsonField.of(mutableListOf())).also { checkKnown("items", it).add(item) } + } + + fun limit(limit: Long) = limit(JsonField.of(limit)) + + /** + * Sets [Builder.limit] to an arbitrary JSON value. + * + * You should usually call [Builder.limit] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun limit(limit: JsonField) = apply { this.limit = limit } + + fun offset(offset: Long) = offset(JsonField.of(offset)) + + /** + * Sets [Builder.offset] to an arbitrary JSON value. + * + * You should usually call [Builder.offset] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun offset(offset: JsonField) = apply { this.offset = offset } + + fun pageCount(pageCount: Long) = pageCount(JsonField.of(pageCount)) + + /** + * Sets [Builder.pageCount] to an arbitrary JSON value. + * + * You should usually call [Builder.pageCount] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun pageCount(pageCount: JsonField) = apply { this.pageCount = pageCount } + + fun totalCount(totalCount: Long) = totalCount(JsonField.of(totalCount)) + + /** + * Sets [Builder.totalCount] to an arbitrary JSON value. + * + * You should usually call [Builder.totalCount] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun totalCount(totalCount: JsonField) = apply { this.totalCount = totalCount } + + 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 [FormattedListPageResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): FormattedListPageResponse = + FormattedListPageResponse( + (items ?: JsonMissing.of()).map { it.toImmutable() }, + limit, + offset, + pageCount, + totalCount, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): FormattedListPageResponse = apply { + if (validated) { + return@apply + } + + items().ifPresent { it.forEach { it.validate() } } + limit() + offset() + pageCount() + totalCount() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (items.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (limit.asKnown().isPresent) 1 else 0) + + (if (offset.asKnown().isPresent) 1 else 0) + + (if (pageCount.asKnown().isPresent) 1 else 0) + + (if (totalCount.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FormattedListPageResponse && + items == other.items && + limit == other.limit && + offset == other.offset && + pageCount == other.pageCount && + totalCount == other.totalCount && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(items, limit, offset, pageCount, totalCount, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "FormattedListPageResponse{items=$items, limit=$limit, offset=$offset, pageCount=$pageCount, totalCount=$totalCount, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolFormattedListParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/formatted/FormattedListParams.kt similarity index 64% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/ToolFormattedListParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/tools/formatted/FormattedListParams.kt index a9daf3b..3112f34 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolFormattedListParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/formatted/FormattedListParams.kt @@ -1,19 +1,19 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.tools.formatted -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params import dev.arcade.core.http.Headers import dev.arcade.core.http.QueryParams import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** * Returns a page of tools from the engine configuration, optionally filtered by toolkit, formatted * for a specific provider */ -class ToolFormattedListParams +class FormattedListParams private constructor( private val format: String?, private val includeAllVersions: Boolean?, @@ -43,35 +43,23 @@ private constructor( /** User ID */ fun userId(): Optional = Optional.ofNullable(userId) + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams { - val queryParams = QueryParams.builder() - this.format?.let { queryParams.put("format", listOf(it.toString())) } - this.includeAllVersions?.let { - queryParams.put("include_all_versions", listOf(it.toString())) - } - this.limit?.let { queryParams.put("limit", listOf(it.toString())) } - this.offset?.let { queryParams.put("offset", listOf(it.toString())) } - this.toolkit?.let { queryParams.put("toolkit", listOf(it.toString())) } - this.userId?.let { queryParams.put("user_id", listOf(it.toString())) } - queryParams.putAll(additionalQueryParams) - return queryParams.build() - } - fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): FormattedListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [FormattedListParams]. */ @JvmStatic fun builder() = Builder() } - /** A builder for [ToolFormattedListParams]. */ - @NoAutoDetect + /** A builder for [FormattedListParams]. */ class Builder internal constructor() { private var format: String? = null @@ -84,68 +72,79 @@ private constructor( private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @JvmSynthetic - internal fun from(toolFormattedListParams: ToolFormattedListParams) = apply { - format = toolFormattedListParams.format - includeAllVersions = toolFormattedListParams.includeAllVersions - limit = toolFormattedListParams.limit - offset = toolFormattedListParams.offset - toolkit = toolFormattedListParams.toolkit - userId = toolFormattedListParams.userId - additionalHeaders = toolFormattedListParams.additionalHeaders.toBuilder() - additionalQueryParams = toolFormattedListParams.additionalQueryParams.toBuilder() + internal fun from(formattedListParams: FormattedListParams) = apply { + format = formattedListParams.format + includeAllVersions = formattedListParams.includeAllVersions + limit = formattedListParams.limit + offset = formattedListParams.offset + toolkit = formattedListParams.toolkit + userId = formattedListParams.userId + additionalHeaders = formattedListParams.additionalHeaders.toBuilder() + additionalQueryParams = formattedListParams.additionalQueryParams.toBuilder() } /** Provider format */ fun format(format: String?) = apply { this.format = format } - /** Provider format */ - fun format(format: Optional) = format(format.orElse(null)) + /** Alias for calling [Builder.format] with `format.orElse(null)`. */ + fun format(format: Optional) = format(format.getOrNull()) /** Include all versions of each tool */ fun includeAllVersions(includeAllVersions: Boolean?) = apply { this.includeAllVersions = includeAllVersions } - /** Include all versions of each tool */ + /** + * Alias for [Builder.includeAllVersions]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun includeAllVersions(includeAllVersions: Boolean) = includeAllVersions(includeAllVersions as Boolean?) - /** Include all versions of each tool */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 + /** + * Alias for calling [Builder.includeAllVersions] with `includeAllVersions.orElse(null)`. + */ fun includeAllVersions(includeAllVersions: Optional) = - includeAllVersions(includeAllVersions.orElse(null) as Boolean?) + includeAllVersions(includeAllVersions.getOrNull()) /** Number of items to return (default: 25, max: 100) */ fun limit(limit: Long?) = apply { this.limit = limit } - /** Number of items to return (default: 25, max: 100) */ + /** + * Alias for [Builder.limit]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun limit(limit: Long) = limit(limit as Long?) - /** Number of items to return (default: 25, max: 100) */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun limit(limit: Optional) = limit(limit.orElse(null) as Long?) + /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ + fun limit(limit: Optional) = limit(limit.getOrNull()) /** Offset from the start of the list (default: 0) */ fun offset(offset: Long?) = apply { this.offset = offset } - /** Offset from the start of the list (default: 0) */ + /** + * Alias for [Builder.offset]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun offset(offset: Long) = offset(offset as Long?) - /** Offset from the start of the list (default: 0) */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun offset(offset: Optional) = offset(offset.orElse(null) as Long?) + /** Alias for calling [Builder.offset] with `offset.orElse(null)`. */ + fun offset(offset: Optional) = offset(offset.getOrNull()) /** Toolkit name */ fun toolkit(toolkit: String?) = apply { this.toolkit = toolkit } - /** Toolkit name */ - fun toolkit(toolkit: Optional) = toolkit(toolkit.orElse(null)) + /** Alias for calling [Builder.toolkit] with `toolkit.orElse(null)`. */ + fun toolkit(toolkit: Optional) = toolkit(toolkit.getOrNull()) /** User ID */ fun userId(userId: String?) = apply { this.userId = userId } - /** User ID */ - fun userId(userId: Optional) = userId(userId.orElse(null)) + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -245,8 +244,13 @@ private constructor( additionalQueryParams.removeAll(keys) } - fun build(): ToolFormattedListParams = - ToolFormattedListParams( + /** + * Returns an immutable instance of [FormattedListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): FormattedListParams = + FormattedListParams( format, includeAllVersions, limit, @@ -258,16 +262,49 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + format?.let { put("format", it) } + includeAllVersions?.let { put("include_all_versions", it.toString()) } + limit?.let { put("limit", it.toString()) } + offset?.let { put("offset", it.toString()) } + toolkit?.let { put("toolkit", it) } + userId?.let { put("user_id", it) } + putAll(additionalQueryParams) + } + .build() + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is ToolFormattedListParams && format == other.format && includeAllVersions == other.includeAllVersions && limit == other.limit && offset == other.offset && toolkit == other.toolkit && userId == other.userId && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is FormattedListParams && + format == other.format && + includeAllVersions == other.includeAllVersions && + limit == other.limit && + offset == other.offset && + toolkit == other.toolkit && + userId == other.userId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(format, includeAllVersions, limit, offset, toolkit, userId, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash( + format, + includeAllVersions, + limit, + offset, + toolkit, + userId, + additionalHeaders, + additionalQueryParams, + ) override fun toString() = - "ToolFormattedListParams{format=$format, includeAllVersions=$includeAllVersions, limit=$limit, offset=$offset, toolkit=$toolkit, userId=$userId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" + "FormattedListParams{format=$format, includeAllVersions=$includeAllVersions, limit=$limit, offset=$offset, toolkit=$toolkit, userId=$userId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolFormattedListResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/formatted/FormattedListResponse.kt similarity index 54% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/ToolFormattedListResponse.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/tools/formatted/FormattedListResponse.kt index 9a620b2..c2c3672 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolFormattedListResponse.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/formatted/FormattedListResponse.kt @@ -1,53 +1,42 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.tools.formatted import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator import dev.arcade.core.ExcludeMissing import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect -import dev.arcade.core.immutableEmptyMap import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException import java.util.Objects -@NoAutoDetect -class ToolFormattedListResponse +class FormattedListResponse @JsonCreator private constructor( - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): ToolFormattedListResponse = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [FormattedListResponse]. */ @JvmStatic fun builder() = Builder() } - /** A builder for [ToolFormattedListResponse]. */ + /** A builder for [FormattedListResponse]. */ class Builder internal constructor() { private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic - internal fun from(toolFormattedListResponse: ToolFormattedListResponse) = apply { - additionalProperties = toolFormattedListResponse.additionalProperties.toMutableMap() + internal fun from(formattedListResponse: FormattedListResponse) = apply { + additionalProperties = formattedListResponse.additionalProperties.toMutableMap() } fun additionalProperties(additionalProperties: Map) = apply { @@ -69,24 +58,53 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): ToolFormattedListResponse = - ToolFormattedListResponse(additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [FormattedListResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): FormattedListResponse = + FormattedListResponse(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): FormattedListResponse = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 /* spotless:off */ other is ToolFormattedListResponse && additionalProperties == other.additionalProperties /* spotless:on */ + return other is FormattedListResponse && additionalProperties == other.additionalProperties } - /* spotless:off */ private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - /* spotless:on */ override fun hashCode(): Int = hashCode - override fun toString() = - "ToolFormattedListResponse{additionalProperties=$additionalProperties}" + override fun toString() = "FormattedListResponse{additionalProperties=$additionalProperties}" } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolScheduledGetParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/scheduled/ScheduledGetParams.kt similarity index 73% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/ToolScheduledGetParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/tools/scheduled/ScheduledGetParams.kt index aeb0299..e1202e2 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolScheduledGetParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/scheduled/ScheduledGetParams.kt @@ -1,48 +1,41 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.tools.scheduled -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params -import dev.arcade.core.checkRequired import dev.arcade.core.http.Headers import dev.arcade.core.http.QueryParams import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Returns the details for a specific scheduled tool execution */ -class ToolScheduledGetParams +class ScheduledGetParams private constructor( - private val id: String, + private val id: String?, private val additionalHeaders: Headers, private val additionalQueryParams: QueryParams, ) : Params { - fun id(): String = id + 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 - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> id - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): ScheduledGetParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [ScheduledGetParams]. */ @JvmStatic fun builder() = Builder() } - /** A builder for [ToolScheduledGetParams]. */ - @NoAutoDetect + /** A builder for [ScheduledGetParams]. */ class Builder internal constructor() { private var id: String? = null @@ -50,13 +43,16 @@ private constructor( private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @JvmSynthetic - internal fun from(toolScheduledGetParams: ToolScheduledGetParams) = apply { - id = toolScheduledGetParams.id - additionalHeaders = toolScheduledGetParams.additionalHeaders.toBuilder() - additionalQueryParams = toolScheduledGetParams.additionalQueryParams.toBuilder() + internal fun from(scheduledGetParams: ScheduledGetParams) = apply { + id = scheduledGetParams.id + additionalHeaders = scheduledGetParams.additionalHeaders.toBuilder() + additionalQueryParams = scheduledGetParams.additionalQueryParams.toBuilder() } - fun id(id: String) = apply { this.id = id } + 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() @@ -156,24 +152,38 @@ private constructor( additionalQueryParams.removeAll(keys) } - fun build(): ToolScheduledGetParams = - ToolScheduledGetParams( - checkRequired("id", id), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + /** + * Returns an immutable instance of [ScheduledGetParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ScheduledGetParams = + ScheduledGetParams(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 /* spotless:off */ other is ToolScheduledGetParams && id == other.id && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is ScheduledGetParams && + id == other.id && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(id, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(id, additionalHeaders, additionalQueryParams) override fun toString() = - "ToolScheduledGetParams{id=$id, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" + "ScheduledGetParams{id=$id, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/scheduled/ScheduledGetResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/scheduled/ScheduledGetResponse.kt new file mode 100644 index 0000000..b8b575d --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/scheduled/ScheduledGetResponse.kt @@ -0,0 +1,750 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.tools.scheduled + +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 dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.core.checkKnown +import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import dev.arcade.models.tools.ToolExecutionAttempt +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class ScheduledGetResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val id: JsonField, + private val attempts: JsonField>, + private val createdAt: JsonField, + private val executionStatus: JsonField, + private val executionType: JsonField, + private val finishedAt: JsonField, + private val input: JsonField, + private val runAt: JsonField, + private val startedAt: JsonField, + private val toolName: JsonField, + private val toolkitName: JsonField, + private val toolkitVersion: JsonField, + private val updatedAt: JsonField, + private val userId: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("attempts") + @ExcludeMissing + attempts: JsonField> = JsonMissing.of(), + @JsonProperty("created_at") @ExcludeMissing createdAt: JsonField = JsonMissing.of(), + @JsonProperty("execution_status") + @ExcludeMissing + executionStatus: JsonField = JsonMissing.of(), + @JsonProperty("execution_type") + @ExcludeMissing + executionType: JsonField = JsonMissing.of(), + @JsonProperty("finished_at") + @ExcludeMissing + finishedAt: JsonField = JsonMissing.of(), + @JsonProperty("input") @ExcludeMissing input: JsonField = JsonMissing.of(), + @JsonProperty("run_at") @ExcludeMissing runAt: JsonField = JsonMissing.of(), + @JsonProperty("started_at") @ExcludeMissing startedAt: JsonField = JsonMissing.of(), + @JsonProperty("tool_name") @ExcludeMissing toolName: JsonField = JsonMissing.of(), + @JsonProperty("toolkit_name") + @ExcludeMissing + toolkitName: JsonField = JsonMissing.of(), + @JsonProperty("toolkit_version") + @ExcludeMissing + toolkitVersion: JsonField = JsonMissing.of(), + @JsonProperty("updated_at") @ExcludeMissing updatedAt: JsonField = JsonMissing.of(), + @JsonProperty("user_id") @ExcludeMissing userId: JsonField = JsonMissing.of(), + ) : this( + id, + attempts, + createdAt, + executionStatus, + executionType, + finishedAt, + input, + runAt, + startedAt, + toolName, + toolkitName, + toolkitVersion, + updatedAt, + userId, + mutableMapOf(), + ) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun attempts(): Optional> = attempts.getOptional("attempts") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun createdAt(): Optional = createdAt.getOptional("created_at") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun executionStatus(): Optional = executionStatus.getOptional("execution_status") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun executionType(): Optional = executionType.getOptional("execution_type") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun finishedAt(): Optional = finishedAt.getOptional("finished_at") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun input(): Optional = input.getOptional("input") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun runAt(): Optional = runAt.getOptional("run_at") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun startedAt(): Optional = startedAt.getOptional("started_at") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun toolName(): Optional = toolName.getOptional("tool_name") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun toolkitName(): Optional = toolkitName.getOptional("toolkit_name") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun toolkitVersion(): Optional = toolkitVersion.getOptional("toolkit_version") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun updatedAt(): Optional = updatedAt.getOptional("updated_at") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun userId(): Optional = userId.getOptional("user_id") + + /** + * 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 [attempts]. + * + * Unlike [attempts], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("attempts") + @ExcludeMissing + fun _attempts(): JsonField> = attempts + + /** + * 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 [executionStatus]. + * + * Unlike [executionStatus], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("execution_status") + @ExcludeMissing + fun _executionStatus(): JsonField = executionStatus + + /** + * Returns the raw JSON value of [executionType]. + * + * Unlike [executionType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("execution_type") + @ExcludeMissing + fun _executionType(): JsonField = executionType + + /** + * Returns the raw JSON value of [finishedAt]. + * + * Unlike [finishedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("finished_at") @ExcludeMissing fun _finishedAt(): JsonField = finishedAt + + /** + * 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 [runAt]. + * + * Unlike [runAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("run_at") @ExcludeMissing fun _runAt(): JsonField = runAt + + /** + * Returns the raw JSON value of [startedAt]. + * + * Unlike [startedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("started_at") @ExcludeMissing fun _startedAt(): JsonField = startedAt + + /** + * Returns the raw JSON value of [toolName]. + * + * Unlike [toolName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tool_name") @ExcludeMissing fun _toolName(): JsonField = toolName + + /** + * Returns the raw JSON value of [toolkitName]. + * + * Unlike [toolkitName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("toolkit_name") + @ExcludeMissing + fun _toolkitName(): JsonField = toolkitName + + /** + * Returns the raw JSON value of [toolkitVersion]. + * + * Unlike [toolkitVersion], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("toolkit_version") + @ExcludeMissing + fun _toolkitVersion(): JsonField = toolkitVersion + + /** + * Returns the raw JSON value of [updatedAt]. + * + * Unlike [updatedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("updated_at") @ExcludeMissing fun _updatedAt(): JsonField = updatedAt + + /** + * Returns the raw JSON value of [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + + @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 [ScheduledGetResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ScheduledGetResponse]. */ + class Builder internal constructor() { + + private var id: JsonField = JsonMissing.of() + private var attempts: JsonField>? = null + private var createdAt: JsonField = JsonMissing.of() + private var executionStatus: JsonField = JsonMissing.of() + private var executionType: JsonField = JsonMissing.of() + private var finishedAt: JsonField = JsonMissing.of() + private var input: JsonField = JsonMissing.of() + private var runAt: JsonField = JsonMissing.of() + private var startedAt: JsonField = JsonMissing.of() + private var toolName: JsonField = JsonMissing.of() + private var toolkitName: JsonField = JsonMissing.of() + private var toolkitVersion: JsonField = JsonMissing.of() + private var updatedAt: JsonField = JsonMissing.of() + private var userId: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(scheduledGetResponse: ScheduledGetResponse) = apply { + id = scheduledGetResponse.id + attempts = scheduledGetResponse.attempts.map { it.toMutableList() } + createdAt = scheduledGetResponse.createdAt + executionStatus = scheduledGetResponse.executionStatus + executionType = scheduledGetResponse.executionType + finishedAt = scheduledGetResponse.finishedAt + input = scheduledGetResponse.input + runAt = scheduledGetResponse.runAt + startedAt = scheduledGetResponse.startedAt + toolName = scheduledGetResponse.toolName + toolkitName = scheduledGetResponse.toolkitName + toolkitVersion = scheduledGetResponse.toolkitVersion + updatedAt = scheduledGetResponse.updatedAt + userId = scheduledGetResponse.userId + additionalProperties = scheduledGetResponse.additionalProperties.toMutableMap() + } + + 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 attempts(attempts: List) = attempts(JsonField.of(attempts)) + + /** + * Sets [Builder.attempts] to an arbitrary JSON value. + * + * You should usually call [Builder.attempts] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun attempts(attempts: JsonField>) = apply { + this.attempts = attempts.map { it.toMutableList() } + } + + /** + * Adds a single [ToolExecutionAttempt] to [attempts]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAttempt(attempt: ToolExecutionAttempt) = apply { + attempts = + (attempts ?: JsonField.of(mutableListOf())).also { + checkKnown("attempts", it).add(attempt) + } + } + + fun createdAt(createdAt: String) = createdAt(JsonField.of(createdAt)) + + /** + * Sets [Builder.createdAt] to an arbitrary JSON value. + * + * You should usually call [Builder.createdAt] with a well-typed [String] 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 executionStatus(executionStatus: String) = + executionStatus(JsonField.of(executionStatus)) + + /** + * Sets [Builder.executionStatus] to an arbitrary JSON value. + * + * You should usually call [Builder.executionStatus] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun executionStatus(executionStatus: JsonField) = apply { + this.executionStatus = executionStatus + } + + fun executionType(executionType: String) = executionType(JsonField.of(executionType)) + + /** + * Sets [Builder.executionType] to an arbitrary JSON value. + * + * You should usually call [Builder.executionType] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun executionType(executionType: JsonField) = apply { + this.executionType = executionType + } + + fun finishedAt(finishedAt: String) = finishedAt(JsonField.of(finishedAt)) + + /** + * Sets [Builder.finishedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.finishedAt] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun finishedAt(finishedAt: JsonField) = apply { this.finishedAt = finishedAt } + + fun input(input: Input) = input(JsonField.of(input)) + + /** + * Sets [Builder.input] to an arbitrary JSON value. + * + * You should usually call [Builder.input] with a well-typed [Input] 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 } + + fun runAt(runAt: String) = runAt(JsonField.of(runAt)) + + /** + * Sets [Builder.runAt] to an arbitrary JSON value. + * + * You should usually call [Builder.runAt] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun runAt(runAt: JsonField) = apply { this.runAt = runAt } + + fun startedAt(startedAt: String) = startedAt(JsonField.of(startedAt)) + + /** + * Sets [Builder.startedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.startedAt] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun startedAt(startedAt: JsonField) = apply { this.startedAt = startedAt } + + fun toolName(toolName: String) = toolName(JsonField.of(toolName)) + + /** + * Sets [Builder.toolName] to an arbitrary JSON value. + * + * You should usually call [Builder.toolName] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun toolName(toolName: JsonField) = apply { this.toolName = toolName } + + fun toolkitName(toolkitName: String) = toolkitName(JsonField.of(toolkitName)) + + /** + * Sets [Builder.toolkitName] to an arbitrary JSON value. + * + * You should usually call [Builder.toolkitName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun toolkitName(toolkitName: JsonField) = apply { this.toolkitName = toolkitName } + + fun toolkitVersion(toolkitVersion: String) = toolkitVersion(JsonField.of(toolkitVersion)) + + /** + * Sets [Builder.toolkitVersion] to an arbitrary JSON value. + * + * You should usually call [Builder.toolkitVersion] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun toolkitVersion(toolkitVersion: JsonField) = apply { + this.toolkitVersion = toolkitVersion + } + + fun updatedAt(updatedAt: String) = updatedAt(JsonField.of(updatedAt)) + + /** + * Sets [Builder.updatedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.updatedAt] with a well-typed [String] 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 userId(userId: String) = userId(JsonField.of(userId)) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun userId(userId: JsonField) = apply { this.userId = userId } + + 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 [ScheduledGetResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ScheduledGetResponse = + ScheduledGetResponse( + id, + (attempts ?: JsonMissing.of()).map { it.toImmutable() }, + createdAt, + executionStatus, + executionType, + finishedAt, + input, + runAt, + startedAt, + toolName, + toolkitName, + toolkitVersion, + updatedAt, + userId, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ScheduledGetResponse = apply { + if (validated) { + return@apply + } + + id() + attempts().ifPresent { it.forEach { it.validate() } } + createdAt() + executionStatus() + executionType() + finishedAt() + input().ifPresent { it.validate() } + runAt() + startedAt() + toolName() + toolkitName() + toolkitVersion() + updatedAt() + userId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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) + + (attempts.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (createdAt.asKnown().isPresent) 1 else 0) + + (if (executionStatus.asKnown().isPresent) 1 else 0) + + (if (executionType.asKnown().isPresent) 1 else 0) + + (if (finishedAt.asKnown().isPresent) 1 else 0) + + (input.asKnown().getOrNull()?.validity() ?: 0) + + (if (runAt.asKnown().isPresent) 1 else 0) + + (if (startedAt.asKnown().isPresent) 1 else 0) + + (if (toolName.asKnown().isPresent) 1 else 0) + + (if (toolkitName.asKnown().isPresent) 1 else 0) + + (if (toolkitVersion.asKnown().isPresent) 1 else 0) + + (if (updatedAt.asKnown().isPresent) 1 else 0) + + (if (userId.asKnown().isPresent) 1 else 0) + + class Input + @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 [Input]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Input]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(input: Input) = apply { + additionalProperties = input.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 [Input]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Input = Input(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Input = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 Input && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Input{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ScheduledGetResponse && + id == other.id && + attempts == other.attempts && + createdAt == other.createdAt && + executionStatus == other.executionStatus && + executionType == other.executionType && + finishedAt == other.finishedAt && + input == other.input && + runAt == other.runAt && + startedAt == other.startedAt && + toolName == other.toolName && + toolkitName == other.toolkitName && + toolkitVersion == other.toolkitVersion && + updatedAt == other.updatedAt && + userId == other.userId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + attempts, + createdAt, + executionStatus, + executionType, + finishedAt, + input, + runAt, + startedAt, + toolName, + toolkitName, + toolkitVersion, + updatedAt, + userId, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ScheduledGetResponse{id=$id, attempts=$attempts, createdAt=$createdAt, executionStatus=$executionStatus, executionType=$executionType, finishedAt=$finishedAt, input=$input, runAt=$runAt, startedAt=$startedAt, toolName=$toolName, toolkitName=$toolkitName, toolkitVersion=$toolkitVersion, updatedAt=$updatedAt, userId=$userId, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/scheduled/ScheduledListPage.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/scheduled/ScheduledListPage.kt new file mode 100644 index 0000000..0c9984e --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/scheduled/ScheduledListPage.kt @@ -0,0 +1,146 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.tools.scheduled + +import dev.arcade.core.AutoPager +import dev.arcade.core.Page +import dev.arcade.core.checkRequired +import dev.arcade.models.tools.ToolExecution +import dev.arcade.services.blocking.tools.ScheduledService +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrDefault +import kotlin.jvm.optionals.getOrNull + +/** @see ScheduledService.list */ +class ScheduledListPage +private constructor( + private val service: ScheduledService, + private val params: ScheduledListParams, + private val response: ScheduledListPageResponse, +) : Page { + + /** + * Delegates to [ScheduledListPageResponse], but gracefully handles missing data. + * + * @see ScheduledListPageResponse.items + */ + override fun items(): List = + response._items().getOptional("items").getOrNull() ?: emptyList() + + /** + * Delegates to [ScheduledListPageResponse], but gracefully handles missing data. + * + * @see ScheduledListPageResponse.totalCount + */ + fun totalCount(): Optional = response._totalCount().getOptional("total_count") + + /** + * Delegates to [ScheduledListPageResponse], but gracefully handles missing data. + * + * @see ScheduledListPageResponse.offset + */ + fun offset(): Optional = response._offset().getOptional("offset") + + override fun hasNextPage(): Boolean { + if (items().isEmpty()) { + return false + } + + val offset = offset().getOrDefault(0) + val totalCount = totalCount().getOrNull() + return totalCount == null || offset + items().size < totalCount + } + + fun nextPageParams(): ScheduledListParams { + val offset = offset().getOrDefault(0) + return params.toBuilder().offset(offset + items().size).build() + } + + override fun nextPage(): ScheduledListPage = service.list(nextPageParams()) + + fun autoPager(): AutoPager = AutoPager.from(this) + + /** The parameters that were used to request this page. */ + fun params(): ScheduledListParams = params + + /** The response that this page was parsed from. */ + fun response(): ScheduledListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ScheduledListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ScheduledListPage]. */ + class Builder internal constructor() { + + private var service: ScheduledService? = null + private var params: ScheduledListParams? = null + private var response: ScheduledListPageResponse? = null + + @JvmSynthetic + internal fun from(scheduledListPage: ScheduledListPage) = apply { + service = scheduledListPage.service + params = scheduledListPage.params + response = scheduledListPage.response + } + + fun service(service: ScheduledService) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: ScheduledListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: ScheduledListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [ScheduledListPage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ScheduledListPage = + ScheduledListPage( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ScheduledListPage && + service == other.service && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, params, response) + + override fun toString() = + "ScheduledListPage{service=$service, params=$params, response=$response}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/scheduled/ScheduledListPageAsync.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/scheduled/ScheduledListPageAsync.kt new file mode 100644 index 0000000..4fabd60 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/scheduled/ScheduledListPageAsync.kt @@ -0,0 +1,161 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.tools.scheduled + +import dev.arcade.core.AutoPagerAsync +import dev.arcade.core.PageAsync +import dev.arcade.core.checkRequired +import dev.arcade.models.tools.ToolExecution +import dev.arcade.services.async.tools.ScheduledServiceAsync +import java.util.Objects +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import kotlin.jvm.optionals.getOrDefault +import kotlin.jvm.optionals.getOrNull + +/** @see ScheduledServiceAsync.list */ +class ScheduledListPageAsync +private constructor( + private val service: ScheduledServiceAsync, + private val streamHandlerExecutor: Executor, + private val params: ScheduledListParams, + private val response: ScheduledListPageResponse, +) : PageAsync { + + /** + * Delegates to [ScheduledListPageResponse], but gracefully handles missing data. + * + * @see ScheduledListPageResponse.items + */ + override fun items(): List = + response._items().getOptional("items").getOrNull() ?: emptyList() + + /** + * Delegates to [ScheduledListPageResponse], but gracefully handles missing data. + * + * @see ScheduledListPageResponse.totalCount + */ + fun totalCount(): Optional = response._totalCount().getOptional("total_count") + + /** + * Delegates to [ScheduledListPageResponse], but gracefully handles missing data. + * + * @see ScheduledListPageResponse.offset + */ + fun offset(): Optional = response._offset().getOptional("offset") + + override fun hasNextPage(): Boolean { + if (items().isEmpty()) { + return false + } + + val offset = offset().getOrDefault(0) + val totalCount = totalCount().getOrNull() + return totalCount == null || offset + items().size < totalCount + } + + fun nextPageParams(): ScheduledListParams { + val offset = offset().getOrDefault(0) + return params.toBuilder().offset(offset + items().size).build() + } + + override fun nextPage(): CompletableFuture = + service.list(nextPageParams()) + + fun autoPager(): AutoPagerAsync = + AutoPagerAsync.from(this, streamHandlerExecutor) + + /** The parameters that were used to request this page. */ + fun params(): ScheduledListParams = params + + /** The response that this page was parsed from. */ + fun response(): ScheduledListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ScheduledListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ScheduledListPageAsync]. */ + class Builder internal constructor() { + + private var service: ScheduledServiceAsync? = null + private var streamHandlerExecutor: Executor? = null + private var params: ScheduledListParams? = null + private var response: ScheduledListPageResponse? = null + + @JvmSynthetic + internal fun from(scheduledListPageAsync: ScheduledListPageAsync) = apply { + service = scheduledListPageAsync.service + streamHandlerExecutor = scheduledListPageAsync.streamHandlerExecutor + params = scheduledListPageAsync.params + response = scheduledListPageAsync.response + } + + fun service(service: ScheduledServiceAsync) = apply { this.service = service } + + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + this.streamHandlerExecutor = streamHandlerExecutor + } + + /** The parameters that were used to request this page. */ + fun params(params: ScheduledListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: ScheduledListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [ScheduledListPageAsync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ScheduledListPageAsync = + ScheduledListPageAsync( + checkRequired("service", service), + checkRequired("streamHandlerExecutor", streamHandlerExecutor), + checkRequired("params", params), + checkRequired("response", response), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ScheduledListPageAsync && + service == other.service && + streamHandlerExecutor == other.streamHandlerExecutor && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, streamHandlerExecutor, params, response) + + override fun toString() = + "ScheduledListPageAsync{service=$service, streamHandlerExecutor=$streamHandlerExecutor, params=$params, response=$response}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/scheduled/ScheduledListPageResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/scheduled/ScheduledListPageResponse.kt new file mode 100644 index 0000000..98f1c94 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/scheduled/ScheduledListPageResponse.kt @@ -0,0 +1,305 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.tools.scheduled + +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 dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.core.checkKnown +import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import dev.arcade.models.tools.ToolExecution +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class ScheduledListPageResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val items: JsonField>, + private val limit: JsonField, + private val offset: JsonField, + private val pageCount: JsonField, + private val totalCount: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("items") + @ExcludeMissing + items: JsonField> = JsonMissing.of(), + @JsonProperty("limit") @ExcludeMissing limit: JsonField = JsonMissing.of(), + @JsonProperty("offset") @ExcludeMissing offset: JsonField = JsonMissing.of(), + @JsonProperty("page_count") @ExcludeMissing pageCount: JsonField = JsonMissing.of(), + @JsonProperty("total_count") @ExcludeMissing totalCount: JsonField = JsonMissing.of(), + ) : this(items, limit, offset, pageCount, totalCount, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun items(): Optional> = items.getOptional("items") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun limit(): Optional = limit.getOptional("limit") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun offset(): Optional = offset.getOptional("offset") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun pageCount(): Optional = pageCount.getOptional("page_count") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun totalCount(): Optional = totalCount.getOptional("total_count") + + /** + * Returns the raw JSON value of [items]. + * + * Unlike [items], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("items") @ExcludeMissing fun _items(): JsonField> = items + + /** + * Returns the raw JSON value of [limit]. + * + * Unlike [limit], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("limit") @ExcludeMissing fun _limit(): JsonField = limit + + /** + * Returns the raw JSON value of [offset]. + * + * Unlike [offset], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("offset") @ExcludeMissing fun _offset(): JsonField = offset + + /** + * Returns the raw JSON value of [pageCount]. + * + * Unlike [pageCount], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("page_count") @ExcludeMissing fun _pageCount(): JsonField = pageCount + + /** + * Returns the raw JSON value of [totalCount]. + * + * Unlike [totalCount], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("total_count") @ExcludeMissing fun _totalCount(): JsonField = totalCount + + @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 [ScheduledListPageResponse]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ScheduledListPageResponse]. */ + class Builder internal constructor() { + + private var items: JsonField>? = null + private var limit: JsonField = JsonMissing.of() + private var offset: JsonField = JsonMissing.of() + private var pageCount: JsonField = JsonMissing.of() + private var totalCount: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(scheduledListPageResponse: ScheduledListPageResponse) = apply { + items = scheduledListPageResponse.items.map { it.toMutableList() } + limit = scheduledListPageResponse.limit + offset = scheduledListPageResponse.offset + pageCount = scheduledListPageResponse.pageCount + totalCount = scheduledListPageResponse.totalCount + additionalProperties = scheduledListPageResponse.additionalProperties.toMutableMap() + } + + fun items(items: List) = items(JsonField.of(items)) + + /** + * Sets [Builder.items] to an arbitrary JSON value. + * + * You should usually call [Builder.items] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun items(items: JsonField>) = apply { + this.items = items.map { it.toMutableList() } + } + + /** + * Adds a single [ToolExecution] to [items]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addItem(item: ToolExecution) = apply { + items = + (items ?: JsonField.of(mutableListOf())).also { checkKnown("items", it).add(item) } + } + + fun limit(limit: Long) = limit(JsonField.of(limit)) + + /** + * Sets [Builder.limit] to an arbitrary JSON value. + * + * You should usually call [Builder.limit] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun limit(limit: JsonField) = apply { this.limit = limit } + + fun offset(offset: Long) = offset(JsonField.of(offset)) + + /** + * Sets [Builder.offset] to an arbitrary JSON value. + * + * You should usually call [Builder.offset] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun offset(offset: JsonField) = apply { this.offset = offset } + + fun pageCount(pageCount: Long) = pageCount(JsonField.of(pageCount)) + + /** + * Sets [Builder.pageCount] to an arbitrary JSON value. + * + * You should usually call [Builder.pageCount] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun pageCount(pageCount: JsonField) = apply { this.pageCount = pageCount } + + fun totalCount(totalCount: Long) = totalCount(JsonField.of(totalCount)) + + /** + * Sets [Builder.totalCount] to an arbitrary JSON value. + * + * You should usually call [Builder.totalCount] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun totalCount(totalCount: JsonField) = apply { this.totalCount = totalCount } + + 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 [ScheduledListPageResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ScheduledListPageResponse = + ScheduledListPageResponse( + (items ?: JsonMissing.of()).map { it.toImmutable() }, + limit, + offset, + pageCount, + totalCount, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ScheduledListPageResponse = apply { + if (validated) { + return@apply + } + + items().ifPresent { it.forEach { it.validate() } } + limit() + offset() + pageCount() + totalCount() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (items.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (limit.asKnown().isPresent) 1 else 0) + + (if (offset.asKnown().isPresent) 1 else 0) + + (if (pageCount.asKnown().isPresent) 1 else 0) + + (if (totalCount.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ScheduledListPageResponse && + items == other.items && + limit == other.limit && + offset == other.offset && + pageCount == other.pageCount && + totalCount == other.totalCount && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(items, limit, offset, pageCount, totalCount, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ScheduledListPageResponse{items=$items, limit=$limit, offset=$offset, pageCount=$pageCount, totalCount=$totalCount, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolScheduledListParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/scheduled/ScheduledListParams.kt similarity index 70% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/ToolScheduledListParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/tools/scheduled/ScheduledListParams.kt index fbdf6bb..eacac65 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/ToolScheduledListParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/tools/scheduled/ScheduledListParams.kt @@ -1,16 +1,16 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.tools.scheduled -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params import dev.arcade.core.http.Headers import dev.arcade.core.http.QueryParams import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Returns a page of scheduled tool executions */ -class ToolScheduledListParams +class ScheduledListParams private constructor( private val limit: Long?, private val offset: Long?, @@ -24,29 +24,23 @@ private constructor( /** Offset from the start of the list (default: 0) */ fun offset(): Optional = Optional.ofNullable(offset) + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams { - val queryParams = QueryParams.builder() - this.limit?.let { queryParams.put("limit", listOf(it.toString())) } - this.offset?.let { queryParams.put("offset", listOf(it.toString())) } - queryParams.putAll(additionalQueryParams) - return queryParams.build() - } - fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): ScheduledListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [ScheduledListParams]. */ @JvmStatic fun builder() = Builder() } - /** A builder for [ToolScheduledListParams]. */ - @NoAutoDetect + /** A builder for [ScheduledListParams]. */ class Builder internal constructor() { private var limit: Long? = null @@ -55,32 +49,38 @@ private constructor( private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @JvmSynthetic - internal fun from(toolScheduledListParams: ToolScheduledListParams) = apply { - limit = toolScheduledListParams.limit - offset = toolScheduledListParams.offset - additionalHeaders = toolScheduledListParams.additionalHeaders.toBuilder() - additionalQueryParams = toolScheduledListParams.additionalQueryParams.toBuilder() + internal fun from(scheduledListParams: ScheduledListParams) = apply { + limit = scheduledListParams.limit + offset = scheduledListParams.offset + additionalHeaders = scheduledListParams.additionalHeaders.toBuilder() + additionalQueryParams = scheduledListParams.additionalQueryParams.toBuilder() } /** Number of items to return (default: 25, max: 100) */ fun limit(limit: Long?) = apply { this.limit = limit } - /** Number of items to return (default: 25, max: 100) */ + /** + * Alias for [Builder.limit]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun limit(limit: Long) = limit(limit as Long?) - /** Number of items to return (default: 25, max: 100) */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun limit(limit: Optional) = limit(limit.orElse(null) as Long?) + /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ + fun limit(limit: Optional) = limit(limit.getOrNull()) /** Offset from the start of the list (default: 0) */ fun offset(offset: Long?) = apply { this.offset = offset } - /** Offset from the start of the list (default: 0) */ + /** + * Alias for [Builder.offset]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun offset(offset: Long) = offset(offset as Long?) - /** Offset from the start of the list (default: 0) */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun offset(offset: Optional) = offset(offset.orElse(null) as Long?) + /** Alias for calling [Builder.offset] with `offset.orElse(null)`. */ + fun offset(offset: Optional) = offset(offset.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -180,8 +180,13 @@ private constructor( additionalQueryParams.removeAll(keys) } - fun build(): ToolScheduledListParams = - ToolScheduledListParams( + /** + * Returns an immutable instance of [ScheduledListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ScheduledListParams = + ScheduledListParams( limit, offset, additionalHeaders.build(), @@ -189,16 +194,32 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + limit?.let { put("limit", it.toString()) } + offset?.let { put("offset", it.toString()) } + putAll(additionalQueryParams) + } + .build() + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is ToolScheduledListParams && limit == other.limit && offset == other.offset && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is ScheduledListParams && + limit == other.limit && + offset == other.offset && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(limit, offset, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(limit, offset, additionalHeaders, additionalQueryParams) override fun toString() = - "ToolScheduledListParams{limit=$limit, offset=$offset, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" + "ScheduledListParams{limit=$limit, offset=$offset, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/CreateWorkerRequest.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/CreateWorkerRequest.kt new file mode 100644 index 0000000..ed1a052 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/CreateWorkerRequest.kt @@ -0,0 +1,1368 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.workers + +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 dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.core.checkRequired +import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class CreateWorkerRequest +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val id: JsonField, + private val enabled: JsonField, + private val http: JsonField, + private val mcp: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("enabled") @ExcludeMissing enabled: JsonField = JsonMissing.of(), + @JsonProperty("http") @ExcludeMissing http: JsonField = JsonMissing.of(), + @JsonProperty("mcp") @ExcludeMissing mcp: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(id, enabled, http, mcp, type, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException 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 ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun enabled(): Optional = enabled.getOptional("enabled") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun http(): Optional = http.getOptional("http") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun mcp(): Optional = mcp.getOptional("mcp") + + /** + * @throws ArcadeInvalidDataException 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 [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 [enabled]. + * + * Unlike [enabled], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("enabled") @ExcludeMissing fun _enabled(): JsonField = enabled + + /** + * Returns the raw JSON value of [http]. + * + * Unlike [http], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("http") @ExcludeMissing fun _http(): JsonField = http + + /** + * Returns the raw JSON value of [mcp]. + * + * Unlike [mcp], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("mcp") @ExcludeMissing fun _mcp(): JsonField = mcp + + /** + * 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 [CreateWorkerRequest]. + * + * The following fields are required: + * ```java + * .id() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CreateWorkerRequest]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var enabled: JsonField = JsonMissing.of() + private var http: JsonField = JsonMissing.of() + private var mcp: JsonField = JsonMissing.of() + private var type: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(createWorkerRequest: CreateWorkerRequest) = apply { + id = createWorkerRequest.id + enabled = createWorkerRequest.enabled + http = createWorkerRequest.http + mcp = createWorkerRequest.mcp + type = createWorkerRequest.type + additionalProperties = createWorkerRequest.additionalProperties.toMutableMap() + } + + 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 enabled(enabled: Boolean) = enabled(JsonField.of(enabled)) + + /** + * Sets [Builder.enabled] to an arbitrary JSON value. + * + * You should usually call [Builder.enabled] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun enabled(enabled: JsonField) = apply { this.enabled = enabled } + + fun http(http: Http) = http(JsonField.of(http)) + + /** + * Sets [Builder.http] to an arbitrary JSON value. + * + * You should usually call [Builder.http] with a well-typed [Http] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun http(http: JsonField) = apply { this.http = http } + + fun mcp(mcp: Mcp) = mcp(JsonField.of(mcp)) + + /** + * Sets [Builder.mcp] to an arbitrary JSON value. + * + * You should usually call [Builder.mcp] with a well-typed [Mcp] value instead. This method + * is primarily for setting the field to an undocumented or not yet supported value. + */ + fun mcp(mcp: JsonField) = apply { this.mcp = mcp } + + 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 [CreateWorkerRequest]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): CreateWorkerRequest = + CreateWorkerRequest( + checkRequired("id", id), + enabled, + http, + mcp, + type, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): CreateWorkerRequest = apply { + if (validated) { + return@apply + } + + id() + enabled() + http().ifPresent { it.validate() } + mcp().ifPresent { it.validate() } + type() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (enabled.asKnown().isPresent) 1 else 0) + + (http.asKnown().getOrNull()?.validity() ?: 0) + + (mcp.asKnown().getOrNull()?.validity() ?: 0) + + (if (type.asKnown().isPresent) 1 else 0) + + class Http + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val retry: JsonField, + private val secret: JsonField, + private val timeout: JsonField, + private val uri: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("retry") @ExcludeMissing retry: JsonField = JsonMissing.of(), + @JsonProperty("secret") @ExcludeMissing secret: JsonField = JsonMissing.of(), + @JsonProperty("timeout") @ExcludeMissing timeout: JsonField = JsonMissing.of(), + @JsonProperty("uri") @ExcludeMissing uri: JsonField = JsonMissing.of(), + ) : this(retry, secret, timeout, uri, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException 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 retry(): Long = retry.getRequired("retry") + + /** + * @throws ArcadeInvalidDataException 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 secret(): String = secret.getRequired("secret") + + /** + * @throws ArcadeInvalidDataException 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 timeout(): Long = timeout.getRequired("timeout") + + /** + * @throws ArcadeInvalidDataException 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 uri(): String = uri.getRequired("uri") + + /** + * Returns the raw JSON value of [retry]. + * + * Unlike [retry], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("retry") @ExcludeMissing fun _retry(): JsonField = retry + + /** + * Returns the raw JSON value of [secret]. + * + * Unlike [secret], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("secret") @ExcludeMissing fun _secret(): JsonField = secret + + /** + * Returns the raw JSON value of [timeout]. + * + * Unlike [timeout], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("timeout") @ExcludeMissing fun _timeout(): JsonField = timeout + + /** + * Returns the raw JSON value of [uri]. + * + * Unlike [uri], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("uri") @ExcludeMissing fun _uri(): JsonField = uri + + @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 [Http]. + * + * The following fields are required: + * ```java + * .retry() + * .secret() + * .timeout() + * .uri() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Http]. */ + class Builder internal constructor() { + + private var retry: JsonField? = null + private var secret: JsonField? = null + private var timeout: JsonField? = null + private var uri: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(http: Http) = apply { + retry = http.retry + secret = http.secret + timeout = http.timeout + uri = http.uri + additionalProperties = http.additionalProperties.toMutableMap() + } + + fun retry(retry: Long) = retry(JsonField.of(retry)) + + /** + * Sets [Builder.retry] to an arbitrary JSON value. + * + * You should usually call [Builder.retry] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun retry(retry: JsonField) = apply { this.retry = retry } + + fun secret(secret: String) = secret(JsonField.of(secret)) + + /** + * Sets [Builder.secret] to an arbitrary JSON value. + * + * You should usually call [Builder.secret] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun secret(secret: JsonField) = apply { this.secret = secret } + + fun timeout(timeout: Long) = timeout(JsonField.of(timeout)) + + /** + * Sets [Builder.timeout] to an arbitrary JSON value. + * + * You should usually call [Builder.timeout] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun timeout(timeout: JsonField) = apply { this.timeout = timeout } + + fun uri(uri: String) = uri(JsonField.of(uri)) + + /** + * Sets [Builder.uri] to an arbitrary JSON value. + * + * You should usually call [Builder.uri] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun uri(uri: JsonField) = apply { this.uri = uri } + + 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 [Http]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .retry() + * .secret() + * .timeout() + * .uri() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Http = + Http( + checkRequired("retry", retry), + checkRequired("secret", secret), + checkRequired("timeout", timeout), + checkRequired("uri", uri), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Http = apply { + if (validated) { + return@apply + } + + retry() + secret() + timeout() + uri() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (retry.asKnown().isPresent) 1 else 0) + + (if (secret.asKnown().isPresent) 1 else 0) + + (if (timeout.asKnown().isPresent) 1 else 0) + + (if (uri.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Http && + retry == other.retry && + secret == other.secret && + timeout == other.timeout && + uri == other.uri && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(retry, secret, timeout, uri, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Http{retry=$retry, secret=$secret, timeout=$timeout, uri=$uri, additionalProperties=$additionalProperties}" + } + + class Mcp + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val retry: JsonField, + private val timeout: JsonField, + private val uri: JsonField, + private val headers: JsonField, + private val oauth2: JsonField, + private val secrets: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("retry") @ExcludeMissing retry: JsonField = JsonMissing.of(), + @JsonProperty("timeout") @ExcludeMissing timeout: JsonField = JsonMissing.of(), + @JsonProperty("uri") @ExcludeMissing uri: JsonField = JsonMissing.of(), + @JsonProperty("headers") @ExcludeMissing headers: JsonField = JsonMissing.of(), + @JsonProperty("oauth2") @ExcludeMissing oauth2: JsonField = JsonMissing.of(), + @JsonProperty("secrets") @ExcludeMissing secrets: JsonField = JsonMissing.of(), + ) : this(retry, timeout, uri, headers, oauth2, secrets, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException 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 retry(): Long = retry.getRequired("retry") + + /** + * @throws ArcadeInvalidDataException 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 timeout(): Long = timeout.getRequired("timeout") + + /** + * @throws ArcadeInvalidDataException 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 uri(): String = uri.getRequired("uri") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun headers(): Optional = headers.getOptional("headers") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun oauth2(): Optional = oauth2.getOptional("oauth2") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun secrets(): Optional = secrets.getOptional("secrets") + + /** + * Returns the raw JSON value of [retry]. + * + * Unlike [retry], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("retry") @ExcludeMissing fun _retry(): JsonField = retry + + /** + * Returns the raw JSON value of [timeout]. + * + * Unlike [timeout], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("timeout") @ExcludeMissing fun _timeout(): JsonField = timeout + + /** + * Returns the raw JSON value of [uri]. + * + * Unlike [uri], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("uri") @ExcludeMissing fun _uri(): JsonField = uri + + /** + * Returns the raw JSON value of [headers]. + * + * Unlike [headers], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("headers") @ExcludeMissing fun _headers(): JsonField = headers + + /** + * Returns the raw JSON value of [oauth2]. + * + * Unlike [oauth2], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("oauth2") @ExcludeMissing fun _oauth2(): JsonField = oauth2 + + /** + * Returns the raw JSON value of [secrets]. + * + * Unlike [secrets], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("secrets") @ExcludeMissing fun _secrets(): JsonField = secrets + + @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 [Mcp]. + * + * The following fields are required: + * ```java + * .retry() + * .timeout() + * .uri() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Mcp]. */ + class Builder internal constructor() { + + private var retry: JsonField? = null + private var timeout: JsonField? = null + private var uri: JsonField? = null + private var headers: JsonField = JsonMissing.of() + private var oauth2: JsonField = JsonMissing.of() + private var secrets: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(mcp: Mcp) = apply { + retry = mcp.retry + timeout = mcp.timeout + uri = mcp.uri + headers = mcp.headers + oauth2 = mcp.oauth2 + secrets = mcp.secrets + additionalProperties = mcp.additionalProperties.toMutableMap() + } + + fun retry(retry: Long) = retry(JsonField.of(retry)) + + /** + * Sets [Builder.retry] to an arbitrary JSON value. + * + * You should usually call [Builder.retry] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun retry(retry: JsonField) = apply { this.retry = retry } + + fun timeout(timeout: Long) = timeout(JsonField.of(timeout)) + + /** + * Sets [Builder.timeout] to an arbitrary JSON value. + * + * You should usually call [Builder.timeout] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun timeout(timeout: JsonField) = apply { this.timeout = timeout } + + fun uri(uri: String) = uri(JsonField.of(uri)) + + /** + * Sets [Builder.uri] to an arbitrary JSON value. + * + * You should usually call [Builder.uri] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun uri(uri: JsonField) = apply { this.uri = uri } + + fun headers(headers: Headers) = headers(JsonField.of(headers)) + + /** + * Sets [Builder.headers] to an arbitrary JSON value. + * + * You should usually call [Builder.headers] with a well-typed [Headers] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun headers(headers: JsonField) = apply { this.headers = headers } + + fun oauth2(oauth2: Oauth2) = oauth2(JsonField.of(oauth2)) + + /** + * Sets [Builder.oauth2] to an arbitrary JSON value. + * + * You should usually call [Builder.oauth2] with a well-typed [Oauth2] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun oauth2(oauth2: JsonField) = apply { this.oauth2 = oauth2 } + + fun secrets(secrets: Secrets) = secrets(JsonField.of(secrets)) + + /** + * Sets [Builder.secrets] to an arbitrary JSON value. + * + * You should usually call [Builder.secrets] with a well-typed [Secrets] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun secrets(secrets: JsonField) = apply { this.secrets = secrets } + + 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 [Mcp]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .retry() + * .timeout() + * .uri() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Mcp = + Mcp( + checkRequired("retry", retry), + checkRequired("timeout", timeout), + checkRequired("uri", uri), + headers, + oauth2, + secrets, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Mcp = apply { + if (validated) { + return@apply + } + + retry() + timeout() + uri() + headers().ifPresent { it.validate() } + oauth2().ifPresent { it.validate() } + secrets().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (retry.asKnown().isPresent) 1 else 0) + + (if (timeout.asKnown().isPresent) 1 else 0) + + (if (uri.asKnown().isPresent) 1 else 0) + + (headers.asKnown().getOrNull()?.validity() ?: 0) + + (oauth2.asKnown().getOrNull()?.validity() ?: 0) + + (secrets.asKnown().getOrNull()?.validity() ?: 0) + + class Headers + @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 [Headers]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Headers]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(headers: Headers) = apply { + additionalProperties = headers.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 [Headers]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Headers = Headers(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Headers = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 Headers && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Headers{additionalProperties=$additionalProperties}" + } + + class Oauth2 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val authorizationUrl: JsonField, + private val clientId: JsonField, + private val clientSecret: JsonField, + private val externalId: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("authorization_url") + @ExcludeMissing + authorizationUrl: JsonField = JsonMissing.of(), + @JsonProperty("client_id") + @ExcludeMissing + clientId: JsonField = JsonMissing.of(), + @JsonProperty("client_secret") + @ExcludeMissing + clientSecret: JsonField = JsonMissing.of(), + @JsonProperty("external_id") + @ExcludeMissing + externalId: JsonField = JsonMissing.of(), + ) : this(authorizationUrl, clientId, clientSecret, externalId, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authorizationUrl(): Optional = + authorizationUrl.getOptional("authorization_url") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun clientId(): Optional = clientId.getOptional("client_id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun clientSecret(): Optional = clientSecret.getOptional("client_secret") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun externalId(): Optional = externalId.getOptional("external_id") + + /** + * Returns the raw JSON value of [authorizationUrl]. + * + * Unlike [authorizationUrl], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("authorization_url") + @ExcludeMissing + fun _authorizationUrl(): JsonField = authorizationUrl + + /** + * Returns the raw JSON value of [clientId]. + * + * Unlike [clientId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("client_id") @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("client_secret") + @ExcludeMissing + fun _clientSecret(): JsonField = clientSecret + + /** + * Returns the raw JSON value of [externalId]. + * + * Unlike [externalId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("external_id") + @ExcludeMissing + fun _externalId(): JsonField = externalId + + @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 [Oauth2]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Oauth2]. */ + class Builder internal constructor() { + + private var authorizationUrl: JsonField = JsonMissing.of() + private var clientId: JsonField = JsonMissing.of() + private var clientSecret: JsonField = JsonMissing.of() + private var externalId: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(oauth2: Oauth2) = apply { + authorizationUrl = oauth2.authorizationUrl + clientId = oauth2.clientId + clientSecret = oauth2.clientSecret + externalId = oauth2.externalId + additionalProperties = oauth2.additionalProperties.toMutableMap() + } + + fun authorizationUrl(authorizationUrl: String) = + authorizationUrl(JsonField.of(authorizationUrl)) + + /** + * Sets [Builder.authorizationUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.authorizationUrl] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun authorizationUrl(authorizationUrl: JsonField) = apply { + this.authorizationUrl = authorizationUrl + } + + 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 } + + 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 + } + + fun externalId(externalId: String) = externalId(JsonField.of(externalId)) + + /** + * Sets [Builder.externalId] to an arbitrary JSON value. + * + * You should usually call [Builder.externalId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun externalId(externalId: JsonField) = apply { + this.externalId = externalId + } + + 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 [Oauth2]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Oauth2 = + Oauth2( + authorizationUrl, + clientId, + clientSecret, + externalId, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Oauth2 = apply { + if (validated) { + return@apply + } + + authorizationUrl() + clientId() + clientSecret() + externalId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (authorizationUrl.asKnown().isPresent) 1 else 0) + + (if (clientId.asKnown().isPresent) 1 else 0) + + (if (clientSecret.asKnown().isPresent) 1 else 0) + + (if (externalId.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Oauth2 && + authorizationUrl == other.authorizationUrl && + clientId == other.clientId && + clientSecret == other.clientSecret && + externalId == other.externalId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + authorizationUrl, + clientId, + clientSecret, + externalId, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Oauth2{authorizationUrl=$authorizationUrl, clientId=$clientId, clientSecret=$clientSecret, externalId=$externalId, additionalProperties=$additionalProperties}" + } + + class Secrets + @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 [Secrets]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Secrets]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(secrets: Secrets) = apply { + additionalProperties = secrets.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 [Secrets]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Secrets = Secrets(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Secrets = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 Secrets && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Secrets{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Mcp && + retry == other.retry && + timeout == other.timeout && + uri == other.uri && + headers == other.headers && + oauth2 == other.oauth2 && + secrets == other.secrets && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(retry, timeout, uri, headers, oauth2, secrets, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Mcp{retry=$retry, timeout=$timeout, uri=$uri, headers=$headers, oauth2=$oauth2, secrets=$secrets, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CreateWorkerRequest && + id == other.id && + enabled == other.enabled && + http == other.http && + mcp == other.mcp && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(id, enabled, http, mcp, type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CreateWorkerRequest{id=$id, enabled=$enabled, http=$http, mcp=$mcp, type=$type, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/UpdateWorkerRequest.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/UpdateWorkerRequest.kt new file mode 100644 index 0000000..039958e --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/UpdateWorkerRequest.kt @@ -0,0 +1,1195 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.workers + +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 dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class UpdateWorkerRequest +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val enabled: JsonField, + private val http: JsonField, + private val mcp: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("enabled") @ExcludeMissing enabled: JsonField = JsonMissing.of(), + @JsonProperty("http") @ExcludeMissing http: JsonField = JsonMissing.of(), + @JsonProperty("mcp") @ExcludeMissing mcp: JsonField = JsonMissing.of(), + ) : this(enabled, http, mcp, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun enabled(): Optional = enabled.getOptional("enabled") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun http(): Optional = http.getOptional("http") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun mcp(): Optional = mcp.getOptional("mcp") + + /** + * Returns the raw JSON value of [enabled]. + * + * Unlike [enabled], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("enabled") @ExcludeMissing fun _enabled(): JsonField = enabled + + /** + * Returns the raw JSON value of [http]. + * + * Unlike [http], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("http") @ExcludeMissing fun _http(): JsonField = http + + /** + * Returns the raw JSON value of [mcp]. + * + * Unlike [mcp], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("mcp") @ExcludeMissing fun _mcp(): JsonField = mcp + + @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 [UpdateWorkerRequest]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UpdateWorkerRequest]. */ + class Builder internal constructor() { + + private var enabled: JsonField = JsonMissing.of() + private var http: JsonField = JsonMissing.of() + private var mcp: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(updateWorkerRequest: UpdateWorkerRequest) = apply { + enabled = updateWorkerRequest.enabled + http = updateWorkerRequest.http + mcp = updateWorkerRequest.mcp + additionalProperties = updateWorkerRequest.additionalProperties.toMutableMap() + } + + fun enabled(enabled: Boolean) = enabled(JsonField.of(enabled)) + + /** + * Sets [Builder.enabled] to an arbitrary JSON value. + * + * You should usually call [Builder.enabled] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun enabled(enabled: JsonField) = apply { this.enabled = enabled } + + fun http(http: Http) = http(JsonField.of(http)) + + /** + * Sets [Builder.http] to an arbitrary JSON value. + * + * You should usually call [Builder.http] with a well-typed [Http] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun http(http: JsonField) = apply { this.http = http } + + fun mcp(mcp: Mcp) = mcp(JsonField.of(mcp)) + + /** + * Sets [Builder.mcp] to an arbitrary JSON value. + * + * You should usually call [Builder.mcp] with a well-typed [Mcp] value instead. This method + * is primarily for setting the field to an undocumented or not yet supported value. + */ + fun mcp(mcp: JsonField) = apply { this.mcp = mcp } + + 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 [UpdateWorkerRequest]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): UpdateWorkerRequest = + UpdateWorkerRequest(enabled, http, mcp, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): UpdateWorkerRequest = apply { + if (validated) { + return@apply + } + + enabled() + http().ifPresent { it.validate() } + mcp().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (enabled.asKnown().isPresent) 1 else 0) + + (http.asKnown().getOrNull()?.validity() ?: 0) + + (mcp.asKnown().getOrNull()?.validity() ?: 0) + + class Http + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val retry: JsonField, + private val secret: JsonField, + private val timeout: JsonField, + private val uri: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("retry") @ExcludeMissing retry: JsonField = JsonMissing.of(), + @JsonProperty("secret") @ExcludeMissing secret: JsonField = JsonMissing.of(), + @JsonProperty("timeout") @ExcludeMissing timeout: JsonField = JsonMissing.of(), + @JsonProperty("uri") @ExcludeMissing uri: JsonField = JsonMissing.of(), + ) : this(retry, secret, timeout, uri, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun retry(): Optional = retry.getOptional("retry") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun secret(): Optional = secret.getOptional("secret") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun timeout(): Optional = timeout.getOptional("timeout") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun uri(): Optional = uri.getOptional("uri") + + /** + * Returns the raw JSON value of [retry]. + * + * Unlike [retry], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("retry") @ExcludeMissing fun _retry(): JsonField = retry + + /** + * Returns the raw JSON value of [secret]. + * + * Unlike [secret], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("secret") @ExcludeMissing fun _secret(): JsonField = secret + + /** + * Returns the raw JSON value of [timeout]. + * + * Unlike [timeout], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("timeout") @ExcludeMissing fun _timeout(): JsonField = timeout + + /** + * Returns the raw JSON value of [uri]. + * + * Unlike [uri], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("uri") @ExcludeMissing fun _uri(): JsonField = uri + + @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 [Http]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Http]. */ + class Builder internal constructor() { + + private var retry: JsonField = JsonMissing.of() + private var secret: JsonField = JsonMissing.of() + private var timeout: JsonField = JsonMissing.of() + private var uri: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(http: Http) = apply { + retry = http.retry + secret = http.secret + timeout = http.timeout + uri = http.uri + additionalProperties = http.additionalProperties.toMutableMap() + } + + fun retry(retry: Long) = retry(JsonField.of(retry)) + + /** + * Sets [Builder.retry] to an arbitrary JSON value. + * + * You should usually call [Builder.retry] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun retry(retry: JsonField) = apply { this.retry = retry } + + fun secret(secret: String) = secret(JsonField.of(secret)) + + /** + * Sets [Builder.secret] to an arbitrary JSON value. + * + * You should usually call [Builder.secret] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun secret(secret: JsonField) = apply { this.secret = secret } + + fun timeout(timeout: Long) = timeout(JsonField.of(timeout)) + + /** + * Sets [Builder.timeout] to an arbitrary JSON value. + * + * You should usually call [Builder.timeout] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun timeout(timeout: JsonField) = apply { this.timeout = timeout } + + fun uri(uri: String) = uri(JsonField.of(uri)) + + /** + * Sets [Builder.uri] to an arbitrary JSON value. + * + * You should usually call [Builder.uri] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun uri(uri: JsonField) = apply { this.uri = uri } + + 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 [Http]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Http = + Http(retry, secret, timeout, uri, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Http = apply { + if (validated) { + return@apply + } + + retry() + secret() + timeout() + uri() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (retry.asKnown().isPresent) 1 else 0) + + (if (secret.asKnown().isPresent) 1 else 0) + + (if (timeout.asKnown().isPresent) 1 else 0) + + (if (uri.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Http && + retry == other.retry && + secret == other.secret && + timeout == other.timeout && + uri == other.uri && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(retry, secret, timeout, uri, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Http{retry=$retry, secret=$secret, timeout=$timeout, uri=$uri, additionalProperties=$additionalProperties}" + } + + class Mcp + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val headers: JsonField, + private val oauth2: JsonField, + private val retry: JsonField, + private val secrets: JsonField, + private val timeout: JsonField, + private val uri: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("headers") @ExcludeMissing headers: JsonField = JsonMissing.of(), + @JsonProperty("oauth2") @ExcludeMissing oauth2: JsonField = JsonMissing.of(), + @JsonProperty("retry") @ExcludeMissing retry: JsonField = JsonMissing.of(), + @JsonProperty("secrets") @ExcludeMissing secrets: JsonField = JsonMissing.of(), + @JsonProperty("timeout") @ExcludeMissing timeout: JsonField = JsonMissing.of(), + @JsonProperty("uri") @ExcludeMissing uri: JsonField = JsonMissing.of(), + ) : this(headers, oauth2, retry, secrets, timeout, uri, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun headers(): Optional = headers.getOptional("headers") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun oauth2(): Optional = oauth2.getOptional("oauth2") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun retry(): Optional = retry.getOptional("retry") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun secrets(): Optional = secrets.getOptional("secrets") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun timeout(): Optional = timeout.getOptional("timeout") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun uri(): Optional = uri.getOptional("uri") + + /** + * Returns the raw JSON value of [headers]. + * + * Unlike [headers], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("headers") @ExcludeMissing fun _headers(): JsonField = headers + + /** + * Returns the raw JSON value of [oauth2]. + * + * Unlike [oauth2], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("oauth2") @ExcludeMissing fun _oauth2(): JsonField = oauth2 + + /** + * Returns the raw JSON value of [retry]. + * + * Unlike [retry], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("retry") @ExcludeMissing fun _retry(): JsonField = retry + + /** + * Returns the raw JSON value of [secrets]. + * + * Unlike [secrets], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("secrets") @ExcludeMissing fun _secrets(): JsonField = secrets + + /** + * Returns the raw JSON value of [timeout]. + * + * Unlike [timeout], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("timeout") @ExcludeMissing fun _timeout(): JsonField = timeout + + /** + * Returns the raw JSON value of [uri]. + * + * Unlike [uri], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("uri") @ExcludeMissing fun _uri(): JsonField = uri + + @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 [Mcp]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Mcp]. */ + class Builder internal constructor() { + + private var headers: JsonField = JsonMissing.of() + private var oauth2: JsonField = JsonMissing.of() + private var retry: JsonField = JsonMissing.of() + private var secrets: JsonField = JsonMissing.of() + private var timeout: JsonField = JsonMissing.of() + private var uri: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(mcp: Mcp) = apply { + headers = mcp.headers + oauth2 = mcp.oauth2 + retry = mcp.retry + secrets = mcp.secrets + timeout = mcp.timeout + uri = mcp.uri + additionalProperties = mcp.additionalProperties.toMutableMap() + } + + fun headers(headers: Headers) = headers(JsonField.of(headers)) + + /** + * Sets [Builder.headers] to an arbitrary JSON value. + * + * You should usually call [Builder.headers] with a well-typed [Headers] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun headers(headers: JsonField) = apply { this.headers = headers } + + fun oauth2(oauth2: Oauth2) = oauth2(JsonField.of(oauth2)) + + /** + * Sets [Builder.oauth2] to an arbitrary JSON value. + * + * You should usually call [Builder.oauth2] with a well-typed [Oauth2] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun oauth2(oauth2: JsonField) = apply { this.oauth2 = oauth2 } + + fun retry(retry: Long) = retry(JsonField.of(retry)) + + /** + * Sets [Builder.retry] to an arbitrary JSON value. + * + * You should usually call [Builder.retry] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun retry(retry: JsonField) = apply { this.retry = retry } + + fun secrets(secrets: Secrets) = secrets(JsonField.of(secrets)) + + /** + * Sets [Builder.secrets] to an arbitrary JSON value. + * + * You should usually call [Builder.secrets] with a well-typed [Secrets] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun secrets(secrets: JsonField) = apply { this.secrets = secrets } + + fun timeout(timeout: Long) = timeout(JsonField.of(timeout)) + + /** + * Sets [Builder.timeout] to an arbitrary JSON value. + * + * You should usually call [Builder.timeout] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun timeout(timeout: JsonField) = apply { this.timeout = timeout } + + fun uri(uri: String) = uri(JsonField.of(uri)) + + /** + * Sets [Builder.uri] to an arbitrary JSON value. + * + * You should usually call [Builder.uri] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun uri(uri: JsonField) = apply { this.uri = uri } + + 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 [Mcp]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Mcp = + Mcp( + headers, + oauth2, + retry, + secrets, + timeout, + uri, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Mcp = apply { + if (validated) { + return@apply + } + + headers().ifPresent { it.validate() } + oauth2().ifPresent { it.validate() } + retry() + secrets().ifPresent { it.validate() } + timeout() + uri() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (headers.asKnown().getOrNull()?.validity() ?: 0) + + (oauth2.asKnown().getOrNull()?.validity() ?: 0) + + (if (retry.asKnown().isPresent) 1 else 0) + + (secrets.asKnown().getOrNull()?.validity() ?: 0) + + (if (timeout.asKnown().isPresent) 1 else 0) + + (if (uri.asKnown().isPresent) 1 else 0) + + class Headers + @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 [Headers]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Headers]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(headers: Headers) = apply { + additionalProperties = headers.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 [Headers]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Headers = Headers(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Headers = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 Headers && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Headers{additionalProperties=$additionalProperties}" + } + + class Oauth2 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val authorizationUrl: JsonField, + private val clientId: JsonField, + private val clientSecret: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("authorization_url") + @ExcludeMissing + authorizationUrl: JsonField = JsonMissing.of(), + @JsonProperty("client_id") + @ExcludeMissing + clientId: JsonField = JsonMissing.of(), + @JsonProperty("client_secret") + @ExcludeMissing + clientSecret: JsonField = JsonMissing.of(), + ) : this(authorizationUrl, clientId, clientSecret, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authorizationUrl(): Optional = + authorizationUrl.getOptional("authorization_url") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun clientId(): Optional = clientId.getOptional("client_id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun clientSecret(): Optional = clientSecret.getOptional("client_secret") + + /** + * Returns the raw JSON value of [authorizationUrl]. + * + * Unlike [authorizationUrl], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("authorization_url") + @ExcludeMissing + fun _authorizationUrl(): JsonField = authorizationUrl + + /** + * Returns the raw JSON value of [clientId]. + * + * Unlike [clientId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("client_id") @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("client_secret") + @ExcludeMissing + fun _clientSecret(): JsonField = clientSecret + + @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 [Oauth2]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Oauth2]. */ + class Builder internal constructor() { + + private var authorizationUrl: JsonField = JsonMissing.of() + private var clientId: JsonField = JsonMissing.of() + private var clientSecret: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(oauth2: Oauth2) = apply { + authorizationUrl = oauth2.authorizationUrl + clientId = oauth2.clientId + clientSecret = oauth2.clientSecret + additionalProperties = oauth2.additionalProperties.toMutableMap() + } + + fun authorizationUrl(authorizationUrl: String) = + authorizationUrl(JsonField.of(authorizationUrl)) + + /** + * Sets [Builder.authorizationUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.authorizationUrl] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun authorizationUrl(authorizationUrl: JsonField) = apply { + this.authorizationUrl = authorizationUrl + } + + 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 } + + 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 + } + + 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 [Oauth2]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Oauth2 = + Oauth2( + authorizationUrl, + clientId, + clientSecret, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Oauth2 = apply { + if (validated) { + return@apply + } + + authorizationUrl() + clientId() + clientSecret() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (authorizationUrl.asKnown().isPresent) 1 else 0) + + (if (clientId.asKnown().isPresent) 1 else 0) + + (if (clientSecret.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Oauth2 && + authorizationUrl == other.authorizationUrl && + clientId == other.clientId && + clientSecret == other.clientSecret && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(authorizationUrl, clientId, clientSecret, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Oauth2{authorizationUrl=$authorizationUrl, clientId=$clientId, clientSecret=$clientSecret, additionalProperties=$additionalProperties}" + } + + class Secrets + @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 [Secrets]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Secrets]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(secrets: Secrets) = apply { + additionalProperties = secrets.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 [Secrets]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Secrets = Secrets(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Secrets = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 Secrets && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Secrets{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Mcp && + headers == other.headers && + oauth2 == other.oauth2 && + retry == other.retry && + secrets == other.secrets && + timeout == other.timeout && + uri == other.uri && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(headers, oauth2, retry, secrets, timeout, uri, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Mcp{headers=$headers, oauth2=$oauth2, retry=$retry, secrets=$secrets, timeout=$timeout, uri=$uri, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UpdateWorkerRequest && + enabled == other.enabled && + http == other.http && + mcp == other.mcp && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(enabled, http, mcp, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "UpdateWorkerRequest{enabled=$enabled, http=$http, mcp=$mcp, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerCreateParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerCreateParams.kt similarity index 83% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerCreateParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerCreateParams.kt index c757fee..d62b616 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerCreateParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerCreateParams.kt @@ -1,9 +1,8 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.workers import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params import dev.arcade.core.checkRequired import dev.arcade.core.http.Headers @@ -23,25 +22,28 @@ private constructor( fun _additionalBodyProperties(): Map = createWorkerRequest._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): CreateWorkerRequest = createWorkerRequest - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [WorkerCreateParams]. + * + * The following fields are required: + * ```java + * .createWorkerRequest() + * ``` + */ @JvmStatic fun builder() = Builder() } /** A builder for [WorkerCreateParams]. */ - @NoAutoDetect class Builder internal constructor() { private var createWorkerRequest: CreateWorkerRequest? = null @@ -157,6 +159,18 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [WorkerCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .createWorkerRequest() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): WorkerCreateParams = WorkerCreateParams( checkRequired("createWorkerRequest", createWorkerRequest), @@ -165,15 +179,25 @@ private constructor( ) } + fun _body(): CreateWorkerRequest = createWorkerRequest + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is WorkerCreateParams && createWorkerRequest == other.createWorkerRequest && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is WorkerCreateParams && + createWorkerRequest == other.createWorkerRequest && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(createWorkerRequest, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(createWorkerRequest, additionalHeaders, additionalQueryParams) override fun toString() = "WorkerCreateParams{createWorkerRequest=$createWorkerRequest, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerDeleteParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerDeleteParams.kt similarity index 83% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerDeleteParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerDeleteParams.kt index e19c502..fddf367 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerDeleteParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerDeleteParams.kt @@ -1,58 +1,47 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.workers import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params -import dev.arcade.core.checkRequired import dev.arcade.core.http.Headers import dev.arcade.core.http.QueryParams import dev.arcade.core.toImmutable import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Delete a worker */ class WorkerDeleteParams private constructor( - private val id: String, + private val id: String?, private val additionalHeaders: Headers, private val additionalQueryParams: QueryParams, private val additionalBodyProperties: Map, ) : Params { - fun id(): String = id - - fun _additionalHeaders(): Headers = additionalHeaders - - fun _additionalQueryParams(): QueryParams = additionalQueryParams + fun id(): Optional = Optional.ofNullable(id) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties - @JvmSynthetic - internal fun _body(): Optional> = - Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders - fun getPathParam(index: Int): String { - return when (index) { - 0 -> id - else -> "" - } - } + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): WorkerDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [WorkerDeleteParams]. */ @JvmStatic fun builder() = Builder() } /** A builder for [WorkerDeleteParams]. */ - @NoAutoDetect class Builder internal constructor() { private var id: String? = null @@ -68,7 +57,10 @@ private constructor( additionalBodyProperties = workerDeleteParams.additionalBodyProperties.toMutableMap() } - fun id(id: String) = apply { this.id = id } + 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() @@ -190,24 +182,47 @@ private constructor( keys.forEach(::removeAdditionalBodyProperty) } + /** + * Returns an immutable instance of [WorkerDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): WorkerDeleteParams = WorkerDeleteParams( - checkRequired("id", id), + 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 /* spotless:off */ other is WorkerDeleteParams && id == other.id && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return other is WorkerDeleteParams && + id == other.id && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(id, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(id, additionalHeaders, additionalQueryParams, additionalBodyProperties) override fun toString() = "WorkerDeleteParams{id=$id, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerGetParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerGetParams.kt similarity index 80% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerGetParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerGetParams.kt index bb2e6af..675388b 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerGetParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerGetParams.kt @@ -1,48 +1,41 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.workers -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params -import dev.arcade.core.checkRequired import dev.arcade.core.http.Headers import dev.arcade.core.http.QueryParams import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Get a worker by ID */ class WorkerGetParams private constructor( - private val id: String, + private val id: String?, private val additionalHeaders: Headers, private val additionalQueryParams: QueryParams, ) : Params { - fun id(): String = id + 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 - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> id - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): WorkerGetParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [WorkerGetParams]. */ @JvmStatic fun builder() = Builder() } /** A builder for [WorkerGetParams]. */ - @NoAutoDetect class Builder internal constructor() { private var id: String? = null @@ -56,7 +49,10 @@ private constructor( additionalQueryParams = workerGetParams.additionalQueryParams.toBuilder() } - fun id(id: String) = apply { this.id = id } + 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() @@ -156,23 +152,37 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [WorkerGetParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): WorkerGetParams = - WorkerGetParams( - checkRequired("id", id), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + WorkerGetParams(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 /* spotless:off */ other is WorkerGetParams && id == other.id && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is WorkerGetParams && + id == other.id && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(id, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(id, additionalHeaders, additionalQueryParams) override fun toString() = "WorkerGetParams{id=$id, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerHealthParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerHealthParams.kt similarity index 80% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerHealthParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerHealthParams.kt index 98ce4eb..9e28dc6 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerHealthParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerHealthParams.kt @@ -1,48 +1,41 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.workers -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params -import dev.arcade.core.checkRequired import dev.arcade.core.http.Headers import dev.arcade.core.http.QueryParams import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Get the health of a worker */ class WorkerHealthParams private constructor( - private val id: String, + private val id: String?, private val additionalHeaders: Headers, private val additionalQueryParams: QueryParams, ) : Params { - fun id(): String = id + 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 - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> id - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): WorkerHealthParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [WorkerHealthParams]. */ @JvmStatic fun builder() = Builder() } /** A builder for [WorkerHealthParams]. */ - @NoAutoDetect class Builder internal constructor() { private var id: String? = null @@ -56,7 +49,10 @@ private constructor( additionalQueryParams = workerHealthParams.additionalQueryParams.toBuilder() } - fun id(id: String) = apply { this.id = id } + 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() @@ -156,23 +152,37 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [WorkerHealthParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): WorkerHealthParams = - WorkerHealthParams( - checkRequired("id", id), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + WorkerHealthParams(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 /* spotless:off */ other is WorkerHealthParams && id == other.id && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is WorkerHealthParams && + id == other.id && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(id, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = Objects.hash(id, additionalHeaders, additionalQueryParams) override fun toString() = "WorkerHealthParams{id=$id, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerHealthResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerHealthResponse.kt new file mode 100644 index 0000000..8a54a8c --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerHealthResponse.kt @@ -0,0 +1,247 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.workers + +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 dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional + +class WorkerHealthResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val id: JsonField, + private val enabled: JsonField, + private val healthy: JsonField, + private val message: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("enabled") @ExcludeMissing enabled: JsonField = JsonMissing.of(), + @JsonProperty("healthy") @ExcludeMissing healthy: JsonField = JsonMissing.of(), + @JsonProperty("message") @ExcludeMissing message: JsonField = JsonMissing.of(), + ) : this(id, enabled, healthy, message, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun enabled(): Optional = enabled.getOptional("enabled") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun healthy(): Optional = healthy.getOptional("healthy") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun message(): Optional = message.getOptional("message") + + /** + * 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 [enabled]. + * + * Unlike [enabled], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("enabled") @ExcludeMissing fun _enabled(): JsonField = enabled + + /** + * Returns the raw JSON value of [healthy]. + * + * Unlike [healthy], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("healthy") @ExcludeMissing fun _healthy(): JsonField = healthy + + /** + * Returns the raw JSON value of [message]. + * + * Unlike [message], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("message") @ExcludeMissing fun _message(): JsonField = message + + @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 [WorkerHealthResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [WorkerHealthResponse]. */ + class Builder internal constructor() { + + private var id: JsonField = JsonMissing.of() + private var enabled: JsonField = JsonMissing.of() + private var healthy: JsonField = JsonMissing.of() + private var message: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(workerHealthResponse: WorkerHealthResponse) = apply { + id = workerHealthResponse.id + enabled = workerHealthResponse.enabled + healthy = workerHealthResponse.healthy + message = workerHealthResponse.message + additionalProperties = workerHealthResponse.additionalProperties.toMutableMap() + } + + 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 enabled(enabled: Boolean) = enabled(JsonField.of(enabled)) + + /** + * Sets [Builder.enabled] to an arbitrary JSON value. + * + * You should usually call [Builder.enabled] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun enabled(enabled: JsonField) = apply { this.enabled = enabled } + + fun healthy(healthy: Boolean) = healthy(JsonField.of(healthy)) + + /** + * Sets [Builder.healthy] to an arbitrary JSON value. + * + * You should usually call [Builder.healthy] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun healthy(healthy: JsonField) = apply { this.healthy = healthy } + + fun message(message: String) = message(JsonField.of(message)) + + /** + * Sets [Builder.message] to an arbitrary JSON value. + * + * You should usually call [Builder.message] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun message(message: JsonField) = apply { this.message = message } + + 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 [WorkerHealthResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): WorkerHealthResponse = + WorkerHealthResponse(id, enabled, healthy, message, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): WorkerHealthResponse = apply { + if (validated) { + return@apply + } + + id() + enabled() + healthy() + message() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (enabled.asKnown().isPresent) 1 else 0) + + (if (healthy.asKnown().isPresent) 1 else 0) + + (if (message.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is WorkerHealthResponse && + id == other.id && + enabled == other.enabled && + healthy == other.healthy && + message == other.message && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(id, enabled, healthy, message, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "WorkerHealthResponse{id=$id, enabled=$enabled, healthy=$healthy, message=$message, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerListPage.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerListPage.kt new file mode 100644 index 0000000..efbe33c --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerListPage.kt @@ -0,0 +1,144 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.workers + +import dev.arcade.core.AutoPager +import dev.arcade.core.Page +import dev.arcade.core.checkRequired +import dev.arcade.services.blocking.WorkerService +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrDefault +import kotlin.jvm.optionals.getOrNull + +/** @see WorkerService.list */ +class WorkerListPage +private constructor( + private val service: WorkerService, + private val params: WorkerListParams, + private val response: WorkerListPageResponse, +) : Page { + + /** + * Delegates to [WorkerListPageResponse], but gracefully handles missing data. + * + * @see WorkerListPageResponse.items + */ + override fun items(): List = + response._items().getOptional("items").getOrNull() ?: emptyList() + + /** + * Delegates to [WorkerListPageResponse], but gracefully handles missing data. + * + * @see WorkerListPageResponse.totalCount + */ + fun totalCount(): Optional = response._totalCount().getOptional("total_count") + + /** + * Delegates to [WorkerListPageResponse], but gracefully handles missing data. + * + * @see WorkerListPageResponse.offset + */ + fun offset(): Optional = response._offset().getOptional("offset") + + override fun hasNextPage(): Boolean { + if (items().isEmpty()) { + return false + } + + val offset = offset().getOrDefault(0) + val totalCount = totalCount().getOrNull() + return totalCount == null || offset + items().size < totalCount + } + + fun nextPageParams(): WorkerListParams { + val offset = offset().getOrDefault(0) + return params.toBuilder().offset(offset + items().size).build() + } + + override fun nextPage(): WorkerListPage = service.list(nextPageParams()) + + fun autoPager(): AutoPager = AutoPager.from(this) + + /** The parameters that were used to request this page. */ + fun params(): WorkerListParams = params + + /** The response that this page was parsed from. */ + fun response(): WorkerListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [WorkerListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [WorkerListPage]. */ + class Builder internal constructor() { + + private var service: WorkerService? = null + private var params: WorkerListParams? = null + private var response: WorkerListPageResponse? = null + + @JvmSynthetic + internal fun from(workerListPage: WorkerListPage) = apply { + service = workerListPage.service + params = workerListPage.params + response = workerListPage.response + } + + fun service(service: WorkerService) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: WorkerListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: WorkerListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [WorkerListPage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): WorkerListPage = + WorkerListPage( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is WorkerListPage && + service == other.service && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, params, response) + + override fun toString() = "WorkerListPage{service=$service, params=$params, response=$response}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerListPageAsync.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerListPageAsync.kt new file mode 100644 index 0000000..9c0d80d --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerListPageAsync.kt @@ -0,0 +1,159 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.workers + +import dev.arcade.core.AutoPagerAsync +import dev.arcade.core.PageAsync +import dev.arcade.core.checkRequired +import dev.arcade.services.async.WorkerServiceAsync +import java.util.Objects +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import kotlin.jvm.optionals.getOrDefault +import kotlin.jvm.optionals.getOrNull + +/** @see WorkerServiceAsync.list */ +class WorkerListPageAsync +private constructor( + private val service: WorkerServiceAsync, + private val streamHandlerExecutor: Executor, + private val params: WorkerListParams, + private val response: WorkerListPageResponse, +) : PageAsync { + + /** + * Delegates to [WorkerListPageResponse], but gracefully handles missing data. + * + * @see WorkerListPageResponse.items + */ + override fun items(): List = + response._items().getOptional("items").getOrNull() ?: emptyList() + + /** + * Delegates to [WorkerListPageResponse], but gracefully handles missing data. + * + * @see WorkerListPageResponse.totalCount + */ + fun totalCount(): Optional = response._totalCount().getOptional("total_count") + + /** + * Delegates to [WorkerListPageResponse], but gracefully handles missing data. + * + * @see WorkerListPageResponse.offset + */ + fun offset(): Optional = response._offset().getOptional("offset") + + override fun hasNextPage(): Boolean { + if (items().isEmpty()) { + return false + } + + val offset = offset().getOrDefault(0) + val totalCount = totalCount().getOrNull() + return totalCount == null || offset + items().size < totalCount + } + + fun nextPageParams(): WorkerListParams { + val offset = offset().getOrDefault(0) + return params.toBuilder().offset(offset + items().size).build() + } + + override fun nextPage(): CompletableFuture = service.list(nextPageParams()) + + fun autoPager(): AutoPagerAsync = + AutoPagerAsync.from(this, streamHandlerExecutor) + + /** The parameters that were used to request this page. */ + fun params(): WorkerListParams = params + + /** The response that this page was parsed from. */ + fun response(): WorkerListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [WorkerListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [WorkerListPageAsync]. */ + class Builder internal constructor() { + + private var service: WorkerServiceAsync? = null + private var streamHandlerExecutor: Executor? = null + private var params: WorkerListParams? = null + private var response: WorkerListPageResponse? = null + + @JvmSynthetic + internal fun from(workerListPageAsync: WorkerListPageAsync) = apply { + service = workerListPageAsync.service + streamHandlerExecutor = workerListPageAsync.streamHandlerExecutor + params = workerListPageAsync.params + response = workerListPageAsync.response + } + + fun service(service: WorkerServiceAsync) = apply { this.service = service } + + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + this.streamHandlerExecutor = streamHandlerExecutor + } + + /** The parameters that were used to request this page. */ + fun params(params: WorkerListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: WorkerListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [WorkerListPageAsync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): WorkerListPageAsync = + WorkerListPageAsync( + checkRequired("service", service), + checkRequired("streamHandlerExecutor", streamHandlerExecutor), + checkRequired("params", params), + checkRequired("response", response), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is WorkerListPageAsync && + service == other.service && + streamHandlerExecutor == other.streamHandlerExecutor && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, streamHandlerExecutor, params, response) + + override fun toString() = + "WorkerListPageAsync{service=$service, streamHandlerExecutor=$streamHandlerExecutor, params=$params, response=$response}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerListPageResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerListPageResponse.kt new file mode 100644 index 0000000..8609944 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerListPageResponse.kt @@ -0,0 +1,302 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.workers + +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 dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.core.checkKnown +import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class WorkerListPageResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val items: JsonField>, + private val limit: JsonField, + private val offset: JsonField, + private val pageCount: JsonField, + private val totalCount: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("items") + @ExcludeMissing + items: JsonField> = JsonMissing.of(), + @JsonProperty("limit") @ExcludeMissing limit: JsonField = JsonMissing.of(), + @JsonProperty("offset") @ExcludeMissing offset: JsonField = JsonMissing.of(), + @JsonProperty("page_count") @ExcludeMissing pageCount: JsonField = JsonMissing.of(), + @JsonProperty("total_count") @ExcludeMissing totalCount: JsonField = JsonMissing.of(), + ) : this(items, limit, offset, pageCount, totalCount, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun items(): Optional> = items.getOptional("items") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun limit(): Optional = limit.getOptional("limit") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun offset(): Optional = offset.getOptional("offset") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun pageCount(): Optional = pageCount.getOptional("page_count") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun totalCount(): Optional = totalCount.getOptional("total_count") + + /** + * Returns the raw JSON value of [items]. + * + * Unlike [items], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("items") @ExcludeMissing fun _items(): JsonField> = items + + /** + * Returns the raw JSON value of [limit]. + * + * Unlike [limit], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("limit") @ExcludeMissing fun _limit(): JsonField = limit + + /** + * Returns the raw JSON value of [offset]. + * + * Unlike [offset], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("offset") @ExcludeMissing fun _offset(): JsonField = offset + + /** + * Returns the raw JSON value of [pageCount]. + * + * Unlike [pageCount], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("page_count") @ExcludeMissing fun _pageCount(): JsonField = pageCount + + /** + * Returns the raw JSON value of [totalCount]. + * + * Unlike [totalCount], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("total_count") @ExcludeMissing fun _totalCount(): JsonField = totalCount + + @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 [WorkerListPageResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [WorkerListPageResponse]. */ + class Builder internal constructor() { + + private var items: JsonField>? = null + private var limit: JsonField = JsonMissing.of() + private var offset: JsonField = JsonMissing.of() + private var pageCount: JsonField = JsonMissing.of() + private var totalCount: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(workerListPageResponse: WorkerListPageResponse) = apply { + items = workerListPageResponse.items.map { it.toMutableList() } + limit = workerListPageResponse.limit + offset = workerListPageResponse.offset + pageCount = workerListPageResponse.pageCount + totalCount = workerListPageResponse.totalCount + additionalProperties = workerListPageResponse.additionalProperties.toMutableMap() + } + + fun items(items: List) = items(JsonField.of(items)) + + /** + * Sets [Builder.items] to an arbitrary JSON value. + * + * You should usually call [Builder.items] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun items(items: JsonField>) = apply { + this.items = items.map { it.toMutableList() } + } + + /** + * Adds a single [WorkerResponse] to [items]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addItem(item: WorkerResponse) = apply { + items = + (items ?: JsonField.of(mutableListOf())).also { checkKnown("items", it).add(item) } + } + + fun limit(limit: Long) = limit(JsonField.of(limit)) + + /** + * Sets [Builder.limit] to an arbitrary JSON value. + * + * You should usually call [Builder.limit] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun limit(limit: JsonField) = apply { this.limit = limit } + + fun offset(offset: Long) = offset(JsonField.of(offset)) + + /** + * Sets [Builder.offset] to an arbitrary JSON value. + * + * You should usually call [Builder.offset] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun offset(offset: JsonField) = apply { this.offset = offset } + + fun pageCount(pageCount: Long) = pageCount(JsonField.of(pageCount)) + + /** + * Sets [Builder.pageCount] to an arbitrary JSON value. + * + * You should usually call [Builder.pageCount] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun pageCount(pageCount: JsonField) = apply { this.pageCount = pageCount } + + fun totalCount(totalCount: Long) = totalCount(JsonField.of(totalCount)) + + /** + * Sets [Builder.totalCount] to an arbitrary JSON value. + * + * You should usually call [Builder.totalCount] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun totalCount(totalCount: JsonField) = apply { this.totalCount = totalCount } + + 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 [WorkerListPageResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): WorkerListPageResponse = + WorkerListPageResponse( + (items ?: JsonMissing.of()).map { it.toImmutable() }, + limit, + offset, + pageCount, + totalCount, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): WorkerListPageResponse = apply { + if (validated) { + return@apply + } + + items().ifPresent { it.forEach { it.validate() } } + limit() + offset() + pageCount() + totalCount() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (items.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (limit.asKnown().isPresent) 1 else 0) + + (if (offset.asKnown().isPresent) 1 else 0) + + (if (pageCount.asKnown().isPresent) 1 else 0) + + (if (totalCount.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is WorkerListPageResponse && + items == other.items && + limit == other.limit && + offset == other.offset && + pageCount == other.pageCount && + totalCount == other.totalCount && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(items, limit, offset, pageCount, totalCount, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "WorkerListPageResponse{items=$items, limit=$limit, offset=$offset, pageCount=$pageCount, totalCount=$totalCount, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerListParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerListParams.kt similarity index 78% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerListParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerListParams.kt index 201517a..e017603 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerListParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerListParams.kt @@ -1,13 +1,13 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.workers -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params import dev.arcade.core.http.Headers import dev.arcade.core.http.QueryParams import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** List all workers with their definitions */ class WorkerListParams @@ -24,29 +24,23 @@ private constructor( /** Offset from the start of the list (default: 0) */ fun offset(): Optional = Optional.ofNullable(offset) + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams { - val queryParams = QueryParams.builder() - this.limit?.let { queryParams.put("limit", listOf(it.toString())) } - this.offset?.let { queryParams.put("offset", listOf(it.toString())) } - queryParams.putAll(additionalQueryParams) - return queryParams.build() - } - fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): WorkerListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [WorkerListParams]. */ @JvmStatic fun builder() = Builder() } /** A builder for [WorkerListParams]. */ - @NoAutoDetect class Builder internal constructor() { private var limit: Long? = null @@ -65,22 +59,28 @@ private constructor( /** Number of items to return (default: 25, max: 100) */ fun limit(limit: Long?) = apply { this.limit = limit } - /** Number of items to return (default: 25, max: 100) */ + /** + * Alias for [Builder.limit]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun limit(limit: Long) = limit(limit as Long?) - /** Number of items to return (default: 25, max: 100) */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun limit(limit: Optional) = limit(limit.orElse(null) as Long?) + /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ + fun limit(limit: Optional) = limit(limit.getOrNull()) /** Offset from the start of the list (default: 0) */ fun offset(offset: Long?) = apply { this.offset = offset } - /** Offset from the start of the list (default: 0) */ + /** + * Alias for [Builder.offset]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun offset(offset: Long) = offset(offset as Long?) - /** Offset from the start of the list (default: 0) */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun offset(offset: Optional) = offset(offset.orElse(null) as Long?) + /** Alias for calling [Builder.offset] with `offset.orElse(null)`. */ + fun offset(offset: Optional) = offset(offset.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -180,6 +180,11 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [WorkerListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): WorkerListParams = WorkerListParams( limit, @@ -189,15 +194,31 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + limit?.let { put("limit", it.toString()) } + offset?.let { put("offset", it.toString()) } + putAll(additionalQueryParams) + } + .build() + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is WorkerListParams && limit == other.limit && offset == other.offset && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is WorkerListParams && + limit == other.limit && + offset == other.offset && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(limit, offset, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(limit, offset, additionalHeaders, additionalQueryParams) override fun toString() = "WorkerListParams{limit=$limit, offset=$offset, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerResponse.kt new file mode 100644 index 0000000..51843b5 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerResponse.kt @@ -0,0 +1,3256 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.workers + +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 dev.arcade.core.Enum +import dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.core.checkKnown +import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class WorkerResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val id: JsonField, + private val binding: JsonField, + private val enabled: JsonField, + private val http: JsonField, + private val managed: JsonField, + private val mcp: JsonField, + private val requirements: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("binding") @ExcludeMissing binding: JsonField = JsonMissing.of(), + @JsonProperty("enabled") @ExcludeMissing enabled: JsonField = JsonMissing.of(), + @JsonProperty("http") @ExcludeMissing http: JsonField = JsonMissing.of(), + @JsonProperty("managed") @ExcludeMissing managed: JsonField = JsonMissing.of(), + @JsonProperty("mcp") @ExcludeMissing mcp: JsonField = JsonMissing.of(), + @JsonProperty("requirements") + @ExcludeMissing + requirements: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(id, binding, enabled, http, managed, mcp, requirements, type, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun binding(): Optional = binding.getOptional("binding") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun enabled(): Optional = enabled.getOptional("enabled") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun http(): Optional = http.getOptional("http") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun managed(): Optional = managed.getOptional("managed") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun mcp(): Optional = mcp.getOptional("mcp") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun requirements(): Optional = requirements.getOptional("requirements") + + /** + * @throws ArcadeInvalidDataException 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 [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 [binding]. + * + * Unlike [binding], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("binding") @ExcludeMissing fun _binding(): JsonField = binding + + /** + * Returns the raw JSON value of [enabled]. + * + * Unlike [enabled], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("enabled") @ExcludeMissing fun _enabled(): JsonField = enabled + + /** + * Returns the raw JSON value of [http]. + * + * Unlike [http], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("http") @ExcludeMissing fun _http(): JsonField = http + + /** + * Returns the raw JSON value of [managed]. + * + * Unlike [managed], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("managed") @ExcludeMissing fun _managed(): JsonField = managed + + /** + * Returns the raw JSON value of [mcp]. + * + * Unlike [mcp], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("mcp") @ExcludeMissing fun _mcp(): JsonField = mcp + + /** + * Returns the raw JSON value of [requirements]. + * + * Unlike [requirements], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("requirements") + @ExcludeMissing + fun _requirements(): JsonField = requirements + + /** + * 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 [WorkerResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [WorkerResponse]. */ + class Builder internal constructor() { + + private var id: JsonField = JsonMissing.of() + private var binding: JsonField = JsonMissing.of() + private var enabled: JsonField = JsonMissing.of() + private var http: JsonField = JsonMissing.of() + private var managed: JsonField = JsonMissing.of() + private var mcp: JsonField = JsonMissing.of() + private var requirements: JsonField = JsonMissing.of() + private var type: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(workerResponse: WorkerResponse) = apply { + id = workerResponse.id + binding = workerResponse.binding + enabled = workerResponse.enabled + http = workerResponse.http + managed = workerResponse.managed + mcp = workerResponse.mcp + requirements = workerResponse.requirements + type = workerResponse.type + additionalProperties = workerResponse.additionalProperties.toMutableMap() + } + + 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 binding(binding: Binding) = binding(JsonField.of(binding)) + + /** + * Sets [Builder.binding] to an arbitrary JSON value. + * + * You should usually call [Builder.binding] with a well-typed [Binding] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun binding(binding: JsonField) = apply { this.binding = binding } + + fun enabled(enabled: Boolean) = enabled(JsonField.of(enabled)) + + /** + * Sets [Builder.enabled] to an arbitrary JSON value. + * + * You should usually call [Builder.enabled] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun enabled(enabled: JsonField) = apply { this.enabled = enabled } + + fun http(http: Http) = http(JsonField.of(http)) + + /** + * Sets [Builder.http] to an arbitrary JSON value. + * + * You should usually call [Builder.http] with a well-typed [Http] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun http(http: JsonField) = apply { this.http = http } + + fun managed(managed: Boolean) = managed(JsonField.of(managed)) + + /** + * Sets [Builder.managed] to an arbitrary JSON value. + * + * You should usually call [Builder.managed] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun managed(managed: JsonField) = apply { this.managed = managed } + + fun mcp(mcp: Mcp) = mcp(JsonField.of(mcp)) + + /** + * Sets [Builder.mcp] to an arbitrary JSON value. + * + * You should usually call [Builder.mcp] with a well-typed [Mcp] value instead. This method + * is primarily for setting the field to an undocumented or not yet supported value. + */ + fun mcp(mcp: JsonField) = apply { this.mcp = mcp } + + fun requirements(requirements: Requirements) = requirements(JsonField.of(requirements)) + + /** + * Sets [Builder.requirements] to an arbitrary JSON value. + * + * You should usually call [Builder.requirements] with a well-typed [Requirements] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun requirements(requirements: JsonField) = apply { + this.requirements = requirements + } + + 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 [WorkerResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): WorkerResponse = + WorkerResponse( + id, + binding, + enabled, + http, + managed, + mcp, + requirements, + type, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): WorkerResponse = apply { + if (validated) { + return@apply + } + + id() + binding().ifPresent { it.validate() } + enabled() + http().ifPresent { it.validate() } + managed() + mcp().ifPresent { it.validate() } + requirements().ifPresent { it.validate() } + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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) + + (binding.asKnown().getOrNull()?.validity() ?: 0) + + (if (enabled.asKnown().isPresent) 1 else 0) + + (http.asKnown().getOrNull()?.validity() ?: 0) + + (if (managed.asKnown().isPresent) 1 else 0) + + (mcp.asKnown().getOrNull()?.validity() ?: 0) + + (requirements.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + + class Binding + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws ArcadeInvalidDataException 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 [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 [Binding]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Binding]. */ + class Builder internal constructor() { + + private var id: JsonField = JsonMissing.of() + private var type: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(binding: Binding) = apply { + id = binding.id + type = binding.type + additionalProperties = binding.additionalProperties.toMutableMap() + } + + 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 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 [Binding]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Binding = Binding(id, type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Binding = apply { + if (validated) { + return@apply + } + + id() + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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) + (type.asKnown().getOrNull()?.validity() ?: 0) + + 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 STATIC = of("static") + + @JvmField val TENANT = of("tenant") + + @JvmField val PROJECT = of("project") + + @JvmField val ACCOUNT = of("account") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + STATIC, + TENANT, + PROJECT, + ACCOUNT, + } + + /** + * 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 { + STATIC, + TENANT, + PROJECT, + ACCOUNT, + /** 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) { + STATIC -> Value.STATIC + TENANT -> Value.TENANT + PROJECT -> Value.PROJECT + ACCOUNT -> Value.ACCOUNT + 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 ArcadeInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + STATIC -> Known.STATIC + TENANT -> Known.TENANT + PROJECT -> Known.PROJECT + ACCOUNT -> Known.ACCOUNT + else -> throw ArcadeInvalidDataException("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 ArcadeInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ArcadeInvalidDataException("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: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 Binding && + 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() = + "Binding{id=$id, type=$type, additionalProperties=$additionalProperties}" + } + + class Http + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val retry: JsonField, + private val secret: JsonField, + private val timeout: JsonField, + private val uri: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("retry") @ExcludeMissing retry: JsonField = JsonMissing.of(), + @JsonProperty("secret") @ExcludeMissing secret: JsonField = JsonMissing.of(), + @JsonProperty("timeout") @ExcludeMissing timeout: JsonField = JsonMissing.of(), + @JsonProperty("uri") @ExcludeMissing uri: JsonField = JsonMissing.of(), + ) : this(retry, secret, timeout, uri, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun retry(): Optional = retry.getOptional("retry") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun secret(): Optional = secret.getOptional("secret") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun timeout(): Optional = timeout.getOptional("timeout") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun uri(): Optional = uri.getOptional("uri") + + /** + * Returns the raw JSON value of [retry]. + * + * Unlike [retry], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("retry") @ExcludeMissing fun _retry(): JsonField = retry + + /** + * Returns the raw JSON value of [secret]. + * + * Unlike [secret], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("secret") @ExcludeMissing fun _secret(): JsonField = secret + + /** + * Returns the raw JSON value of [timeout]. + * + * Unlike [timeout], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("timeout") @ExcludeMissing fun _timeout(): JsonField = timeout + + /** + * Returns the raw JSON value of [uri]. + * + * Unlike [uri], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("uri") @ExcludeMissing fun _uri(): JsonField = uri + + @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 [Http]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Http]. */ + class Builder internal constructor() { + + private var retry: JsonField = JsonMissing.of() + private var secret: JsonField = JsonMissing.of() + private var timeout: JsonField = JsonMissing.of() + private var uri: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(http: Http) = apply { + retry = http.retry + secret = http.secret + timeout = http.timeout + uri = http.uri + additionalProperties = http.additionalProperties.toMutableMap() + } + + fun retry(retry: Long) = retry(JsonField.of(retry)) + + /** + * Sets [Builder.retry] to an arbitrary JSON value. + * + * You should usually call [Builder.retry] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun retry(retry: JsonField) = apply { this.retry = retry } + + fun secret(secret: Secret) = secret(JsonField.of(secret)) + + /** + * Sets [Builder.secret] to an arbitrary JSON value. + * + * You should usually call [Builder.secret] with a well-typed [Secret] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun secret(secret: JsonField) = apply { this.secret = secret } + + fun timeout(timeout: Long) = timeout(JsonField.of(timeout)) + + /** + * Sets [Builder.timeout] to an arbitrary JSON value. + * + * You should usually call [Builder.timeout] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun timeout(timeout: JsonField) = apply { this.timeout = timeout } + + fun uri(uri: String) = uri(JsonField.of(uri)) + + /** + * Sets [Builder.uri] to an arbitrary JSON value. + * + * You should usually call [Builder.uri] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun uri(uri: JsonField) = apply { this.uri = uri } + + 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 [Http]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Http = + Http(retry, secret, timeout, uri, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Http = apply { + if (validated) { + return@apply + } + + retry() + secret().ifPresent { it.validate() } + timeout() + uri() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (retry.asKnown().isPresent) 1 else 0) + + (secret.asKnown().getOrNull()?.validity() ?: 0) + + (if (timeout.asKnown().isPresent) 1 else 0) + + (if (uri.asKnown().isPresent) 1 else 0) + + class Secret + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val binding: JsonField, + private val editable: JsonField, + private val exists: JsonField, + private val value: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("binding") + @ExcludeMissing + binding: JsonField = JsonMissing.of(), + @JsonProperty("editable") + @ExcludeMissing + editable: JsonField = JsonMissing.of(), + @JsonProperty("exists") + @ExcludeMissing + exists: JsonField = JsonMissing.of(), + @JsonProperty("value") @ExcludeMissing value: JsonField = JsonMissing.of(), + ) : this(binding, editable, exists, value, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun binding(): Optional = binding.getOptional("binding") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun editable(): Optional = editable.getOptional("editable") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun exists(): Optional = exists.getOptional("exists") + + /** + * @throws ArcadeInvalidDataException 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 [binding]. + * + * Unlike [binding], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("binding") @ExcludeMissing fun _binding(): JsonField = binding + + /** + * Returns the raw JSON value of [editable]. + * + * Unlike [editable], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("editable") @ExcludeMissing fun _editable(): JsonField = editable + + /** + * Returns the raw JSON value of [exists]. + * + * Unlike [exists], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("exists") @ExcludeMissing fun _exists(): JsonField = exists + + /** + * 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 [Secret]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Secret]. */ + class Builder internal constructor() { + + private var binding: JsonField = JsonMissing.of() + private var editable: JsonField = JsonMissing.of() + private var exists: JsonField = JsonMissing.of() + private var value: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(secret: Secret) = apply { + binding = secret.binding + editable = secret.editable + exists = secret.exists + value = secret.value + additionalProperties = secret.additionalProperties.toMutableMap() + } + + fun binding(binding: Binding) = binding(JsonField.of(binding)) + + /** + * Sets [Builder.binding] to an arbitrary JSON value. + * + * You should usually call [Builder.binding] with a well-typed [Binding] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun binding(binding: JsonField) = apply { this.binding = binding } + + fun editable(editable: Boolean) = editable(JsonField.of(editable)) + + /** + * Sets [Builder.editable] to an arbitrary JSON value. + * + * You should usually call [Builder.editable] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun editable(editable: JsonField) = apply { this.editable = editable } + + fun exists(exists: Boolean) = exists(JsonField.of(exists)) + + /** + * Sets [Builder.exists] to an arbitrary JSON value. + * + * You should usually call [Builder.exists] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun exists(exists: JsonField) = apply { this.exists = exists } + + 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 [Secret]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Secret = + Secret(binding, editable, exists, value, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Secret = apply { + if (validated) { + return@apply + } + + binding().ifPresent { it.validate() } + editable() + exists() + value() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (binding.asKnown().getOrNull()?.validity() ?: 0) + + (if (editable.asKnown().isPresent) 1 else 0) + + (if (exists.asKnown().isPresent) 1 else 0) + + (if (value.asKnown().isPresent) 1 else 0) + + class Binding @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 STATIC = of("static") + + @JvmField val TENANT = of("tenant") + + @JvmField val PROJECT = of("project") + + @JvmField val ACCOUNT = of("account") + + @JvmStatic fun of(value: String) = Binding(JsonField.of(value)) + } + + /** An enum containing [Binding]'s known values. */ + enum class Known { + STATIC, + TENANT, + PROJECT, + ACCOUNT, + } + + /** + * An enum containing [Binding]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Binding] 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 { + STATIC, + TENANT, + PROJECT, + ACCOUNT, + /** + * An enum member indicating that [Binding] 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) { + STATIC -> Value.STATIC + TENANT -> Value.TENANT + PROJECT -> Value.PROJECT + ACCOUNT -> Value.ACCOUNT + 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 ArcadeInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + STATIC -> Known.STATIC + TENANT -> Known.TENANT + PROJECT -> Known.PROJECT + ACCOUNT -> Known.ACCOUNT + else -> throw ArcadeInvalidDataException("Unknown Binding: $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 ArcadeInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ArcadeInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Binding = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 Binding && 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 Secret && + binding == other.binding && + editable == other.editable && + exists == other.exists && + value == other.value && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(binding, editable, exists, value, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Secret{binding=$binding, editable=$editable, exists=$exists, value=$value, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Http && + retry == other.retry && + secret == other.secret && + timeout == other.timeout && + uri == other.uri && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(retry, secret, timeout, uri, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Http{retry=$retry, secret=$secret, timeout=$timeout, uri=$uri, additionalProperties=$additionalProperties}" + } + + class Mcp + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val headers: JsonField, + private val oauth2: JsonField, + private val retry: JsonField, + private val secrets: JsonField, + private val timeout: JsonField, + private val uri: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("headers") @ExcludeMissing headers: JsonField = JsonMissing.of(), + @JsonProperty("oauth2") @ExcludeMissing oauth2: JsonField = JsonMissing.of(), + @JsonProperty("retry") @ExcludeMissing retry: JsonField = JsonMissing.of(), + @JsonProperty("secrets") @ExcludeMissing secrets: JsonField = JsonMissing.of(), + @JsonProperty("timeout") @ExcludeMissing timeout: JsonField = JsonMissing.of(), + @JsonProperty("uri") @ExcludeMissing uri: JsonField = JsonMissing.of(), + ) : this(headers, oauth2, retry, secrets, timeout, uri, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun headers(): Optional = headers.getOptional("headers") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun oauth2(): Optional = oauth2.getOptional("oauth2") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun retry(): Optional = retry.getOptional("retry") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun secrets(): Optional = secrets.getOptional("secrets") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun timeout(): Optional = timeout.getOptional("timeout") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun uri(): Optional = uri.getOptional("uri") + + /** + * Returns the raw JSON value of [headers]. + * + * Unlike [headers], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("headers") @ExcludeMissing fun _headers(): JsonField = headers + + /** + * Returns the raw JSON value of [oauth2]. + * + * Unlike [oauth2], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("oauth2") @ExcludeMissing fun _oauth2(): JsonField = oauth2 + + /** + * Returns the raw JSON value of [retry]. + * + * Unlike [retry], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("retry") @ExcludeMissing fun _retry(): JsonField = retry + + /** + * Returns the raw JSON value of [secrets]. + * + * Unlike [secrets], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("secrets") @ExcludeMissing fun _secrets(): JsonField = secrets + + /** + * Returns the raw JSON value of [timeout]. + * + * Unlike [timeout], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("timeout") @ExcludeMissing fun _timeout(): JsonField = timeout + + /** + * Returns the raw JSON value of [uri]. + * + * Unlike [uri], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("uri") @ExcludeMissing fun _uri(): JsonField = uri + + @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 [Mcp]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Mcp]. */ + class Builder internal constructor() { + + private var headers: JsonField = JsonMissing.of() + private var oauth2: JsonField = JsonMissing.of() + private var retry: JsonField = JsonMissing.of() + private var secrets: JsonField = JsonMissing.of() + private var timeout: JsonField = JsonMissing.of() + private var uri: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(mcp: Mcp) = apply { + headers = mcp.headers + oauth2 = mcp.oauth2 + retry = mcp.retry + secrets = mcp.secrets + timeout = mcp.timeout + uri = mcp.uri + additionalProperties = mcp.additionalProperties.toMutableMap() + } + + fun headers(headers: Headers) = headers(JsonField.of(headers)) + + /** + * Sets [Builder.headers] to an arbitrary JSON value. + * + * You should usually call [Builder.headers] with a well-typed [Headers] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun headers(headers: JsonField) = apply { this.headers = headers } + + fun oauth2(oauth2: Oauth2) = oauth2(JsonField.of(oauth2)) + + /** + * Sets [Builder.oauth2] to an arbitrary JSON value. + * + * You should usually call [Builder.oauth2] with a well-typed [Oauth2] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun oauth2(oauth2: JsonField) = apply { this.oauth2 = oauth2 } + + fun retry(retry: Long) = retry(JsonField.of(retry)) + + /** + * Sets [Builder.retry] to an arbitrary JSON value. + * + * You should usually call [Builder.retry] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun retry(retry: JsonField) = apply { this.retry = retry } + + fun secrets(secrets: Secrets) = secrets(JsonField.of(secrets)) + + /** + * Sets [Builder.secrets] to an arbitrary JSON value. + * + * You should usually call [Builder.secrets] with a well-typed [Secrets] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun secrets(secrets: JsonField) = apply { this.secrets = secrets } + + fun timeout(timeout: Long) = timeout(JsonField.of(timeout)) + + /** + * Sets [Builder.timeout] to an arbitrary JSON value. + * + * You should usually call [Builder.timeout] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun timeout(timeout: JsonField) = apply { this.timeout = timeout } + + fun uri(uri: String) = uri(JsonField.of(uri)) + + /** + * Sets [Builder.uri] to an arbitrary JSON value. + * + * You should usually call [Builder.uri] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun uri(uri: JsonField) = apply { this.uri = uri } + + 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 [Mcp]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Mcp = + Mcp( + headers, + oauth2, + retry, + secrets, + timeout, + uri, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Mcp = apply { + if (validated) { + return@apply + } + + headers().ifPresent { it.validate() } + oauth2().ifPresent { it.validate() } + retry() + secrets().ifPresent { it.validate() } + timeout() + uri() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (headers.asKnown().getOrNull()?.validity() ?: 0) + + (oauth2.asKnown().getOrNull()?.validity() ?: 0) + + (if (retry.asKnown().isPresent) 1 else 0) + + (secrets.asKnown().getOrNull()?.validity() ?: 0) + + (if (timeout.asKnown().isPresent) 1 else 0) + + (if (uri.asKnown().isPresent) 1 else 0) + + class Headers + @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 [Headers]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Headers]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(headers: Headers) = apply { + additionalProperties = headers.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 [Headers]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Headers = Headers(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Headers = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 Headers && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Headers{additionalProperties=$additionalProperties}" + } + + class Oauth2 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val authorizationUrl: JsonField, + private val clientId: JsonField, + private val clientSecret: JsonField, + private val externalId: JsonField, + private val redirectUri: JsonField, + private val supportedScopes: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("authorization_url") + @ExcludeMissing + authorizationUrl: JsonField = JsonMissing.of(), + @JsonProperty("client_id") + @ExcludeMissing + clientId: JsonField = JsonMissing.of(), + @JsonProperty("client_secret") + @ExcludeMissing + clientSecret: JsonField = JsonMissing.of(), + @JsonProperty("external_id") + @ExcludeMissing + externalId: JsonField = JsonMissing.of(), + @JsonProperty("redirect_uri") + @ExcludeMissing + redirectUri: JsonField = JsonMissing.of(), + @JsonProperty("supported_scopes") + @ExcludeMissing + supportedScopes: JsonField> = JsonMissing.of(), + ) : this( + authorizationUrl, + clientId, + clientSecret, + externalId, + redirectUri, + supportedScopes, + mutableMapOf(), + ) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun authorizationUrl(): Optional = + authorizationUrl.getOptional("authorization_url") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun clientId(): Optional = clientId.getOptional("client_id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun clientSecret(): Optional = clientSecret.getOptional("client_secret") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun externalId(): Optional = externalId.getOptional("external_id") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun redirectUri(): Optional = redirectUri.getOptional("redirect_uri") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun supportedScopes(): Optional> = + supportedScopes.getOptional("supported_scopes") + + /** + * Returns the raw JSON value of [authorizationUrl]. + * + * Unlike [authorizationUrl], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("authorization_url") + @ExcludeMissing + fun _authorizationUrl(): JsonField = authorizationUrl + + /** + * Returns the raw JSON value of [clientId]. + * + * Unlike [clientId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("client_id") @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("client_secret") + @ExcludeMissing + fun _clientSecret(): JsonField = clientSecret + + /** + * Returns the raw JSON value of [externalId]. + * + * Unlike [externalId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("external_id") + @ExcludeMissing + fun _externalId(): JsonField = externalId + + /** + * Returns the raw JSON value of [redirectUri]. + * + * Unlike [redirectUri], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("redirect_uri") + @ExcludeMissing + fun _redirectUri(): JsonField = redirectUri + + /** + * Returns the raw JSON value of [supportedScopes]. + * + * Unlike [supportedScopes], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("supported_scopes") + @ExcludeMissing + fun _supportedScopes(): JsonField> = supportedScopes + + @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 [Oauth2]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Oauth2]. */ + class Builder internal constructor() { + + private var authorizationUrl: JsonField = JsonMissing.of() + private var clientId: JsonField = JsonMissing.of() + private var clientSecret: JsonField = JsonMissing.of() + private var externalId: JsonField = JsonMissing.of() + private var redirectUri: JsonField = JsonMissing.of() + private var supportedScopes: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(oauth2: Oauth2) = apply { + authorizationUrl = oauth2.authorizationUrl + clientId = oauth2.clientId + clientSecret = oauth2.clientSecret + externalId = oauth2.externalId + redirectUri = oauth2.redirectUri + supportedScopes = oauth2.supportedScopes.map { it.toMutableList() } + additionalProperties = oauth2.additionalProperties.toMutableMap() + } + + fun authorizationUrl(authorizationUrl: String) = + authorizationUrl(JsonField.of(authorizationUrl)) + + /** + * Sets [Builder.authorizationUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.authorizationUrl] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun authorizationUrl(authorizationUrl: JsonField) = apply { + this.authorizationUrl = authorizationUrl + } + + 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 } + + fun clientSecret(clientSecret: ClientSecret) = + clientSecret(JsonField.of(clientSecret)) + + /** + * Sets [Builder.clientSecret] to an arbitrary JSON value. + * + * You should usually call [Builder.clientSecret] with a well-typed [ClientSecret] + * 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 + } + + fun externalId(externalId: String) = externalId(JsonField.of(externalId)) + + /** + * Sets [Builder.externalId] to an arbitrary JSON value. + * + * You should usually call [Builder.externalId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun externalId(externalId: JsonField) = apply { + this.externalId = externalId + } + + fun redirectUri(redirectUri: String) = redirectUri(JsonField.of(redirectUri)) + + /** + * Sets [Builder.redirectUri] to an arbitrary JSON value. + * + * You should usually call [Builder.redirectUri] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun redirectUri(redirectUri: JsonField) = apply { + this.redirectUri = redirectUri + } + + fun supportedScopes(supportedScopes: List) = + supportedScopes(JsonField.of(supportedScopes)) + + /** + * Sets [Builder.supportedScopes] to an arbitrary JSON value. + * + * You should usually call [Builder.supportedScopes] with a well-typed + * `List` value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun supportedScopes(supportedScopes: JsonField>) = apply { + this.supportedScopes = supportedScopes.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [supportedScopes]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addSupportedScope(supportedScope: String) = apply { + supportedScopes = + (supportedScopes ?: JsonField.of(mutableListOf())).also { + checkKnown("supportedScopes", it).add(supportedScope) + } + } + + 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 [Oauth2]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Oauth2 = + Oauth2( + authorizationUrl, + clientId, + clientSecret, + externalId, + redirectUri, + (supportedScopes ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Oauth2 = apply { + if (validated) { + return@apply + } + + authorizationUrl() + clientId() + clientSecret().ifPresent { it.validate() } + externalId() + redirectUri() + supportedScopes() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (authorizationUrl.asKnown().isPresent) 1 else 0) + + (if (clientId.asKnown().isPresent) 1 else 0) + + (clientSecret.asKnown().getOrNull()?.validity() ?: 0) + + (if (externalId.asKnown().isPresent) 1 else 0) + + (if (redirectUri.asKnown().isPresent) 1 else 0) + + (supportedScopes.asKnown().getOrNull()?.size ?: 0) + + class ClientSecret + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val binding: JsonField, + private val editable: JsonField, + private val exists: JsonField, + private val value: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("binding") + @ExcludeMissing + binding: JsonField = JsonMissing.of(), + @JsonProperty("editable") + @ExcludeMissing + editable: JsonField = JsonMissing.of(), + @JsonProperty("exists") + @ExcludeMissing + exists: JsonField = JsonMissing.of(), + @JsonProperty("value") + @ExcludeMissing + value: JsonField = JsonMissing.of(), + ) : this(binding, editable, exists, value, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun binding(): Optional = binding.getOptional("binding") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun editable(): Optional = editable.getOptional("editable") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun exists(): Optional = exists.getOptional("exists") + + /** + * @throws ArcadeInvalidDataException 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 [binding]. + * + * Unlike [binding], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("binding") + @ExcludeMissing + fun _binding(): JsonField = binding + + /** + * Returns the raw JSON value of [editable]. + * + * Unlike [editable], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("editable") + @ExcludeMissing + fun _editable(): JsonField = editable + + /** + * Returns the raw JSON value of [exists]. + * + * Unlike [exists], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("exists") @ExcludeMissing fun _exists(): JsonField = exists + + /** + * 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 [ClientSecret]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ClientSecret]. */ + class Builder internal constructor() { + + private var binding: JsonField = JsonMissing.of() + private var editable: JsonField = JsonMissing.of() + private var exists: JsonField = JsonMissing.of() + private var value: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(clientSecret: ClientSecret) = apply { + binding = clientSecret.binding + editable = clientSecret.editable + exists = clientSecret.exists + value = clientSecret.value + additionalProperties = clientSecret.additionalProperties.toMutableMap() + } + + fun binding(binding: Binding) = binding(JsonField.of(binding)) + + /** + * Sets [Builder.binding] to an arbitrary JSON value. + * + * You should usually call [Builder.binding] with a well-typed [Binding] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun binding(binding: JsonField) = apply { this.binding = binding } + + fun editable(editable: Boolean) = editable(JsonField.of(editable)) + + /** + * Sets [Builder.editable] to an arbitrary JSON value. + * + * You should usually call [Builder.editable] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun editable(editable: JsonField) = apply { this.editable = editable } + + fun exists(exists: Boolean) = exists(JsonField.of(exists)) + + /** + * Sets [Builder.exists] to an arbitrary JSON value. + * + * You should usually call [Builder.exists] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun exists(exists: JsonField) = apply { this.exists = exists } + + 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 [ClientSecret]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ClientSecret = + ClientSecret( + binding, + editable, + exists, + value, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): ClientSecret = apply { + if (validated) { + return@apply + } + + binding().ifPresent { it.validate() } + editable() + exists() + value() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (binding.asKnown().getOrNull()?.validity() ?: 0) + + (if (editable.asKnown().isPresent) 1 else 0) + + (if (exists.asKnown().isPresent) 1 else 0) + + (if (value.asKnown().isPresent) 1 else 0) + + class Binding + @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 STATIC = of("static") + + @JvmField val TENANT = of("tenant") + + @JvmField val PROJECT = of("project") + + @JvmField val ACCOUNT = of("account") + + @JvmStatic fun of(value: String) = Binding(JsonField.of(value)) + } + + /** An enum containing [Binding]'s known values. */ + enum class Known { + STATIC, + TENANT, + PROJECT, + ACCOUNT, + } + + /** + * An enum containing [Binding]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Binding] 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 { + STATIC, + TENANT, + PROJECT, + ACCOUNT, + /** + * An enum member indicating that [Binding] 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) { + STATIC -> Value.STATIC + TENANT -> Value.TENANT + PROJECT -> Value.PROJECT + ACCOUNT -> Value.ACCOUNT + 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 ArcadeInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + STATIC -> Known.STATIC + TENANT -> Known.TENANT + PROJECT -> Known.PROJECT + ACCOUNT -> Known.ACCOUNT + else -> throw ArcadeInvalidDataException("Unknown Binding: $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 ArcadeInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + ArcadeInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Binding = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 Binding && 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 ClientSecret && + binding == other.binding && + editable == other.editable && + exists == other.exists && + value == other.value && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(binding, editable, exists, value, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ClientSecret{binding=$binding, editable=$editable, exists=$exists, value=$value, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Oauth2 && + authorizationUrl == other.authorizationUrl && + clientId == other.clientId && + clientSecret == other.clientSecret && + externalId == other.externalId && + redirectUri == other.redirectUri && + supportedScopes == other.supportedScopes && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + authorizationUrl, + clientId, + clientSecret, + externalId, + redirectUri, + supportedScopes, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Oauth2{authorizationUrl=$authorizationUrl, clientId=$clientId, clientSecret=$clientSecret, externalId=$externalId, redirectUri=$redirectUri, supportedScopes=$supportedScopes, additionalProperties=$additionalProperties}" + } + + class Secrets + @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 [Secrets]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Secrets]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(secrets: Secrets) = apply { + additionalProperties = secrets.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 [Secrets]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Secrets = Secrets(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Secrets = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 Secrets && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Secrets{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Mcp && + headers == other.headers && + oauth2 == other.oauth2 && + retry == other.retry && + secrets == other.secrets && + timeout == other.timeout && + uri == other.uri && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(headers, oauth2, retry, secrets, timeout, uri, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Mcp{headers=$headers, oauth2=$oauth2, retry=$retry, secrets=$secrets, timeout=$timeout, uri=$uri, additionalProperties=$additionalProperties}" + } + + class Requirements + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val authorization: JsonField, + private val met: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("authorization") + @ExcludeMissing + authorization: JsonField = JsonMissing.of(), + @JsonProperty("met") @ExcludeMissing met: JsonField = JsonMissing.of(), + ) : this(authorization, met, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun authorization(): Optional = authorization.getOptional("authorization") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun met(): Optional = met.getOptional("met") + + /** + * Returns the raw JSON value of [authorization]. + * + * Unlike [authorization], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("authorization") + @ExcludeMissing + fun _authorization(): JsonField = authorization + + /** + * Returns the raw JSON value of [met]. + * + * Unlike [met], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("met") @ExcludeMissing fun _met(): JsonField = met + + @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 [Requirements]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Requirements]. */ + class Builder internal constructor() { + + private var authorization: JsonField = JsonMissing.of() + private var met: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(requirements: Requirements) = apply { + authorization = requirements.authorization + met = requirements.met + additionalProperties = requirements.additionalProperties.toMutableMap() + } + + fun authorization(authorization: Authorization) = + authorization(JsonField.of(authorization)) + + /** + * Sets [Builder.authorization] to an arbitrary JSON value. + * + * You should usually call [Builder.authorization] with a well-typed [Authorization] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun authorization(authorization: JsonField) = apply { + this.authorization = authorization + } + + fun met(met: Boolean) = met(JsonField.of(met)) + + /** + * Sets [Builder.met] to an arbitrary JSON value. + * + * You should usually call [Builder.met] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun met(met: JsonField) = apply { this.met = met } + + 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 [Requirements]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Requirements = + Requirements(authorization, met, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Requirements = apply { + if (validated) { + return@apply + } + + authorization().ifPresent { it.validate() } + met() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (authorization.asKnown().getOrNull()?.validity() ?: 0) + + (if (met.asKnown().isPresent) 1 else 0) + + class Authorization + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val met: JsonField, + private val oauth2: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("met") @ExcludeMissing met: JsonField = JsonMissing.of(), + @JsonProperty("oauth2") @ExcludeMissing oauth2: JsonField = JsonMissing.of(), + ) : this(met, oauth2, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun met(): Optional = met.getOptional("met") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun oauth2(): Optional = oauth2.getOptional("oauth2") + + /** + * Returns the raw JSON value of [met]. + * + * Unlike [met], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("met") @ExcludeMissing fun _met(): JsonField = met + + /** + * Returns the raw JSON value of [oauth2]. + * + * Unlike [oauth2], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("oauth2") @ExcludeMissing fun _oauth2(): JsonField = oauth2 + + @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 [Authorization]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Authorization]. */ + class Builder internal constructor() { + + private var met: JsonField = JsonMissing.of() + private var oauth2: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(authorization: Authorization) = apply { + met = authorization.met + oauth2 = authorization.oauth2 + additionalProperties = authorization.additionalProperties.toMutableMap() + } + + fun met(met: Boolean) = met(JsonField.of(met)) + + /** + * Sets [Builder.met] to an arbitrary JSON value. + * + * You should usually call [Builder.met] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun met(met: JsonField) = apply { this.met = met } + + fun oauth2(oauth2: Oauth2) = oauth2(JsonField.of(oauth2)) + + /** + * Sets [Builder.oauth2] to an arbitrary JSON value. + * + * You should usually call [Builder.oauth2] with a well-typed [Oauth2] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun oauth2(oauth2: JsonField) = apply { this.oauth2 = oauth2 } + + 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 [Authorization]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Authorization = + Authorization(met, oauth2, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Authorization = apply { + if (validated) { + return@apply + } + + met() + oauth2().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (met.asKnown().isPresent) 1 else 0) + + (oauth2.asKnown().getOrNull()?.validity() ?: 0) + + class Oauth2 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val met: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("met") @ExcludeMissing met: JsonField = JsonMissing.of() + ) : this(met, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun met(): Optional = met.getOptional("met") + + /** + * Returns the raw JSON value of [met]. + * + * Unlike [met], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("met") @ExcludeMissing fun _met(): JsonField = met + + @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 [Oauth2]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Oauth2]. */ + class Builder internal constructor() { + + private var met: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(oauth2: Oauth2) = apply { + met = oauth2.met + additionalProperties = oauth2.additionalProperties.toMutableMap() + } + + fun met(met: Boolean) = met(JsonField.of(met)) + + /** + * Sets [Builder.met] to an arbitrary JSON value. + * + * You should usually call [Builder.met] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun met(met: JsonField) = apply { this.met = met } + + 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 [Oauth2]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Oauth2 = Oauth2(met, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Oauth2 = apply { + if (validated) { + return@apply + } + + met() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 (met.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Oauth2 && + met == other.met && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(met, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Oauth2{met=$met, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Authorization && + met == other.met && + oauth2 == other.oauth2 && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(met, oauth2, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Authorization{met=$met, oauth2=$oauth2, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Requirements && + authorization == other.authorization && + met == other.met && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(authorization, met, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Requirements{authorization=$authorization, met=$met, additionalProperties=$additionalProperties}" + } + + 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 HTTP = of("http") + + @JvmField val MCP = of("mcp") + + @JvmField val UNKNOWN = of("unknown") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + HTTP, + MCP, + UNKNOWN, + } + + /** + * 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 { + HTTP, + MCP, + UNKNOWN, + /** 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) { + HTTP -> Value.HTTP + MCP -> Value.MCP + UNKNOWN -> Value.UNKNOWN + 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 ArcadeInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + HTTP -> Known.HTTP + MCP -> Known.MCP + UNKNOWN -> Known.UNKNOWN + else -> throw ArcadeInvalidDataException("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 ArcadeInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { ArcadeInvalidDataException("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: ArcadeInvalidDataException) { + false + } + + /** + * Returns 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 WorkerResponse && + id == other.id && + binding == other.binding && + enabled == other.enabled && + http == other.http && + managed == other.managed && + mcp == other.mcp && + requirements == other.requirements && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + binding, + enabled, + http, + managed, + mcp, + requirements, + type, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "WorkerResponse{id=$id, binding=$binding, enabled=$enabled, http=$http, managed=$managed, mcp=$mcp, requirements=$requirements, type=$type, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerToolsPage.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerToolsPage.kt new file mode 100644 index 0000000..14f9133 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerToolsPage.kt @@ -0,0 +1,146 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.workers + +import dev.arcade.core.AutoPager +import dev.arcade.core.Page +import dev.arcade.core.checkRequired +import dev.arcade.models.tools.ToolDefinition +import dev.arcade.services.blocking.WorkerService +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrDefault +import kotlin.jvm.optionals.getOrNull + +/** @see WorkerService.tools */ +class WorkerToolsPage +private constructor( + private val service: WorkerService, + private val params: WorkerToolsParams, + private val response: WorkerToolsPageResponse, +) : Page { + + /** + * Delegates to [WorkerToolsPageResponse], but gracefully handles missing data. + * + * @see WorkerToolsPageResponse.items + */ + override fun items(): List = + response._items().getOptional("items").getOrNull() ?: emptyList() + + /** + * Delegates to [WorkerToolsPageResponse], but gracefully handles missing data. + * + * @see WorkerToolsPageResponse.totalCount + */ + fun totalCount(): Optional = response._totalCount().getOptional("total_count") + + /** + * Delegates to [WorkerToolsPageResponse], but gracefully handles missing data. + * + * @see WorkerToolsPageResponse.offset + */ + fun offset(): Optional = response._offset().getOptional("offset") + + override fun hasNextPage(): Boolean { + if (items().isEmpty()) { + return false + } + + val offset = offset().getOrDefault(0) + val totalCount = totalCount().getOrNull() + return totalCount == null || offset + items().size < totalCount + } + + fun nextPageParams(): WorkerToolsParams { + val offset = offset().getOrDefault(0) + return params.toBuilder().offset(offset + items().size).build() + } + + override fun nextPage(): WorkerToolsPage = service.tools(nextPageParams()) + + fun autoPager(): AutoPager = AutoPager.from(this) + + /** The parameters that were used to request this page. */ + fun params(): WorkerToolsParams = params + + /** The response that this page was parsed from. */ + fun response(): WorkerToolsPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [WorkerToolsPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [WorkerToolsPage]. */ + class Builder internal constructor() { + + private var service: WorkerService? = null + private var params: WorkerToolsParams? = null + private var response: WorkerToolsPageResponse? = null + + @JvmSynthetic + internal fun from(workerToolsPage: WorkerToolsPage) = apply { + service = workerToolsPage.service + params = workerToolsPage.params + response = workerToolsPage.response + } + + fun service(service: WorkerService) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: WorkerToolsParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: WorkerToolsPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [WorkerToolsPage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): WorkerToolsPage = + WorkerToolsPage( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is WorkerToolsPage && + service == other.service && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, params, response) + + override fun toString() = + "WorkerToolsPage{service=$service, params=$params, response=$response}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerToolsPageAsync.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerToolsPageAsync.kt new file mode 100644 index 0000000..65fbb50 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerToolsPageAsync.kt @@ -0,0 +1,161 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.workers + +import dev.arcade.core.AutoPagerAsync +import dev.arcade.core.PageAsync +import dev.arcade.core.checkRequired +import dev.arcade.models.tools.ToolDefinition +import dev.arcade.services.async.WorkerServiceAsync +import java.util.Objects +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import kotlin.jvm.optionals.getOrDefault +import kotlin.jvm.optionals.getOrNull + +/** @see WorkerServiceAsync.tools */ +class WorkerToolsPageAsync +private constructor( + private val service: WorkerServiceAsync, + private val streamHandlerExecutor: Executor, + private val params: WorkerToolsParams, + private val response: WorkerToolsPageResponse, +) : PageAsync { + + /** + * Delegates to [WorkerToolsPageResponse], but gracefully handles missing data. + * + * @see WorkerToolsPageResponse.items + */ + override fun items(): List = + response._items().getOptional("items").getOrNull() ?: emptyList() + + /** + * Delegates to [WorkerToolsPageResponse], but gracefully handles missing data. + * + * @see WorkerToolsPageResponse.totalCount + */ + fun totalCount(): Optional = response._totalCount().getOptional("total_count") + + /** + * Delegates to [WorkerToolsPageResponse], but gracefully handles missing data. + * + * @see WorkerToolsPageResponse.offset + */ + fun offset(): Optional = response._offset().getOptional("offset") + + override fun hasNextPage(): Boolean { + if (items().isEmpty()) { + return false + } + + val offset = offset().getOrDefault(0) + val totalCount = totalCount().getOrNull() + return totalCount == null || offset + items().size < totalCount + } + + fun nextPageParams(): WorkerToolsParams { + val offset = offset().getOrDefault(0) + return params.toBuilder().offset(offset + items().size).build() + } + + override fun nextPage(): CompletableFuture = + service.tools(nextPageParams()) + + fun autoPager(): AutoPagerAsync = + AutoPagerAsync.from(this, streamHandlerExecutor) + + /** The parameters that were used to request this page. */ + fun params(): WorkerToolsParams = params + + /** The response that this page was parsed from. */ + fun response(): WorkerToolsPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [WorkerToolsPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [WorkerToolsPageAsync]. */ + class Builder internal constructor() { + + private var service: WorkerServiceAsync? = null + private var streamHandlerExecutor: Executor? = null + private var params: WorkerToolsParams? = null + private var response: WorkerToolsPageResponse? = null + + @JvmSynthetic + internal fun from(workerToolsPageAsync: WorkerToolsPageAsync) = apply { + service = workerToolsPageAsync.service + streamHandlerExecutor = workerToolsPageAsync.streamHandlerExecutor + params = workerToolsPageAsync.params + response = workerToolsPageAsync.response + } + + fun service(service: WorkerServiceAsync) = apply { this.service = service } + + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + this.streamHandlerExecutor = streamHandlerExecutor + } + + /** The parameters that were used to request this page. */ + fun params(params: WorkerToolsParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: WorkerToolsPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [WorkerToolsPageAsync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): WorkerToolsPageAsync = + WorkerToolsPageAsync( + checkRequired("service", service), + checkRequired("streamHandlerExecutor", streamHandlerExecutor), + checkRequired("params", params), + checkRequired("response", response), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is WorkerToolsPageAsync && + service == other.service && + streamHandlerExecutor == other.streamHandlerExecutor && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, streamHandlerExecutor, params, response) + + override fun toString() = + "WorkerToolsPageAsync{service=$service, streamHandlerExecutor=$streamHandlerExecutor, params=$params, response=$response}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerToolsPageResponse.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerToolsPageResponse.kt new file mode 100644 index 0000000..b585877 --- /dev/null +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerToolsPageResponse.kt @@ -0,0 +1,303 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.workers + +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 dev.arcade.core.ExcludeMissing +import dev.arcade.core.JsonField +import dev.arcade.core.JsonMissing +import dev.arcade.core.JsonValue +import dev.arcade.core.checkKnown +import dev.arcade.core.toImmutable +import dev.arcade.errors.ArcadeInvalidDataException +import dev.arcade.models.tools.ToolDefinition +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class WorkerToolsPageResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val items: JsonField>, + private val limit: JsonField, + private val offset: JsonField, + private val pageCount: JsonField, + private val totalCount: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("items") + @ExcludeMissing + items: JsonField> = JsonMissing.of(), + @JsonProperty("limit") @ExcludeMissing limit: JsonField = JsonMissing.of(), + @JsonProperty("offset") @ExcludeMissing offset: JsonField = JsonMissing.of(), + @JsonProperty("page_count") @ExcludeMissing pageCount: JsonField = JsonMissing.of(), + @JsonProperty("total_count") @ExcludeMissing totalCount: JsonField = JsonMissing.of(), + ) : this(items, limit, offset, pageCount, totalCount, mutableMapOf()) + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun items(): Optional> = items.getOptional("items") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun limit(): Optional = limit.getOptional("limit") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun offset(): Optional = offset.getOptional("offset") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun pageCount(): Optional = pageCount.getOptional("page_count") + + /** + * @throws ArcadeInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun totalCount(): Optional = totalCount.getOptional("total_count") + + /** + * Returns the raw JSON value of [items]. + * + * Unlike [items], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("items") @ExcludeMissing fun _items(): JsonField> = items + + /** + * Returns the raw JSON value of [limit]. + * + * Unlike [limit], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("limit") @ExcludeMissing fun _limit(): JsonField = limit + + /** + * Returns the raw JSON value of [offset]. + * + * Unlike [offset], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("offset") @ExcludeMissing fun _offset(): JsonField = offset + + /** + * Returns the raw JSON value of [pageCount]. + * + * Unlike [pageCount], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("page_count") @ExcludeMissing fun _pageCount(): JsonField = pageCount + + /** + * Returns the raw JSON value of [totalCount]. + * + * Unlike [totalCount], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("total_count") @ExcludeMissing fun _totalCount(): JsonField = totalCount + + @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 [WorkerToolsPageResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [WorkerToolsPageResponse]. */ + class Builder internal constructor() { + + private var items: JsonField>? = null + private var limit: JsonField = JsonMissing.of() + private var offset: JsonField = JsonMissing.of() + private var pageCount: JsonField = JsonMissing.of() + private var totalCount: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(workerToolsPageResponse: WorkerToolsPageResponse) = apply { + items = workerToolsPageResponse.items.map { it.toMutableList() } + limit = workerToolsPageResponse.limit + offset = workerToolsPageResponse.offset + pageCount = workerToolsPageResponse.pageCount + totalCount = workerToolsPageResponse.totalCount + additionalProperties = workerToolsPageResponse.additionalProperties.toMutableMap() + } + + fun items(items: List) = items(JsonField.of(items)) + + /** + * Sets [Builder.items] to an arbitrary JSON value. + * + * You should usually call [Builder.items] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun items(items: JsonField>) = apply { + this.items = items.map { it.toMutableList() } + } + + /** + * Adds a single [ToolDefinition] to [items]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addItem(item: ToolDefinition) = apply { + items = + (items ?: JsonField.of(mutableListOf())).also { checkKnown("items", it).add(item) } + } + + fun limit(limit: Long) = limit(JsonField.of(limit)) + + /** + * Sets [Builder.limit] to an arbitrary JSON value. + * + * You should usually call [Builder.limit] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun limit(limit: JsonField) = apply { this.limit = limit } + + fun offset(offset: Long) = offset(JsonField.of(offset)) + + /** + * Sets [Builder.offset] to an arbitrary JSON value. + * + * You should usually call [Builder.offset] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun offset(offset: JsonField) = apply { this.offset = offset } + + fun pageCount(pageCount: Long) = pageCount(JsonField.of(pageCount)) + + /** + * Sets [Builder.pageCount] to an arbitrary JSON value. + * + * You should usually call [Builder.pageCount] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun pageCount(pageCount: JsonField) = apply { this.pageCount = pageCount } + + fun totalCount(totalCount: Long) = totalCount(JsonField.of(totalCount)) + + /** + * Sets [Builder.totalCount] to an arbitrary JSON value. + * + * You should usually call [Builder.totalCount] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun totalCount(totalCount: JsonField) = apply { this.totalCount = totalCount } + + 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 [WorkerToolsPageResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): WorkerToolsPageResponse = + WorkerToolsPageResponse( + (items ?: JsonMissing.of()).map { it.toImmutable() }, + limit, + offset, + pageCount, + totalCount, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): WorkerToolsPageResponse = apply { + if (validated) { + return@apply + } + + items().ifPresent { it.forEach { it.validate() } } + limit() + offset() + pageCount() + totalCount() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: ArcadeInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (items.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (limit.asKnown().isPresent) 1 else 0) + + (if (offset.asKnown().isPresent) 1 else 0) + + (if (pageCount.asKnown().isPresent) 1 else 0) + + (if (totalCount.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is WorkerToolsPageResponse && + items == other.items && + limit == other.limit && + offset == other.offset && + pageCount == other.pageCount && + totalCount == other.totalCount && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(items, limit, offset, pageCount, totalCount, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "WorkerToolsPageResponse{items=$items, limit=$limit, offset=$offset, pageCount=$pageCount, totalCount=$totalCount, additionalProperties=$additionalProperties}" +} diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerToolsParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerToolsParams.kt similarity index 74% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerToolsParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerToolsParams.kt index babb32c..49fa2e0 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerToolsParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerToolsParams.kt @@ -1,26 +1,25 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.workers -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params -import dev.arcade.core.checkRequired import dev.arcade.core.http.Headers import dev.arcade.core.http.QueryParams import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Returns a page of tools */ class WorkerToolsParams private constructor( - private val id: String, + private val id: String?, private val limit: Long?, private val offset: Long?, private val additionalHeaders: Headers, private val additionalQueryParams: QueryParams, ) : Params { - fun id(): String = id + fun id(): Optional = Optional.ofNullable(id) /** Number of items to return (default: 25, max: 100) */ fun limit(): Optional = Optional.ofNullable(limit) @@ -28,36 +27,23 @@ private constructor( /** Offset from the start of the list (default: 0) */ fun offset(): Optional = Optional.ofNullable(offset) + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams { - val queryParams = QueryParams.builder() - this.limit?.let { queryParams.put("limit", listOf(it.toString())) } - this.offset?.let { queryParams.put("offset", listOf(it.toString())) } - queryParams.putAll(additionalQueryParams) - return queryParams.build() - } - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> id - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): WorkerToolsParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [WorkerToolsParams]. */ @JvmStatic fun builder() = Builder() } /** A builder for [WorkerToolsParams]. */ - @NoAutoDetect class Builder internal constructor() { private var id: String? = null @@ -75,27 +61,36 @@ private constructor( additionalQueryParams = workerToolsParams.additionalQueryParams.toBuilder() } - fun id(id: String) = apply { this.id = id } + fun id(id: String?) = apply { this.id = id } + + /** Alias for calling [Builder.id] with `id.orElse(null)`. */ + fun id(id: Optional) = id(id.getOrNull()) /** Number of items to return (default: 25, max: 100) */ fun limit(limit: Long?) = apply { this.limit = limit } - /** Number of items to return (default: 25, max: 100) */ + /** + * Alias for [Builder.limit]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun limit(limit: Long) = limit(limit as Long?) - /** Number of items to return (default: 25, max: 100) */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun limit(limit: Optional) = limit(limit.orElse(null) as Long?) + /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ + fun limit(limit: Optional) = limit(limit.getOrNull()) /** Offset from the start of the list (default: 0) */ fun offset(offset: Long?) = apply { this.offset = offset } - /** Offset from the start of the list (default: 0) */ + /** + * Alias for [Builder.offset]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun offset(offset: Long) = offset(offset as Long?) - /** Offset from the start of the list (default: 0) */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun offset(offset: Optional) = offset(offset.orElse(null) as Long?) + /** Alias for calling [Builder.offset] with `offset.orElse(null)`. */ + fun offset(offset: Optional) = offset(offset.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -195,9 +190,14 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [WorkerToolsParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): WorkerToolsParams = WorkerToolsParams( - checkRequired("id", id), + id, limit, offset, additionalHeaders.build(), @@ -205,15 +205,38 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> id ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + limit?.let { put("limit", it.toString()) } + offset?.let { put("offset", it.toString()) } + putAll(additionalQueryParams) + } + .build() + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is WorkerToolsParams && id == other.id && limit == other.limit && offset == other.offset && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is WorkerToolsParams && + id == other.id && + limit == other.limit && + offset == other.offset && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(id, limit, offset, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(id, limit, offset, additionalHeaders, additionalQueryParams) override fun toString() = "WorkerToolsParams{id=$id, limit=$limit, offset=$offset, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerUpdateParams.kt b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerUpdateParams.kt similarity index 79% rename from arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerUpdateParams.kt rename to arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerUpdateParams.kt index 9701793..a2c76bd 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/models/WorkerUpdateParams.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/models/workers/WorkerUpdateParams.kt @@ -1,57 +1,54 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.workers import dev.arcade.core.JsonValue -import dev.arcade.core.NoAutoDetect import dev.arcade.core.Params import dev.arcade.core.checkRequired import dev.arcade.core.http.Headers import dev.arcade.core.http.QueryParams import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Update a worker */ class WorkerUpdateParams private constructor( - private val id: String, + private val id: String?, private val updateWorkerRequest: UpdateWorkerRequest, private val additionalHeaders: Headers, private val additionalQueryParams: QueryParams, ) : Params { - fun id(): String = id + fun id(): Optional = Optional.ofNullable(id) fun updateWorkerRequest(): UpdateWorkerRequest = updateWorkerRequest fun _additionalBodyProperties(): Map = updateWorkerRequest._additionalProperties() + /** Additional headers to send with the request. */ fun _additionalHeaders(): Headers = additionalHeaders + /** Additional query param to send with the request. */ fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): UpdateWorkerRequest = updateWorkerRequest - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> id - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [WorkerUpdateParams]. + * + * The following fields are required: + * ```java + * .updateWorkerRequest() + * ``` + */ @JvmStatic fun builder() = Builder() } /** A builder for [WorkerUpdateParams]. */ - @NoAutoDetect class Builder internal constructor() { private var id: String? = null @@ -67,7 +64,10 @@ private constructor( additionalQueryParams = workerUpdateParams.additionalQueryParams.toBuilder() } - fun id(id: String) = apply { this.id = id } + 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 updateWorkerRequest(updateWorkerRequest: UpdateWorkerRequest) = apply { this.updateWorkerRequest = updateWorkerRequest @@ -171,24 +171,53 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [WorkerUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .updateWorkerRequest() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): WorkerUpdateParams = WorkerUpdateParams( - checkRequired("id", id), + id, checkRequired("updateWorkerRequest", updateWorkerRequest), additionalHeaders.build(), additionalQueryParams.build(), ) } + fun _body(): UpdateWorkerRequest = updateWorkerRequest + + 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 /* spotless:off */ other is WorkerUpdateParams && id == other.id && updateWorkerRequest == other.updateWorkerRequest && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + return other is WorkerUpdateParams && + id == other.id && + updateWorkerRequest == other.updateWorkerRequest && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(id, updateWorkerRequest, additionalHeaders, additionalQueryParams) /* spotless:on */ + override fun hashCode(): Int = + Objects.hash(id, updateWorkerRequest, additionalHeaders, additionalQueryParams) override fun toString() = "WorkerUpdateParams{id=$id, updateWorkerRequest=$updateWorkerRequest, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/AdminServiceAsync.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/AdminServiceAsync.kt index d56dbff..2b7e3f6 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/AdminServiceAsync.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/AdminServiceAsync.kt @@ -2,15 +2,48 @@ package dev.arcade.services.async +import dev.arcade.core.ClientOptions import dev.arcade.services.async.admin.AuthProviderServiceAsync import dev.arcade.services.async.admin.SecretServiceAsync import dev.arcade.services.async.admin.UserConnectionServiceAsync +import java.util.function.Consumer interface AdminServiceAsync { + /** + * 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): AdminServiceAsync + fun userConnections(): UserConnectionServiceAsync fun authProviders(): AuthProviderServiceAsync fun secrets(): SecretServiceAsync + + /** A view of [AdminServiceAsync] 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 + ): AdminServiceAsync.WithRawResponse + + fun userConnections(): UserConnectionServiceAsync.WithRawResponse + + fun authProviders(): AuthProviderServiceAsync.WithRawResponse + + fun secrets(): SecretServiceAsync.WithRawResponse + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/AdminServiceAsyncImpl.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/AdminServiceAsyncImpl.kt index b74b7dc..ec14c7b 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/AdminServiceAsyncImpl.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/AdminServiceAsyncImpl.kt @@ -9,10 +9,15 @@ import dev.arcade.services.async.admin.SecretServiceAsync import dev.arcade.services.async.admin.SecretServiceAsyncImpl import dev.arcade.services.async.admin.UserConnectionServiceAsync import dev.arcade.services.async.admin.UserConnectionServiceAsyncImpl +import java.util.function.Consumer class AdminServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : AdminServiceAsync { + private val withRawResponse: AdminServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + private val userConnections: UserConnectionServiceAsync by lazy { UserConnectionServiceAsyncImpl(clientOptions) } @@ -23,9 +28,43 @@ class AdminServiceAsyncImpl internal constructor(private val clientOptions: Clie private val secrets: SecretServiceAsync by lazy { SecretServiceAsyncImpl(clientOptions) } + override fun withRawResponse(): AdminServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): AdminServiceAsync = + AdminServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + override fun userConnections(): UserConnectionServiceAsync = userConnections override fun authProviders(): AuthProviderServiceAsync = authProviders override fun secrets(): SecretServiceAsync = secrets + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + AdminServiceAsync.WithRawResponse { + + private val userConnections: UserConnectionServiceAsync.WithRawResponse by lazy { + UserConnectionServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val authProviders: AuthProviderServiceAsync.WithRawResponse by lazy { + AuthProviderServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val secrets: SecretServiceAsync.WithRawResponse by lazy { + SecretServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + override fun withOptions( + modifier: Consumer + ): AdminServiceAsync.WithRawResponse = + AdminServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun userConnections(): UserConnectionServiceAsync.WithRawResponse = userConnections + + override fun authProviders(): AuthProviderServiceAsync.WithRawResponse = authProviders + + override fun secrets(): SecretServiceAsync.WithRawResponse = secrets + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/AuthServiceAsync.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/AuthServiceAsync.kt index 1594e9d..9583809 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/AuthServiceAsync.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/AuthServiceAsync.kt @@ -1,41 +1,201 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package dev.arcade.services.async +import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions -import dev.arcade.models.AuthAuthorizeParams -import dev.arcade.models.AuthConfirmUserParams -import dev.arcade.models.AuthStatusParams +import dev.arcade.core.http.HttpResponseFor import dev.arcade.models.AuthorizationResponse -import dev.arcade.models.ConfirmUserResponse +import dev.arcade.models.auth.AuthAuthorizeParams +import dev.arcade.models.auth.AuthConfirmUserParams +import dev.arcade.models.auth.AuthRequest +import dev.arcade.models.auth.AuthStatusParams +import dev.arcade.models.auth.ConfirmUserRequest +import dev.arcade.models.auth.ConfirmUserResponse import java.util.concurrent.CompletableFuture +import java.util.function.Consumer interface AuthServiceAsync { + /** + * 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): AuthServiceAsync + /** Starts the authorization process for given authorization requirements */ - @JvmOverloads + fun authorize(params: AuthAuthorizeParams): CompletableFuture = + authorize(params, RequestOptions.none()) + + /** @see authorize */ fun authorize( params: AuthAuthorizeParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + /** @see authorize */ + fun authorize( + authRequest: AuthRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + authorize(AuthAuthorizeParams.builder().authRequest(authRequest).build(), requestOptions) + + /** @see authorize */ + fun authorize(authRequest: AuthRequest): CompletableFuture = + authorize(authRequest, RequestOptions.none()) + /** Confirms a user's details during an authorization flow */ - @JvmOverloads + fun confirmUser(params: AuthConfirmUserParams): CompletableFuture = + confirmUser(params, RequestOptions.none()) + + /** @see confirmUser */ fun confirmUser( params: AuthConfirmUserParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + /** @see confirmUser */ + fun confirmUser( + confirmUserRequest: ConfirmUserRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + confirmUser( + AuthConfirmUserParams.builder().confirmUserRequest(confirmUserRequest).build(), + requestOptions, + ) + + /** @see confirmUser */ + fun confirmUser( + confirmUserRequest: ConfirmUserRequest + ): CompletableFuture = + confirmUser(confirmUserRequest, RequestOptions.none()) + /** * Checks the status of an ongoing authorization process for a specific tool. If 'wait' param is * present, does not respond until either the auth status becomes completed or the timeout is * reached. */ - @JvmOverloads + fun status(params: AuthStatusParams): CompletableFuture = + status(params, RequestOptions.none()) + + /** @see status */ fun status( params: AuthStatusParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + + /** A view of [AuthServiceAsync] 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): AuthServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/auth/authorize`, but is otherwise the same as + * [AuthServiceAsync.authorize]. + */ + fun authorize( + params: AuthAuthorizeParams + ): CompletableFuture> = + authorize(params, RequestOptions.none()) + + /** @see authorize */ + fun authorize( + params: AuthAuthorizeParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see authorize */ + fun authorize( + authRequest: AuthRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + authorize( + AuthAuthorizeParams.builder().authRequest(authRequest).build(), + requestOptions, + ) + + /** @see authorize */ + fun authorize( + authRequest: AuthRequest + ): CompletableFuture> = + authorize(authRequest, RequestOptions.none()) + + /** + * Returns a raw HTTP response for `post /v1/auth/confirm_user`, but is otherwise the same + * as [AuthServiceAsync.confirmUser]. + */ + fun confirmUser( + params: AuthConfirmUserParams + ): CompletableFuture> = + confirmUser(params, RequestOptions.none()) + + /** @see confirmUser */ + fun confirmUser( + params: AuthConfirmUserParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see confirmUser */ + fun confirmUser( + confirmUserRequest: ConfirmUserRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + confirmUser( + AuthConfirmUserParams.builder().confirmUserRequest(confirmUserRequest).build(), + requestOptions, + ) + + /** @see confirmUser */ + fun confirmUser( + confirmUserRequest: ConfirmUserRequest + ): CompletableFuture> = + confirmUser(confirmUserRequest, RequestOptions.none()) + + /** + * Returns a raw HTTP response for `get /v1/auth/status`, but is otherwise the same as + * [AuthServiceAsync.status]. + */ + fun status( + params: AuthStatusParams + ): CompletableFuture> = + status(params, RequestOptions.none()) + + /** @see status */ + fun status( + params: AuthStatusParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } + + // ------------------------------------------------------------------------- + // Start of manually added code + // ------------------------------------------------------------------------- + + /** + * Starts the authorization process for a given provider and scopes. + * + * @param userId The user ID for which authorization is being requested. + * @param provider The authorization provider (e.g., 'github', 'google', 'linkedin', + * 'microsoft', 'slack', 'spotify', 'x', 'zoom'). + * @param providerType The type of authorization provider. Optional, defaults to 'oauth2'. + * @param scopes A list of scopes required for authorization, if any. + * @return A CompletableFuture containing the authorization response based on the request. + */ + fun start( + userId: String, + provider: String, + providerType: String = "oauth2", + scopes: List = emptyList(), + ): CompletableFuture } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/AuthServiceAsyncImpl.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/AuthServiceAsyncImpl.kt index 3f586f8..9aa984f 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/AuthServiceAsyncImpl.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/AuthServiceAsyncImpl.kt @@ -4,111 +4,194 @@ package dev.arcade.services.async import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions +import dev.arcade.core.handlers.errorBodyHandler import dev.arcade.core.handlers.errorHandler import dev.arcade.core.handlers.jsonHandler -import dev.arcade.core.handlers.withErrorHandler import dev.arcade.core.http.HttpMethod import dev.arcade.core.http.HttpRequest +import dev.arcade.core.http.HttpResponse import dev.arcade.core.http.HttpResponse.Handler -import dev.arcade.core.json +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.core.http.json +import dev.arcade.core.http.parseable import dev.arcade.core.prepareAsync -import dev.arcade.errors.ArcadeError -import dev.arcade.models.AuthAuthorizeParams -import dev.arcade.models.AuthConfirmUserParams -import dev.arcade.models.AuthStatusParams import dev.arcade.models.AuthorizationResponse -import dev.arcade.models.ConfirmUserResponse +import dev.arcade.models.auth.AuthAuthorizeParams +import dev.arcade.models.auth.AuthConfirmUserParams +import dev.arcade.models.auth.AuthRequest +import dev.arcade.models.auth.AuthStatusParams +import dev.arcade.models.auth.ConfirmUserResponse import java.util.concurrent.CompletableFuture +import java.util.function.Consumer class AuthServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : AuthServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: AuthServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): AuthServiceAsync.WithRawResponse = withRawResponse - private val authorizeHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withOptions(modifier: Consumer): AuthServiceAsync = + AuthServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) - /** Starts the authorization process for given authorization requirements */ override fun authorize( params: AuthAuthorizeParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "auth", "authorize") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { authorizeHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - } - - private val confirmUserHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + ): CompletableFuture = + // post /v1/auth/authorize + withRawResponse().authorize(params, requestOptions).thenApply { it.parse() } - /** Confirms a user's details during an authorization flow */ override fun confirmUser( params: AuthConfirmUserParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "auth", "confirm_user") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { confirmUserHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - } - - private val statusHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + ): CompletableFuture = + // post /v1/auth/confirm_user + withRawResponse().confirmUser(params, requestOptions).thenApply { it.parse() } - /** - * Checks the status of an ongoing authorization process for a specific tool. If 'wait' param is - * present, does not respond until either the auth status becomes completed or the timeout is - * reached. - */ override fun status( params: AuthStatusParams, requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/auth/status + withRawResponse().status(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + AuthServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): AuthServiceAsync.WithRawResponse = + AuthServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val authorizeHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun authorize( + params: AuthAuthorizeParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "auth", "authorize") + .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 { authorizeHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val confirmUserHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun confirmUser( + params: AuthConfirmUserParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "auth", "confirm_user") + .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 { confirmUserHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val statusHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun status( + params: AuthStatusParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "auth", "status") + .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 { statusHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } + + // ------------------------------------------------------------------------- + // Start of manually added code + // ------------------------------------------------------------------------- + + override fun start( + userId: String, + provider: String, + providerType: String, + scopes: List, ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "auth", "status") + return authorize( + AuthAuthorizeParams.builder() + .authRequest( + AuthRequest.builder() + .userId(userId) + .authRequirement( + AuthRequest.AuthRequirement.builder() + .providerId(provider) + .providerType(providerType) + .oauth2( + AuthRequest.AuthRequirement.Oauth2.builder() + .scopes(scopes) + .build() + ) + .build() + ) + .build() + ) .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { statusHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } + ) } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/ChatServiceAsync.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/ChatServiceAsync.kt index 9b2e892..79aaf35 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/ChatServiceAsync.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/ChatServiceAsync.kt @@ -2,9 +2,36 @@ package dev.arcade.services.async +import dev.arcade.core.ClientOptions import dev.arcade.services.async.chat.CompletionServiceAsync +import java.util.function.Consumer interface ChatServiceAsync { + /** + * 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): ChatServiceAsync + fun completions(): CompletionServiceAsync + + /** A view of [ChatServiceAsync] 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): ChatServiceAsync.WithRawResponse + + fun completions(): CompletionServiceAsync.WithRawResponse + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/ChatServiceAsyncImpl.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/ChatServiceAsyncImpl.kt index dd5b64a..b7dc0d3 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/ChatServiceAsyncImpl.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/ChatServiceAsyncImpl.kt @@ -5,13 +5,40 @@ package dev.arcade.services.async import dev.arcade.core.ClientOptions import dev.arcade.services.async.chat.CompletionServiceAsync import dev.arcade.services.async.chat.CompletionServiceAsyncImpl +import java.util.function.Consumer class ChatServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : ChatServiceAsync { + private val withRawResponse: ChatServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + private val completions: CompletionServiceAsync by lazy { CompletionServiceAsyncImpl(clientOptions) } + override fun withRawResponse(): ChatServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): ChatServiceAsync = + ChatServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + override fun completions(): CompletionServiceAsync = completions + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ChatServiceAsync.WithRawResponse { + + private val completions: CompletionServiceAsync.WithRawResponse by lazy { + CompletionServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + override fun withOptions( + modifier: Consumer + ): ChatServiceAsync.WithRawResponse = + ChatServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun completions(): CompletionServiceAsync.WithRawResponse = completions + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/HealthServiceAsync.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/HealthServiceAsync.kt index add8147..61ec79d 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/HealthServiceAsync.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/HealthServiceAsync.kt @@ -1,20 +1,83 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package dev.arcade.services.async +import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions -import dev.arcade.models.HealthCheckParams -import dev.arcade.models.HealthSchema +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.models.health.HealthCheckParams +import dev.arcade.models.health.HealthSchema import java.util.concurrent.CompletableFuture +import java.util.function.Consumer interface HealthServiceAsync { + /** + * 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): HealthServiceAsync + /** Check if Arcade Engine is healthy */ - @JvmOverloads + fun check(): CompletableFuture = check(HealthCheckParams.none()) + + /** @see check */ fun check( - params: HealthCheckParams, + params: HealthCheckParams = HealthCheckParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + + /** @see check */ + fun check( + params: HealthCheckParams = HealthCheckParams.none() + ): CompletableFuture = check(params, RequestOptions.none()) + + /** @see check */ + fun check(requestOptions: RequestOptions): CompletableFuture = + check(HealthCheckParams.none(), requestOptions) + + /** + * A view of [HealthServiceAsync] 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 + ): HealthServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `get /v1/health`, but is otherwise the same as + * [HealthServiceAsync.check]. + */ + fun check(): CompletableFuture> = + check(HealthCheckParams.none()) + + /** @see check */ + fun check( + params: HealthCheckParams = HealthCheckParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see check */ + fun check( + params: HealthCheckParams = HealthCheckParams.none() + ): CompletableFuture> = check(params, RequestOptions.none()) + + /** @see check */ + fun check( + requestOptions: RequestOptions + ): CompletableFuture> = + check(HealthCheckParams.none(), requestOptions) + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/HealthServiceAsyncImpl.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/HealthServiceAsyncImpl.kt index 3c243b0..ca8c691 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/HealthServiceAsyncImpl.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/HealthServiceAsyncImpl.kt @@ -4,47 +4,81 @@ package dev.arcade.services.async import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions +import dev.arcade.core.handlers.errorBodyHandler import dev.arcade.core.handlers.errorHandler import dev.arcade.core.handlers.jsonHandler -import dev.arcade.core.handlers.withErrorHandler import dev.arcade.core.http.HttpMethod import dev.arcade.core.http.HttpRequest +import dev.arcade.core.http.HttpResponse import dev.arcade.core.http.HttpResponse.Handler +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.core.http.parseable import dev.arcade.core.prepareAsync -import dev.arcade.errors.ArcadeError -import dev.arcade.models.HealthCheckParams -import dev.arcade.models.HealthSchema +import dev.arcade.models.health.HealthCheckParams +import dev.arcade.models.health.HealthSchema import java.util.concurrent.CompletableFuture +import java.util.function.Consumer class HealthServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : HealthServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: HealthServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): HealthServiceAsync.WithRawResponse = withRawResponse - private val checkHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withOptions(modifier: Consumer): HealthServiceAsync = + HealthServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) - /** Check if Arcade Engine is healthy */ override fun check( params: HealthCheckParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "health") - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { checkHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): CompletableFuture = + // get /v1/health + withRawResponse().check(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + HealthServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): HealthServiceAsync.WithRawResponse = + HealthServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val checkHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun check( + params: HealthCheckParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "health") + .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 { checkHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } - } + } + } } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/ToolServiceAsync.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/ToolServiceAsync.kt index e7c83b4..4a773b7 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/ToolServiceAsync.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/ToolServiceAsync.kt @@ -1,53 +1,279 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package dev.arcade.services.async +import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions +import dev.arcade.core.http.HttpResponseFor import dev.arcade.models.AuthorizationResponse -import dev.arcade.models.ExecuteToolResponse -import dev.arcade.models.ToolAuthorizeParams -import dev.arcade.models.ToolDefinition -import dev.arcade.models.ToolExecuteParams -import dev.arcade.models.ToolGetParams -import dev.arcade.models.ToolListPageAsync -import dev.arcade.models.ToolListParams +import dev.arcade.models.tools.AuthorizeToolRequest +import dev.arcade.models.tools.ExecuteToolRequest +import dev.arcade.models.tools.ExecuteToolResponse +import dev.arcade.models.tools.ToolAuthorizeParams +import dev.arcade.models.tools.ToolDefinition +import dev.arcade.models.tools.ToolExecuteParams +import dev.arcade.models.tools.ToolGetParams +import dev.arcade.models.tools.ToolListPageAsync +import dev.arcade.models.tools.ToolListParams import dev.arcade.services.async.tools.FormattedServiceAsync import dev.arcade.services.async.tools.ScheduledServiceAsync import java.util.concurrent.CompletableFuture +import java.util.function.Consumer interface ToolServiceAsync { + /** + * 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): ToolServiceAsync + fun scheduled(): ScheduledServiceAsync fun formatted(): FormattedServiceAsync /** Returns a page of tools from the engine configuration, optionally filtered by toolkit */ - @JvmOverloads + fun list(): CompletableFuture = list(ToolListParams.none()) + + /** @see list */ fun list( - params: ToolListParams, + params: ToolListParams = ToolListParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + /** @see list */ + fun list(params: ToolListParams = ToolListParams.none()): CompletableFuture = + list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): CompletableFuture = + list(ToolListParams.none(), requestOptions) + /** Authorizes a user for a specific tool by name */ - @JvmOverloads + fun authorize(params: ToolAuthorizeParams): CompletableFuture = + authorize(params, RequestOptions.none()) + + /** @see authorize */ fun authorize( params: ToolAuthorizeParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + /** @see authorize */ + fun authorize( + authorizeToolRequest: AuthorizeToolRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + authorize( + ToolAuthorizeParams.builder().authorizeToolRequest(authorizeToolRequest).build(), + requestOptions, + ) + + /** @see authorize */ + fun authorize( + authorizeToolRequest: AuthorizeToolRequest + ): CompletableFuture = + authorize(authorizeToolRequest, RequestOptions.none()) + /** Executes a tool by name and arguments */ - @JvmOverloads + fun execute(params: ToolExecuteParams): CompletableFuture = + execute(params, RequestOptions.none()) + + /** @see execute */ fun execute( params: ToolExecuteParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + /** @see execute */ + fun execute( + executeToolRequest: ExecuteToolRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + execute( + ToolExecuteParams.builder().executeToolRequest(executeToolRequest).build(), + requestOptions, + ) + + /** @see execute */ + fun execute(executeToolRequest: ExecuteToolRequest): CompletableFuture = + execute(executeToolRequest, RequestOptions.none()) + /** Returns the arcade tool specification for a specific tool */ - @JvmOverloads + fun get(name: String): CompletableFuture = get(name, ToolGetParams.none()) + + /** @see get */ + fun get( + name: String, + params: ToolGetParams = ToolGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + get(params.toBuilder().name(name).build(), requestOptions) + + /** @see get */ + fun get( + name: String, + params: ToolGetParams = ToolGetParams.none(), + ): CompletableFuture = get(name, params, RequestOptions.none()) + + /** @see get */ fun get( params: ToolGetParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + + /** @see get */ + fun get(params: ToolGetParams): CompletableFuture = + get(params, RequestOptions.none()) + + /** @see get */ + fun get(name: String, requestOptions: RequestOptions): CompletableFuture = + get(name, ToolGetParams.none(), requestOptions) + + /** A view of [ToolServiceAsync] 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): ToolServiceAsync.WithRawResponse + + fun scheduled(): ScheduledServiceAsync.WithRawResponse + + fun formatted(): FormattedServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `get /v1/tools`, but is otherwise the same as + * [ToolServiceAsync.list]. + */ + fun list(): CompletableFuture> = + list(ToolListParams.none()) + + /** @see list */ + fun list( + params: ToolListParams = ToolListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list( + params: ToolListParams = ToolListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(ToolListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `post /v1/tools/authorize`, but is otherwise the same as + * [ToolServiceAsync.authorize]. + */ + fun authorize( + params: ToolAuthorizeParams + ): CompletableFuture> = + authorize(params, RequestOptions.none()) + + /** @see authorize */ + fun authorize( + params: ToolAuthorizeParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see authorize */ + fun authorize( + authorizeToolRequest: AuthorizeToolRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + authorize( + ToolAuthorizeParams.builder().authorizeToolRequest(authorizeToolRequest).build(), + requestOptions, + ) + + /** @see authorize */ + fun authorize( + authorizeToolRequest: AuthorizeToolRequest + ): CompletableFuture> = + authorize(authorizeToolRequest, RequestOptions.none()) + + /** + * Returns a raw HTTP response for `post /v1/tools/execute`, but is otherwise the same as + * [ToolServiceAsync.execute]. + */ + fun execute( + params: ToolExecuteParams + ): CompletableFuture> = + execute(params, RequestOptions.none()) + + /** @see execute */ + fun execute( + params: ToolExecuteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see execute */ + fun execute( + executeToolRequest: ExecuteToolRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + execute( + ToolExecuteParams.builder().executeToolRequest(executeToolRequest).build(), + requestOptions, + ) + + /** @see execute */ + fun execute( + executeToolRequest: ExecuteToolRequest + ): CompletableFuture> = + execute(executeToolRequest, RequestOptions.none()) + + /** + * Returns a raw HTTP response for `get /v1/tools/{name}`, but is otherwise the same as + * [ToolServiceAsync.get]. + */ + fun get(name: String): CompletableFuture> = + get(name, ToolGetParams.none()) + + /** @see get */ + fun get( + name: String, + params: ToolGetParams = ToolGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + get(params.toBuilder().name(name).build(), requestOptions) + + /** @see get */ + fun get( + name: String, + params: ToolGetParams = ToolGetParams.none(), + ): CompletableFuture> = + get(name, params, RequestOptions.none()) + + /** @see get */ + fun get( + params: ToolGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see get */ + fun get(params: ToolGetParams): CompletableFuture> = + get(params, RequestOptions.none()) + + /** @see get */ + fun get( + name: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + get(name, ToolGetParams.none(), requestOptions) + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/ToolServiceAsyncImpl.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/ToolServiceAsyncImpl.kt index 5f2bb57..ece2d7d 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/ToolServiceAsyncImpl.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/ToolServiceAsyncImpl.kt @@ -4,33 +4,41 @@ package dev.arcade.services.async import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions +import dev.arcade.core.checkRequired +import dev.arcade.core.handlers.errorBodyHandler import dev.arcade.core.handlers.errorHandler import dev.arcade.core.handlers.jsonHandler -import dev.arcade.core.handlers.withErrorHandler import dev.arcade.core.http.HttpMethod import dev.arcade.core.http.HttpRequest +import dev.arcade.core.http.HttpResponse import dev.arcade.core.http.HttpResponse.Handler -import dev.arcade.core.json +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.core.http.json +import dev.arcade.core.http.parseable import dev.arcade.core.prepareAsync -import dev.arcade.errors.ArcadeError import dev.arcade.models.AuthorizationResponse -import dev.arcade.models.ExecuteToolResponse -import dev.arcade.models.ToolAuthorizeParams -import dev.arcade.models.ToolDefinition -import dev.arcade.models.ToolExecuteParams -import dev.arcade.models.ToolGetParams -import dev.arcade.models.ToolListPageAsync -import dev.arcade.models.ToolListParams +import dev.arcade.models.tools.ExecuteToolResponse +import dev.arcade.models.tools.ToolAuthorizeParams +import dev.arcade.models.tools.ToolDefinition +import dev.arcade.models.tools.ToolExecuteParams +import dev.arcade.models.tools.ToolGetParams +import dev.arcade.models.tools.ToolListPageAsync +import dev.arcade.models.tools.ToolListPageResponse +import dev.arcade.models.tools.ToolListParams import dev.arcade.services.async.tools.FormattedServiceAsync import dev.arcade.services.async.tools.FormattedServiceAsyncImpl import dev.arcade.services.async.tools.ScheduledServiceAsync import dev.arcade.services.async.tools.ScheduledServiceAsyncImpl import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull class ToolServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : ToolServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: ToolServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } private val scheduled: ScheduledServiceAsync by lazy { ScheduledServiceAsyncImpl(clientOptions) @@ -40,119 +48,199 @@ class ToolServiceAsyncImpl internal constructor(private val clientOptions: Clien FormattedServiceAsyncImpl(clientOptions) } + override fun withRawResponse(): ToolServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): ToolServiceAsync = + ToolServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + override fun scheduled(): ScheduledServiceAsync = scheduled override fun formatted(): FormattedServiceAsync = formatted - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** Returns a page of tools from the engine configuration, optionally filtered by toolkit */ override fun list( params: ToolListParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "tools") - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - .let { ToolListPageAsync.of(this, params, it) } - } - } + ): CompletableFuture = + // get /v1/tools + withRawResponse().list(params, requestOptions).thenApply { it.parse() } - private val authorizeHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** Authorizes a user for a specific tool by name */ override fun authorize( params: ToolAuthorizeParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "tools", "authorize") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { authorizeHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - } - - private val executeHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + ): CompletableFuture = + // post /v1/tools/authorize + withRawResponse().authorize(params, requestOptions).thenApply { it.parse() } - /** Executes a tool by name and arguments */ override fun execute( params: ToolExecuteParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "tools", "execute") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { executeHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - } + ): CompletableFuture = + // post /v1/tools/execute + withRawResponse().execute(params, requestOptions).thenApply { it.parse() } - private val getHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** Returns the arcade tool specification for a specific tool */ override fun get( params: ToolGetParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "tools", params.getPathParam(0)) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { getHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): CompletableFuture = + // get /v1/tools/{name} + withRawResponse().get(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ToolServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + private val scheduled: ScheduledServiceAsync.WithRawResponse by lazy { + ScheduledServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val formatted: FormattedServiceAsync.WithRawResponse by lazy { + FormattedServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + override fun withOptions( + modifier: Consumer + ): ToolServiceAsync.WithRawResponse = + ToolServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun scheduled(): ScheduledServiceAsync.WithRawResponse = scheduled + + override fun formatted(): FormattedServiceAsync.WithRawResponse = formatted + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: ToolListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "tools") + .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.validate() + } + } + .let { + ToolListPageAsync.builder() + .service(ToolServiceAsyncImpl(clientOptions)) + .streamHandlerExecutor(clientOptions.streamHandlerExecutor) + .params(params) + .response(it) + .build() + } + } + } + } + + private val authorizeHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun authorize( + params: ToolAuthorizeParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "tools", "authorize") + .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 { authorizeHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val executeHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun execute( + params: ToolExecuteParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "tools", "execute") + .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 { executeHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val getHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun get( + params: ToolGetParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("name", params.name().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "tools", 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/arcade-java-core/src/main/kotlin/dev/arcade/services/async/WorkerServiceAsync.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/WorkerServiceAsync.kt index 4be0b70..2b0bdc3 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/WorkerServiceAsync.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/WorkerServiceAsync.kt @@ -1,71 +1,480 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package dev.arcade.services.async +import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions -import dev.arcade.models.WorkerCreateParams -import dev.arcade.models.WorkerDeleteParams -import dev.arcade.models.WorkerGetParams -import dev.arcade.models.WorkerHealthParams -import dev.arcade.models.WorkerHealthResponse -import dev.arcade.models.WorkerListPageAsync -import dev.arcade.models.WorkerListParams -import dev.arcade.models.WorkerResponse -import dev.arcade.models.WorkerToolsPageAsync -import dev.arcade.models.WorkerToolsParams -import dev.arcade.models.WorkerUpdateParams +import dev.arcade.core.http.HttpResponse +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.models.workers.CreateWorkerRequest +import dev.arcade.models.workers.WorkerCreateParams +import dev.arcade.models.workers.WorkerDeleteParams +import dev.arcade.models.workers.WorkerGetParams +import dev.arcade.models.workers.WorkerHealthParams +import dev.arcade.models.workers.WorkerHealthResponse +import dev.arcade.models.workers.WorkerListPageAsync +import dev.arcade.models.workers.WorkerListParams +import dev.arcade.models.workers.WorkerResponse +import dev.arcade.models.workers.WorkerToolsPageAsync +import dev.arcade.models.workers.WorkerToolsParams +import dev.arcade.models.workers.WorkerUpdateParams import java.util.concurrent.CompletableFuture +import java.util.function.Consumer interface WorkerServiceAsync { + /** + * 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): WorkerServiceAsync + /** Create a worker */ - @JvmOverloads + fun create(params: WorkerCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see create */ fun create( params: WorkerCreateParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + /** @see create */ + fun create( + createWorkerRequest: CreateWorkerRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + create( + WorkerCreateParams.builder().createWorkerRequest(createWorkerRequest).build(), + requestOptions, + ) + + /** @see create */ + fun create(createWorkerRequest: CreateWorkerRequest): CompletableFuture = + create(createWorkerRequest, RequestOptions.none()) + /** Update a worker */ - @JvmOverloads + fun update(id: String, params: WorkerUpdateParams): CompletableFuture = + update(id, params, RequestOptions.none()) + + /** @see update */ + fun update( + id: String, + params: WorkerUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = update(params.toBuilder().id(id).build(), requestOptions) + + /** @see update */ + fun update(params: WorkerUpdateParams): CompletableFuture = + update(params, RequestOptions.none()) + + /** @see update */ fun update( params: WorkerUpdateParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture /** List all workers with their definitions */ - @JvmOverloads + fun list(): CompletableFuture = list(WorkerListParams.none()) + + /** @see list */ fun list( - params: WorkerListParams, + params: WorkerListParams = WorkerListParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + /** @see list */ + fun list( + params: WorkerListParams = WorkerListParams.none() + ): CompletableFuture = list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): CompletableFuture = + list(WorkerListParams.none(), requestOptions) + /** Delete a worker */ - @JvmOverloads + fun delete(id: String): CompletableFuture = delete(id, WorkerDeleteParams.none()) + + /** @see delete */ + fun delete( + id: String, + params: WorkerDeleteParams = WorkerDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = delete(params.toBuilder().id(id).build(), requestOptions) + + /** @see delete */ + fun delete( + id: String, + params: WorkerDeleteParams = WorkerDeleteParams.none(), + ): CompletableFuture = delete(id, params, RequestOptions.none()) + + /** @see delete */ fun delete( params: WorkerDeleteParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + /** @see delete */ + fun delete(params: WorkerDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(id: String, requestOptions: RequestOptions): CompletableFuture = + delete(id, WorkerDeleteParams.none(), requestOptions) + /** Get a worker by ID */ - @JvmOverloads + fun get(id: String): CompletableFuture = get(id, WorkerGetParams.none()) + + /** @see get */ + fun get( + id: String, + params: WorkerGetParams = WorkerGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = get(params.toBuilder().id(id).build(), requestOptions) + + /** @see get */ + fun get( + id: String, + params: WorkerGetParams = WorkerGetParams.none(), + ): CompletableFuture = get(id, params, RequestOptions.none()) + + /** @see get */ fun get( params: WorkerGetParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + /** @see get */ + fun get(params: WorkerGetParams): CompletableFuture = + get(params, RequestOptions.none()) + + /** @see get */ + fun get(id: String, requestOptions: RequestOptions): CompletableFuture = + get(id, WorkerGetParams.none(), requestOptions) + /** Get the health of a worker */ - @JvmOverloads + fun health(id: String): CompletableFuture = + health(id, WorkerHealthParams.none()) + + /** @see health */ + fun health( + id: String, + params: WorkerHealthParams = WorkerHealthParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + health(params.toBuilder().id(id).build(), requestOptions) + + /** @see health */ + fun health( + id: String, + params: WorkerHealthParams = WorkerHealthParams.none(), + ): CompletableFuture = health(id, params, RequestOptions.none()) + + /** @see health */ fun health( params: WorkerHealthParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + /** @see health */ + fun health(params: WorkerHealthParams): CompletableFuture = + health(params, RequestOptions.none()) + + /** @see health */ + fun health( + id: String, + requestOptions: RequestOptions, + ): CompletableFuture = + health(id, WorkerHealthParams.none(), requestOptions) + /** Returns a page of tools */ - @JvmOverloads + fun tools(id: String): CompletableFuture = + tools(id, WorkerToolsParams.none()) + + /** @see tools */ + fun tools( + id: String, + params: WorkerToolsParams = WorkerToolsParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + tools(params.toBuilder().id(id).build(), requestOptions) + + /** @see tools */ + fun tools( + id: String, + params: WorkerToolsParams = WorkerToolsParams.none(), + ): CompletableFuture = tools(id, params, RequestOptions.none()) + + /** @see tools */ fun tools( params: WorkerToolsParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + + /** @see tools */ + fun tools(params: WorkerToolsParams): CompletableFuture = + tools(params, RequestOptions.none()) + + /** @see tools */ + fun tools(id: String, requestOptions: RequestOptions): CompletableFuture = + tools(id, WorkerToolsParams.none(), requestOptions) + + /** + * A view of [WorkerServiceAsync] 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 + ): WorkerServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/workers`, but is otherwise the same as + * [WorkerServiceAsync.create]. + */ + fun create(params: WorkerCreateParams): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: WorkerCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see create */ + fun create( + createWorkerRequest: CreateWorkerRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + create( + WorkerCreateParams.builder().createWorkerRequest(createWorkerRequest).build(), + requestOptions, + ) + + /** @see create */ + fun create( + createWorkerRequest: CreateWorkerRequest + ): CompletableFuture> = + create(createWorkerRequest, RequestOptions.none()) + + /** + * Returns a raw HTTP response for `patch /v1/workers/{id}`, but is otherwise the same as + * [WorkerServiceAsync.update]. + */ + fun update( + id: String, + params: WorkerUpdateParams, + ): CompletableFuture> = + update(id, params, RequestOptions.none()) + + /** @see update */ + fun update( + id: String, + params: WorkerUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + update(params.toBuilder().id(id).build(), requestOptions) + + /** @see update */ + fun update(params: WorkerUpdateParams): CompletableFuture> = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + params: WorkerUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/workers`, but is otherwise the same as + * [WorkerServiceAsync.list]. + */ + fun list(): CompletableFuture> = + list(WorkerListParams.none()) + + /** @see list */ + fun list( + params: WorkerListParams = WorkerListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list( + params: WorkerListParams = WorkerListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(WorkerListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/workers/{id}`, but is otherwise the same as + * [WorkerServiceAsync.delete]. + */ + fun delete(id: String): CompletableFuture = + delete(id, WorkerDeleteParams.none()) + + /** @see delete */ + fun delete( + id: String, + params: WorkerDeleteParams = WorkerDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + delete(params.toBuilder().id(id).build(), requestOptions) + + /** @see delete */ + fun delete( + id: String, + params: WorkerDeleteParams = WorkerDeleteParams.none(), + ): CompletableFuture = delete(id, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: WorkerDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see delete */ + fun delete(params: WorkerDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(id: String, requestOptions: RequestOptions): CompletableFuture = + delete(id, WorkerDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/workers/{id}`, but is otherwise the same as + * [WorkerServiceAsync.get]. + */ + fun get(id: String): CompletableFuture> = + get(id, WorkerGetParams.none()) + + /** @see get */ + fun get( + id: String, + params: WorkerGetParams = WorkerGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + get(params.toBuilder().id(id).build(), requestOptions) + + /** @see get */ + fun get( + id: String, + params: WorkerGetParams = WorkerGetParams.none(), + ): CompletableFuture> = + get(id, params, RequestOptions.none()) + + /** @see get */ + fun get( + params: WorkerGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see get */ + fun get(params: WorkerGetParams): CompletableFuture> = + get(params, RequestOptions.none()) + + /** @see get */ + fun get( + id: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + get(id, WorkerGetParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/workers/{id}/health`, but is otherwise the same + * as [WorkerServiceAsync.health]. + */ + fun health(id: String): CompletableFuture> = + health(id, WorkerHealthParams.none()) + + /** @see health */ + fun health( + id: String, + params: WorkerHealthParams = WorkerHealthParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + health(params.toBuilder().id(id).build(), requestOptions) + + /** @see health */ + fun health( + id: String, + params: WorkerHealthParams = WorkerHealthParams.none(), + ): CompletableFuture> = + health(id, params, RequestOptions.none()) + + /** @see health */ + fun health( + params: WorkerHealthParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see health */ + fun health( + params: WorkerHealthParams + ): CompletableFuture> = + health(params, RequestOptions.none()) + + /** @see health */ + fun health( + id: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + health(id, WorkerHealthParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/workers/{id}/tools`, but is otherwise the same + * as [WorkerServiceAsync.tools]. + */ + fun tools(id: String): CompletableFuture> = + tools(id, WorkerToolsParams.none()) + + /** @see tools */ + fun tools( + id: String, + params: WorkerToolsParams = WorkerToolsParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + tools(params.toBuilder().id(id).build(), requestOptions) + + /** @see tools */ + fun tools( + id: String, + params: WorkerToolsParams = WorkerToolsParams.none(), + ): CompletableFuture> = + tools(id, params, RequestOptions.none()) + + /** @see tools */ + fun tools( + params: WorkerToolsParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see tools */ + fun tools( + params: WorkerToolsParams + ): CompletableFuture> = + tools(params, RequestOptions.none()) + + /** @see tools */ + fun tools( + id: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + tools(id, WorkerToolsParams.none(), requestOptions) + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/WorkerServiceAsyncImpl.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/WorkerServiceAsyncImpl.kt index 98bccfa..b5891f2 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/WorkerServiceAsyncImpl.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/WorkerServiceAsyncImpl.kt @@ -4,218 +4,345 @@ package dev.arcade.services.async import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions +import dev.arcade.core.checkRequired import dev.arcade.core.handlers.emptyHandler +import dev.arcade.core.handlers.errorBodyHandler import dev.arcade.core.handlers.errorHandler import dev.arcade.core.handlers.jsonHandler -import dev.arcade.core.handlers.withErrorHandler import dev.arcade.core.http.HttpMethod import dev.arcade.core.http.HttpRequest +import dev.arcade.core.http.HttpResponse import dev.arcade.core.http.HttpResponse.Handler -import dev.arcade.core.json +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.core.http.json +import dev.arcade.core.http.parseable import dev.arcade.core.prepareAsync -import dev.arcade.errors.ArcadeError -import dev.arcade.models.WorkerCreateParams -import dev.arcade.models.WorkerDeleteParams -import dev.arcade.models.WorkerGetParams -import dev.arcade.models.WorkerHealthParams -import dev.arcade.models.WorkerHealthResponse -import dev.arcade.models.WorkerListPageAsync -import dev.arcade.models.WorkerListParams -import dev.arcade.models.WorkerResponse -import dev.arcade.models.WorkerToolsPageAsync -import dev.arcade.models.WorkerToolsParams -import dev.arcade.models.WorkerUpdateParams +import dev.arcade.models.workers.WorkerCreateParams +import dev.arcade.models.workers.WorkerDeleteParams +import dev.arcade.models.workers.WorkerGetParams +import dev.arcade.models.workers.WorkerHealthParams +import dev.arcade.models.workers.WorkerHealthResponse +import dev.arcade.models.workers.WorkerListPageAsync +import dev.arcade.models.workers.WorkerListPageResponse +import dev.arcade.models.workers.WorkerListParams +import dev.arcade.models.workers.WorkerResponse +import dev.arcade.models.workers.WorkerToolsPageAsync +import dev.arcade.models.workers.WorkerToolsPageResponse +import dev.arcade.models.workers.WorkerToolsParams +import dev.arcade.models.workers.WorkerUpdateParams import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull class WorkerServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : WorkerServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: WorkerServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): WorkerServiceAsync.WithRawResponse = withRawResponse - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withOptions(modifier: Consumer): WorkerServiceAsync = + WorkerServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) - /** Create a worker */ override fun create( params: WorkerCreateParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "workers") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { createHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - } - - private val updateHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + ): CompletableFuture = + // post /v1/workers + withRawResponse().create(params, requestOptions).thenApply { it.parse() } - /** Update a worker */ override fun update( params: WorkerUpdateParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.PATCH) - .addPathSegments("v1", "workers", params.getPathParam(0)) - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { updateHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - } - - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + ): CompletableFuture = + // patch /v1/workers/{id} + withRawResponse().update(params, requestOptions).thenApply { it.parse() } - /** List all workers with their definitions */ override fun list( params: WorkerListParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "workers") - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - .let { WorkerListPageAsync.of(this, params, it) } - } - } - - private val deleteHandler: Handler = emptyHandler().withErrorHandler(errorHandler) + ): CompletableFuture = + // get /v1/workers + withRawResponse().list(params, requestOptions).thenApply { it.parse() } - /** Delete a worker */ override fun delete( params: WorkerDeleteParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.DELETE) - .addPathSegments("v1", "workers", params.getPathParam(0)) - .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> response.use { deleteHandler.handle(it) } } - } - - private val getHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + ): CompletableFuture = + // delete /v1/workers/{id} + withRawResponse().delete(params, requestOptions).thenAccept {} - /** Get a worker by ID */ override fun get( params: WorkerGetParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "workers", params.getPathParam(0)) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { getHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - } - - private val healthHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + ): CompletableFuture = + // get /v1/workers/{id} + withRawResponse().get(params, requestOptions).thenApply { it.parse() } - /** Get the health of a worker */ override fun health( params: WorkerHealthParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "workers", params.getPathParam(0), "health") - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { healthHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - } - - private val toolsHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + ): CompletableFuture = + // get /v1/workers/{id}/health + withRawResponse().health(params, requestOptions).thenApply { it.parse() } - /** Returns a page of tools */ override fun tools( params: WorkerToolsParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "workers", params.getPathParam(0), "tools") - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { toolsHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): CompletableFuture = + // get /v1/workers/{id}/tools + withRawResponse().tools(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + WorkerServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): WorkerServiceAsync.WithRawResponse = + WorkerServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: WorkerCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "workers") + .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: WorkerUpdateParams, + 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", "workers", 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: WorkerListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "workers") + .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.validate() + } + } + .let { + WorkerListPageAsync.builder() + .service(WorkerServiceAsyncImpl(clientOptions)) + .streamHandlerExecutor(clientOptions.streamHandlerExecutor) + .params(params) + .response(it) + .build() + } + } + } + } + + private val deleteHandler: Handler = emptyHandler() + + override fun delete( + params: WorkerDeleteParams, + 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", "workers", 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: WorkerGetParams, + 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", "workers", 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() + } + } + } + } + } + + private val healthHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun health( + params: WorkerHealthParams, + 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", "workers", params._pathParam(0), "health") + .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 { healthHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val toolsHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun tools( + params: WorkerToolsParams, + 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", "workers", params._pathParam(0), "tools") + .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 { toolsHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + WorkerToolsPageAsync.builder() + .service(WorkerServiceAsyncImpl(clientOptions)) + .streamHandlerExecutor(clientOptions.streamHandlerExecutor) + .params(params) + .response(it) + .build() + } } - .let { WorkerToolsPageAsync.of(this, params, it) } - } + } + } } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/admin/AuthProviderServiceAsync.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/admin/AuthProviderServiceAsync.kt index cd9e7e5..195b38a 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/admin/AuthProviderServiceAsync.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/admin/AuthProviderServiceAsync.kt @@ -1,53 +1,355 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package dev.arcade.services.async.admin +import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions -import dev.arcade.models.AdminAuthProviderCreateParams -import dev.arcade.models.AdminAuthProviderDeleteParams -import dev.arcade.models.AdminAuthProviderGetParams -import dev.arcade.models.AdminAuthProviderListParams -import dev.arcade.models.AdminAuthProviderListResponse -import dev.arcade.models.AdminAuthProviderPatchParams -import dev.arcade.models.AuthProviderResponse +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.models.admin.authproviders.AuthProviderCreateParams +import dev.arcade.models.admin.authproviders.AuthProviderCreateRequest +import dev.arcade.models.admin.authproviders.AuthProviderDeleteParams +import dev.arcade.models.admin.authproviders.AuthProviderGetParams +import dev.arcade.models.admin.authproviders.AuthProviderListParams +import dev.arcade.models.admin.authproviders.AuthProviderListResponse +import dev.arcade.models.admin.authproviders.AuthProviderPatchParams +import dev.arcade.models.admin.authproviders.AuthProviderResponse import java.util.concurrent.CompletableFuture +import java.util.function.Consumer interface AuthProviderServiceAsync { + /** + * 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): AuthProviderServiceAsync + /** Create a new auth provider */ - @JvmOverloads + fun create(params: AuthProviderCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see create */ fun create( - params: AdminAuthProviderCreateParams, + params: AuthProviderCreateParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + /** @see create */ + fun create( + authProviderCreateRequest: AuthProviderCreateRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + create( + AuthProviderCreateParams.builder() + .authProviderCreateRequest(authProviderCreateRequest) + .build(), + requestOptions, + ) + + /** @see create */ + fun create( + authProviderCreateRequest: AuthProviderCreateRequest + ): CompletableFuture = + create(authProviderCreateRequest, RequestOptions.none()) + /** List a page of auth providers that are available to the caller */ - @JvmOverloads + fun list(): CompletableFuture = list(AuthProviderListParams.none()) + + /** @see list */ fun list( - params: AdminAuthProviderListParams, + params: AuthProviderListParams = AuthProviderListParams.none(), requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture + ): CompletableFuture + + /** @see list */ + fun list( + params: AuthProviderListParams = AuthProviderListParams.none() + ): CompletableFuture = list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): CompletableFuture = + list(AuthProviderListParams.none(), requestOptions) /** Delete a specific auth provider */ - @JvmOverloads + fun delete(id: String): CompletableFuture = + delete(id, AuthProviderDeleteParams.none()) + + /** @see delete */ fun delete( - params: AdminAuthProviderDeleteParams, + id: String, + params: AuthProviderDeleteParams = AuthProviderDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + delete(params.toBuilder().id(id).build(), requestOptions) + + /** @see delete */ + fun delete( + id: String, + params: AuthProviderDeleteParams = AuthProviderDeleteParams.none(), + ): CompletableFuture = delete(id, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: AuthProviderDeleteParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + /** @see delete */ + fun delete(params: AuthProviderDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + id: String, + requestOptions: RequestOptions, + ): CompletableFuture = + delete(id, AuthProviderDeleteParams.none(), requestOptions) + /** Get the details of a specific auth provider */ - @JvmOverloads + fun get(id: String): CompletableFuture = + get(id, AuthProviderGetParams.none()) + + /** @see get */ fun get( - params: AdminAuthProviderGetParams, + id: String, + params: AuthProviderGetParams = AuthProviderGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + get(params.toBuilder().id(id).build(), requestOptions) + + /** @see get */ + fun get( + id: String, + params: AuthProviderGetParams = AuthProviderGetParams.none(), + ): CompletableFuture = get(id, params, RequestOptions.none()) + + /** @see get */ + fun get( + params: AuthProviderGetParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + /** @see get */ + fun get(params: AuthProviderGetParams): CompletableFuture = + get(params, RequestOptions.none()) + + /** @see get */ + fun get(id: String, requestOptions: RequestOptions): CompletableFuture = + get(id, AuthProviderGetParams.none(), requestOptions) + /** Patch an existing auth provider */ - @JvmOverloads fun patch( - params: AdminAuthProviderPatchParams, + pathId: String, + params: AuthProviderPatchParams, + ): CompletableFuture = patch(pathId, params, RequestOptions.none()) + + /** @see patch */ + fun patch( + pathId: String, + params: AuthProviderPatchParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + patch(params.toBuilder().pathId(pathId).build(), requestOptions) + + /** @see patch */ + fun patch(params: AuthProviderPatchParams): CompletableFuture = + patch(params, RequestOptions.none()) + + /** @see patch */ + fun patch( + params: AuthProviderPatchParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + + /** + * A view of [AuthProviderServiceAsync] 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 + ): AuthProviderServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/admin/auth_providers`, but is otherwise the + * same as [AuthProviderServiceAsync.create]. + */ + fun create( + params: AuthProviderCreateParams + ): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: AuthProviderCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see create */ + fun create( + authProviderCreateRequest: AuthProviderCreateRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + create( + AuthProviderCreateParams.builder() + .authProviderCreateRequest(authProviderCreateRequest) + .build(), + requestOptions, + ) + + /** @see create */ + fun create( + authProviderCreateRequest: AuthProviderCreateRequest + ): CompletableFuture> = + create(authProviderCreateRequest, RequestOptions.none()) + + /** + * Returns a raw HTTP response for `get /v1/admin/auth_providers`, but is otherwise the same + * as [AuthProviderServiceAsync.list]. + */ + fun list(): CompletableFuture> = + list(AuthProviderListParams.none()) + + /** @see list */ + fun list( + params: AuthProviderListParams = AuthProviderListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list( + params: AuthProviderListParams = AuthProviderListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(AuthProviderListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/admin/auth_providers/{id}`, but is otherwise + * the same as [AuthProviderServiceAsync.delete]. + */ + fun delete(id: String): CompletableFuture> = + delete(id, AuthProviderDeleteParams.none()) + + /** @see delete */ + fun delete( + id: String, + params: AuthProviderDeleteParams = AuthProviderDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + delete(params.toBuilder().id(id).build(), requestOptions) + + /** @see delete */ + fun delete( + id: String, + params: AuthProviderDeleteParams = AuthProviderDeleteParams.none(), + ): CompletableFuture> = + delete(id, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: AuthProviderDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see delete */ + fun delete( + params: AuthProviderDeleteParams + ): CompletableFuture> = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + id: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + delete(id, AuthProviderDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/admin/auth_providers/{id}`, but is otherwise the + * same as [AuthProviderServiceAsync.get]. + */ + fun get(id: String): CompletableFuture> = + get(id, AuthProviderGetParams.none()) + + /** @see get */ + fun get( + id: String, + params: AuthProviderGetParams = AuthProviderGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + get(params.toBuilder().id(id).build(), requestOptions) + + /** @see get */ + fun get( + id: String, + params: AuthProviderGetParams = AuthProviderGetParams.none(), + ): CompletableFuture> = + get(id, params, RequestOptions.none()) + + /** @see get */ + fun get( + params: AuthProviderGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see get */ + fun get( + params: AuthProviderGetParams + ): CompletableFuture> = + get(params, RequestOptions.none()) + + /** @see get */ + fun get( + id: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + get(id, AuthProviderGetParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/admin/auth_providers/{id}`, but is otherwise + * the same as [AuthProviderServiceAsync.patch]. + */ + fun patch( + pathId: String, + params: AuthProviderPatchParams, + ): CompletableFuture> = + patch(pathId, params, RequestOptions.none()) + + /** @see patch */ + fun patch( + pathId: String, + params: AuthProviderPatchParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + patch(params.toBuilder().pathId(pathId).build(), requestOptions) + + /** @see patch */ + fun patch( + params: AuthProviderPatchParams + ): CompletableFuture> = + patch(params, RequestOptions.none()) + + /** @see patch */ + fun patch( + params: AuthProviderPatchParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/admin/AuthProviderServiceAsyncImpl.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/admin/AuthProviderServiceAsyncImpl.kt index 81d77dc..2ffcae8 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/admin/AuthProviderServiceAsyncImpl.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/admin/AuthProviderServiceAsyncImpl.kt @@ -4,165 +4,249 @@ package dev.arcade.services.async.admin import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions +import dev.arcade.core.checkRequired +import dev.arcade.core.handlers.errorBodyHandler import dev.arcade.core.handlers.errorHandler import dev.arcade.core.handlers.jsonHandler -import dev.arcade.core.handlers.withErrorHandler import dev.arcade.core.http.HttpMethod import dev.arcade.core.http.HttpRequest +import dev.arcade.core.http.HttpResponse import dev.arcade.core.http.HttpResponse.Handler -import dev.arcade.core.json +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.core.http.json +import dev.arcade.core.http.parseable import dev.arcade.core.prepareAsync -import dev.arcade.errors.ArcadeError -import dev.arcade.models.AdminAuthProviderCreateParams -import dev.arcade.models.AdminAuthProviderDeleteParams -import dev.arcade.models.AdminAuthProviderGetParams -import dev.arcade.models.AdminAuthProviderListParams -import dev.arcade.models.AdminAuthProviderListResponse -import dev.arcade.models.AdminAuthProviderPatchParams -import dev.arcade.models.AuthProviderResponse +import dev.arcade.models.admin.authproviders.AuthProviderCreateParams +import dev.arcade.models.admin.authproviders.AuthProviderDeleteParams +import dev.arcade.models.admin.authproviders.AuthProviderGetParams +import dev.arcade.models.admin.authproviders.AuthProviderListParams +import dev.arcade.models.admin.authproviders.AuthProviderListResponse +import dev.arcade.models.admin.authproviders.AuthProviderPatchParams +import dev.arcade.models.admin.authproviders.AuthProviderResponse import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull class AuthProviderServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : AuthProviderServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: AuthProviderServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): AuthProviderServiceAsync.WithRawResponse = withRawResponse - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withOptions(modifier: Consumer): AuthProviderServiceAsync = + AuthProviderServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) - /** Create a new auth provider */ override fun create( - params: AdminAuthProviderCreateParams, + params: AuthProviderCreateParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "admin", "auth_providers") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { createHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - } + ): CompletableFuture = + // post /v1/admin/auth_providers + withRawResponse().create(params, requestOptions).thenApply { it.parse() } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** List a page of auth providers that are available to the caller */ override fun list( - params: AdminAuthProviderListParams, + params: AuthProviderListParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "admin", "auth_providers") - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - } - - private val deleteHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + ): CompletableFuture = + // get /v1/admin/auth_providers + withRawResponse().list(params, requestOptions).thenApply { it.parse() } - /** Delete a specific auth provider */ override fun delete( - params: AdminAuthProviderDeleteParams, + params: AuthProviderDeleteParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.DELETE) - .addPathSegments("v1", "admin", "auth_providers", params.getPathParam(0)) - .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { deleteHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - } + ): CompletableFuture = + // delete /v1/admin/auth_providers/{id} + withRawResponse().delete(params, requestOptions).thenApply { it.parse() } - private val getHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** Get the details of a specific auth provider */ override fun get( - params: AdminAuthProviderGetParams, + params: AuthProviderGetParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "admin", "auth_providers", params.getPathParam(0)) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { getHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - } - - private val patchHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + ): CompletableFuture = + // get /v1/admin/auth_providers/{id} + withRawResponse().get(params, requestOptions).thenApply { it.parse() } - /** Patch an existing auth provider */ override fun patch( - params: AdminAuthProviderPatchParams, + params: AuthProviderPatchParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.PATCH) - .addPathSegments("v1", "admin", "auth_providers", params.getPathParam(0)) - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { patchHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): CompletableFuture = + // patch /v1/admin/auth_providers/{id} + withRawResponse().patch(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + AuthProviderServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): AuthProviderServiceAsync.WithRawResponse = + AuthProviderServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: AuthProviderCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "admin", "auth_providers") + .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 listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: AuthProviderListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "admin", "auth_providers") + .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.validate() + } + } + } + } + } + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: AuthProviderDeleteParams, + 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", "admin", "auth_providers", 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() + } + } + } + } + } + + private val getHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun get( + params: AuthProviderGetParams, + 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", "admin", "auth_providers", 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() + } + } + } + } + } + + private val patchHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun patch( + params: AuthProviderPatchParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("pathId", params.pathId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "admin", "auth_providers", 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 { patchHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } - } + } + } } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/admin/SecretServiceAsync.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/admin/SecretServiceAsync.kt index 96fc438..7d6e4e2 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/admin/SecretServiceAsync.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/admin/SecretServiceAsync.kt @@ -1,37 +1,208 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package dev.arcade.services.async.admin +import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions -import dev.arcade.models.AdminSecretCreateParams -import dev.arcade.models.AdminSecretDeleteParams -import dev.arcade.models.AdminSecretListParams -import dev.arcade.models.AdminSecretListResponse -import dev.arcade.models.SecretResponse +import dev.arcade.core.http.HttpResponse +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.models.admin.secrets.SecretCreateParams +import dev.arcade.models.admin.secrets.SecretDeleteParams +import dev.arcade.models.admin.secrets.SecretListParams +import dev.arcade.models.admin.secrets.SecretListResponse +import dev.arcade.models.admin.secrets.SecretResponse import java.util.concurrent.CompletableFuture +import java.util.function.Consumer interface SecretServiceAsync { + /** + * 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): SecretServiceAsync + /** Create or update a secret */ - @JvmOverloads + fun create(secretKey: String, params: SecretCreateParams): CompletableFuture = + create(secretKey, params, RequestOptions.none()) + + /** @see create */ fun create( - params: AdminSecretCreateParams, + secretKey: String, + params: SecretCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + create(params.toBuilder().secretKey(secretKey).build(), requestOptions) + + /** @see create */ + fun create(params: SecretCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: SecretCreateParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture /** List all secrets that are visible to the caller */ - @JvmOverloads + fun list(): CompletableFuture = list(SecretListParams.none()) + + /** @see list */ fun list( - params: AdminSecretListParams, + params: SecretListParams = SecretListParams.none(), requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture + ): CompletableFuture + + /** @see list */ + fun list( + params: SecretListParams = SecretListParams.none() + ): CompletableFuture = list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): CompletableFuture = + list(SecretListParams.none(), requestOptions) /** Delete a secret by its ID */ - @JvmOverloads + fun delete(secretId: String): CompletableFuture = + delete(secretId, SecretDeleteParams.none()) + + /** @see delete */ + fun delete( + secretId: String, + params: SecretDeleteParams = SecretDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + delete(params.toBuilder().secretId(secretId).build(), requestOptions) + + /** @see delete */ + fun delete( + secretId: String, + params: SecretDeleteParams = SecretDeleteParams.none(), + ): CompletableFuture = delete(secretId, params, RequestOptions.none()) + + /** @see delete */ fun delete( - params: AdminSecretDeleteParams, + params: SecretDeleteParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + + /** @see delete */ + fun delete(params: SecretDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(secretId: String, requestOptions: RequestOptions): CompletableFuture = + delete(secretId, SecretDeleteParams.none(), requestOptions) + + /** + * A view of [SecretServiceAsync] 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 + ): SecretServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/admin/secrets/{secret_key}`, but is otherwise + * the same as [SecretServiceAsync.create]. + */ + fun create( + secretKey: String, + params: SecretCreateParams, + ): CompletableFuture> = + create(secretKey, params, RequestOptions.none()) + + /** @see create */ + fun create( + secretKey: String, + params: SecretCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + create(params.toBuilder().secretKey(secretKey).build(), requestOptions) + + /** @see create */ + fun create(params: SecretCreateParams): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: SecretCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/admin/secrets`, but is otherwise the same as + * [SecretServiceAsync.list]. + */ + fun list(): CompletableFuture> = + list(SecretListParams.none()) + + /** @see list */ + fun list( + params: SecretListParams = SecretListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list( + params: SecretListParams = SecretListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(SecretListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/admin/secrets/{secret_id}`, but is otherwise + * the same as [SecretServiceAsync.delete]. + */ + fun delete(secretId: String): CompletableFuture = + delete(secretId, SecretDeleteParams.none()) + + /** @see delete */ + fun delete( + secretId: String, + params: SecretDeleteParams = SecretDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + delete(params.toBuilder().secretId(secretId).build(), requestOptions) + + /** @see delete */ + fun delete( + secretId: String, + params: SecretDeleteParams = SecretDeleteParams.none(), + ): CompletableFuture = delete(secretId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: SecretDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see delete */ + fun delete(params: SecretDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + secretId: String, + requestOptions: RequestOptions, + ): CompletableFuture = + delete(secretId, SecretDeleteParams.none(), requestOptions) + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/admin/SecretServiceAsyncImpl.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/admin/SecretServiceAsyncImpl.kt index 09376f2..c194335 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/admin/SecretServiceAsyncImpl.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/admin/SecretServiceAsyncImpl.kt @@ -4,100 +4,163 @@ package dev.arcade.services.async.admin import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions +import dev.arcade.core.checkRequired import dev.arcade.core.handlers.emptyHandler +import dev.arcade.core.handlers.errorBodyHandler import dev.arcade.core.handlers.errorHandler import dev.arcade.core.handlers.jsonHandler -import dev.arcade.core.handlers.withErrorHandler import dev.arcade.core.http.HttpMethod import dev.arcade.core.http.HttpRequest +import dev.arcade.core.http.HttpResponse import dev.arcade.core.http.HttpResponse.Handler -import dev.arcade.core.json +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.core.http.json +import dev.arcade.core.http.parseable import dev.arcade.core.prepareAsync -import dev.arcade.errors.ArcadeError -import dev.arcade.models.AdminSecretCreateParams -import dev.arcade.models.AdminSecretDeleteParams -import dev.arcade.models.AdminSecretListParams -import dev.arcade.models.AdminSecretListResponse -import dev.arcade.models.SecretResponse +import dev.arcade.models.admin.secrets.SecretCreateParams +import dev.arcade.models.admin.secrets.SecretDeleteParams +import dev.arcade.models.admin.secrets.SecretListParams +import dev.arcade.models.admin.secrets.SecretListResponse +import dev.arcade.models.admin.secrets.SecretResponse import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull class SecretServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : SecretServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: SecretServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): SecretServiceAsync.WithRawResponse = withRawResponse - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withOptions(modifier: Consumer): SecretServiceAsync = + SecretServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) - /** Create or update a secret */ override fun create( - params: AdminSecretCreateParams, + params: SecretCreateParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "admin", "secrets", params.getPathParam(0)) - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { createHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - } - - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + ): CompletableFuture = + // post /v1/admin/secrets/{secret_key} + withRawResponse().create(params, requestOptions).thenApply { it.parse() } - /** List all secrets that are visible to the caller */ override fun list( - params: AdminSecretListParams, + params: SecretListParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "admin", "secrets") - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - } - - private val deleteHandler: Handler = emptyHandler().withErrorHandler(errorHandler) + ): CompletableFuture = + // get /v1/admin/secrets + withRawResponse().list(params, requestOptions).thenApply { it.parse() } - /** Delete a secret by its ID */ override fun delete( - params: AdminSecretDeleteParams, + params: SecretDeleteParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.DELETE) - .addPathSegments("v1", "admin", "secrets", params.getPathParam(0)) - .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> response.use { deleteHandler.handle(it) } } + ): CompletableFuture = + // delete /v1/admin/secrets/{secret_id} + withRawResponse().delete(params, requestOptions).thenAccept {} + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + SecretServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): SecretServiceAsync.WithRawResponse = + SecretServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: SecretCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("secretKey", params.secretKey().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "admin", "secrets", 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 { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: SecretListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "admin", "secrets") + .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.validate() + } + } + } + } + } + + private val deleteHandler: Handler = emptyHandler() + + override fun delete( + params: SecretDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("secretId", params.secretId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "admin", "secrets", 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) } + } + } + } } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/admin/UserConnectionServiceAsync.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/admin/UserConnectionServiceAsync.kt index c8899af..ec43d0b 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/admin/UserConnectionServiceAsync.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/admin/UserConnectionServiceAsync.kt @@ -1,28 +1,153 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package dev.arcade.services.async.admin +import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions -import dev.arcade.models.AdminUserConnectionDeleteParams -import dev.arcade.models.AdminUserConnectionListPageAsync -import dev.arcade.models.AdminUserConnectionListParams +import dev.arcade.core.http.HttpResponse +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.models.admin.userconnections.UserConnectionDeleteParams +import dev.arcade.models.admin.userconnections.UserConnectionListPageAsync +import dev.arcade.models.admin.userconnections.UserConnectionListParams import java.util.concurrent.CompletableFuture +import java.util.function.Consumer interface UserConnectionServiceAsync { + /** + * 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): UserConnectionServiceAsync + /** List all auth connections */ - @JvmOverloads + fun list(): CompletableFuture = + list(UserConnectionListParams.none()) + + /** @see list */ fun list( - params: AdminUserConnectionListParams, + params: UserConnectionListParams = UserConnectionListParams.none(), requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture + ): CompletableFuture + + /** @see list */ + fun list( + params: UserConnectionListParams = UserConnectionListParams.none() + ): CompletableFuture = list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): CompletableFuture = + list(UserConnectionListParams.none(), requestOptions) /** Delete a user/auth provider connection */ - @JvmOverloads + fun delete(id: String): CompletableFuture = delete(id, UserConnectionDeleteParams.none()) + + /** @see delete */ fun delete( - params: AdminUserConnectionDeleteParams, + id: String, + params: UserConnectionDeleteParams = UserConnectionDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = delete(params.toBuilder().id(id).build(), requestOptions) + + /** @see delete */ + fun delete( + id: String, + params: UserConnectionDeleteParams = UserConnectionDeleteParams.none(), + ): CompletableFuture = delete(id, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: UserConnectionDeleteParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + + /** @see delete */ + fun delete(params: UserConnectionDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(id: String, requestOptions: RequestOptions): CompletableFuture = + delete(id, UserConnectionDeleteParams.none(), requestOptions) + + /** + * A view of [UserConnectionServiceAsync] 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 + ): UserConnectionServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `get /v1/admin/user_connections`, but is otherwise the + * same as [UserConnectionServiceAsync.list]. + */ + fun list(): CompletableFuture> = + list(UserConnectionListParams.none()) + + /** @see list */ + fun list( + params: UserConnectionListParams = UserConnectionListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list( + params: UserConnectionListParams = UserConnectionListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(UserConnectionListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/admin/user_connections/{id}`, but is + * otherwise the same as [UserConnectionServiceAsync.delete]. + */ + fun delete(id: String): CompletableFuture = + delete(id, UserConnectionDeleteParams.none()) + + /** @see delete */ + fun delete( + id: String, + params: UserConnectionDeleteParams = UserConnectionDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + delete(params.toBuilder().id(id).build(), requestOptions) + + /** @see delete */ + fun delete( + id: String, + params: UserConnectionDeleteParams = UserConnectionDeleteParams.none(), + ): CompletableFuture = delete(id, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: UserConnectionDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see delete */ + fun delete(params: UserConnectionDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(id: String, requestOptions: RequestOptions): CompletableFuture = + delete(id, UserConnectionDeleteParams.none(), requestOptions) + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/admin/UserConnectionServiceAsyncImpl.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/admin/UserConnectionServiceAsyncImpl.kt index 41f9c06..9b14447 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/admin/UserConnectionServiceAsyncImpl.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/admin/UserConnectionServiceAsyncImpl.kt @@ -4,71 +4,131 @@ package dev.arcade.services.async.admin import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions +import dev.arcade.core.checkRequired import dev.arcade.core.handlers.emptyHandler +import dev.arcade.core.handlers.errorBodyHandler import dev.arcade.core.handlers.errorHandler import dev.arcade.core.handlers.jsonHandler -import dev.arcade.core.handlers.withErrorHandler import dev.arcade.core.http.HttpMethod import dev.arcade.core.http.HttpRequest +import dev.arcade.core.http.HttpResponse import dev.arcade.core.http.HttpResponse.Handler -import dev.arcade.core.json +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.core.http.json +import dev.arcade.core.http.parseable import dev.arcade.core.prepareAsync -import dev.arcade.errors.ArcadeError -import dev.arcade.models.AdminUserConnectionDeleteParams -import dev.arcade.models.AdminUserConnectionListPageAsync -import dev.arcade.models.AdminUserConnectionListParams +import dev.arcade.models.admin.userconnections.UserConnectionDeleteParams +import dev.arcade.models.admin.userconnections.UserConnectionListPageAsync +import dev.arcade.models.admin.userconnections.UserConnectionListPageResponse +import dev.arcade.models.admin.userconnections.UserConnectionListParams import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull class UserConnectionServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : UserConnectionServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: UserConnectionServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): UserConnectionServiceAsync.WithRawResponse = withRawResponse - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withOptions( + modifier: Consumer + ): UserConnectionServiceAsync = + UserConnectionServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) - /** List all auth connections */ override fun list( - params: AdminUserConnectionListParams, + params: UserConnectionListParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "admin", "user_connections") - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - .let { AdminUserConnectionListPageAsync.of(this, params, it) } - } - } + ): CompletableFuture = + // get /v1/admin/user_connections + withRawResponse().list(params, requestOptions).thenApply { it.parse() } - private val deleteHandler: Handler = emptyHandler().withErrorHandler(errorHandler) - - /** Delete a user/auth provider connection */ override fun delete( - params: AdminUserConnectionDeleteParams, + params: UserConnectionDeleteParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.DELETE) - .addPathSegments("v1", "admin", "user_connections", params.getPathParam(0)) - .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> response.use { deleteHandler.handle(it) } } + ): CompletableFuture = + // delete /v1/admin/user_connections/{id} + withRawResponse().delete(params, requestOptions).thenAccept {} + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + UserConnectionServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): UserConnectionServiceAsync.WithRawResponse = + UserConnectionServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: UserConnectionListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "admin", "user_connections") + .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.validate() + } + } + .let { + UserConnectionListPageAsync.builder() + .service(UserConnectionServiceAsyncImpl(clientOptions)) + .streamHandlerExecutor(clientOptions.streamHandlerExecutor) + .params(params) + .response(it) + .build() + } + } + } + } + + private val deleteHandler: Handler = emptyHandler() + + override fun delete( + params: UserConnectionDeleteParams, + 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", "admin", "user_connections", 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) } + } + } + } } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/chat/CompletionServiceAsync.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/chat/CompletionServiceAsync.kt index f52e269..07141ab 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/chat/CompletionServiceAsync.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/chat/CompletionServiceAsync.kt @@ -1,20 +1,92 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package dev.arcade.services.async.chat +import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions -import dev.arcade.models.ChatCompletionCreateParams -import dev.arcade.models.ChatResponse +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.models.chat.ChatRequest +import dev.arcade.models.chat.ChatResponse +import dev.arcade.models.chat.completions.CompletionCreateParams import java.util.concurrent.CompletableFuture +import java.util.function.Consumer interface CompletionServiceAsync { + /** + * 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): CompletionServiceAsync + /** Interact with language models via OpenAI's chat completions API */ - @JvmOverloads + fun create(params: CompletionCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see create */ fun create( - params: ChatCompletionCreateParams, + params: CompletionCreateParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + + /** @see create */ + fun create( + chatRequest: ChatRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + create(CompletionCreateParams.builder().chatRequest(chatRequest).build(), requestOptions) + + /** @see create */ + fun create(chatRequest: ChatRequest): CompletableFuture = + create(chatRequest, RequestOptions.none()) + + /** + * A view of [CompletionServiceAsync] 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 + ): CompletionServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/chat/completions`, but is otherwise the same as + * [CompletionServiceAsync.create]. + */ + fun create( + params: CompletionCreateParams + ): CompletableFuture> = create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: CompletionCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see create */ + fun create( + chatRequest: ChatRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + create( + CompletionCreateParams.builder().chatRequest(chatRequest).build(), + requestOptions, + ) + + /** @see create */ + fun create(chatRequest: ChatRequest): CompletableFuture> = + create(chatRequest, RequestOptions.none()) + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/chat/CompletionServiceAsyncImpl.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/chat/CompletionServiceAsyncImpl.kt index a7d0aff..7e99ff9 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/chat/CompletionServiceAsyncImpl.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/chat/CompletionServiceAsyncImpl.kt @@ -4,49 +4,83 @@ package dev.arcade.services.async.chat import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions +import dev.arcade.core.handlers.errorBodyHandler import dev.arcade.core.handlers.errorHandler import dev.arcade.core.handlers.jsonHandler -import dev.arcade.core.handlers.withErrorHandler import dev.arcade.core.http.HttpMethod import dev.arcade.core.http.HttpRequest +import dev.arcade.core.http.HttpResponse import dev.arcade.core.http.HttpResponse.Handler -import dev.arcade.core.json +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.core.http.json +import dev.arcade.core.http.parseable import dev.arcade.core.prepareAsync -import dev.arcade.errors.ArcadeError -import dev.arcade.models.ChatCompletionCreateParams -import dev.arcade.models.ChatResponse +import dev.arcade.models.chat.ChatResponse +import dev.arcade.models.chat.completions.CompletionCreateParams import java.util.concurrent.CompletableFuture +import java.util.function.Consumer class CompletionServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : CompletionServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: CompletionServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): CompletionServiceAsync.WithRawResponse = withRawResponse - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withOptions(modifier: Consumer): CompletionServiceAsync = + CompletionServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) - /** Interact with language models via OpenAI's chat completions API */ override fun create( - params: ChatCompletionCreateParams, + params: CompletionCreateParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "chat", "completions") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { createHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): CompletableFuture = + // post /v1/chat/completions + withRawResponse().create(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + CompletionServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): CompletionServiceAsync.WithRawResponse = + CompletionServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: CompletionCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "chat", "completions") + .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() + } + } } - } + } + } } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/tools/FormattedServiceAsync.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/tools/FormattedServiceAsync.kt index e74f1b4..385de17 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/tools/FormattedServiceAsync.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/tools/FormattedServiceAsync.kt @@ -1,32 +1,162 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package dev.arcade.services.async.tools +import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions -import dev.arcade.models.ToolFormattedGetParams -import dev.arcade.models.ToolFormattedGetResponse -import dev.arcade.models.ToolFormattedListPageAsync -import dev.arcade.models.ToolFormattedListParams +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.models.tools.formatted.FormattedGetParams +import dev.arcade.models.tools.formatted.FormattedGetResponse +import dev.arcade.models.tools.formatted.FormattedListPageAsync +import dev.arcade.models.tools.formatted.FormattedListParams import java.util.concurrent.CompletableFuture +import java.util.function.Consumer interface FormattedServiceAsync { + /** + * 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): FormattedServiceAsync + /** * Returns a page of tools from the engine configuration, optionally filtered by toolkit, * formatted for a specific provider */ - @JvmOverloads + fun list(): CompletableFuture = list(FormattedListParams.none()) + + /** @see list */ fun list( - params: ToolFormattedListParams, + params: FormattedListParams = FormattedListParams.none(), requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture + ): CompletableFuture + + /** @see list */ + fun list( + params: FormattedListParams = FormattedListParams.none() + ): CompletableFuture = list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): CompletableFuture = + list(FormattedListParams.none(), requestOptions) /** Returns the formatted tool specification for a specific tool, given a provider */ - @JvmOverloads + fun get(name: String): CompletableFuture = + get(name, FormattedGetParams.none()) + + /** @see get */ + fun get( + name: String, + params: FormattedGetParams = FormattedGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + get(params.toBuilder().name(name).build(), requestOptions) + + /** @see get */ + fun get( + name: String, + params: FormattedGetParams = FormattedGetParams.none(), + ): CompletableFuture = get(name, params, RequestOptions.none()) + + /** @see get */ fun get( - params: ToolFormattedGetParams, + params: FormattedGetParams, requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture + ): CompletableFuture + + /** @see get */ + fun get(params: FormattedGetParams): CompletableFuture = + get(params, RequestOptions.none()) + + /** @see get */ + fun get(name: String, requestOptions: RequestOptions): CompletableFuture = + get(name, FormattedGetParams.none(), requestOptions) + + /** + * A view of [FormattedServiceAsync] 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 + ): FormattedServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `get /v1/formatted_tools`, but is otherwise the same as + * [FormattedServiceAsync.list]. + */ + fun list(): CompletableFuture> = + list(FormattedListParams.none()) + + /** @see list */ + fun list( + params: FormattedListParams = FormattedListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list( + params: FormattedListParams = FormattedListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(FormattedListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/formatted_tools/{name}`, but is otherwise the + * same as [FormattedServiceAsync.get]. + */ + fun get(name: String): CompletableFuture> = + get(name, FormattedGetParams.none()) + + /** @see get */ + fun get( + name: String, + params: FormattedGetParams = FormattedGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + get(params.toBuilder().name(name).build(), requestOptions) + + /** @see get */ + fun get( + name: String, + params: FormattedGetParams = FormattedGetParams.none(), + ): CompletableFuture> = + get(name, params, RequestOptions.none()) + + /** @see get */ + fun get( + params: FormattedGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see get */ + fun get( + params: FormattedGetParams + ): CompletableFuture> = + get(params, RequestOptions.none()) + + /** @see get */ + fun get( + name: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + get(name, FormattedGetParams.none(), requestOptions) + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/tools/FormattedServiceAsyncImpl.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/tools/FormattedServiceAsyncImpl.kt index e042d1c..b9c590c 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/tools/FormattedServiceAsyncImpl.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/tools/FormattedServiceAsyncImpl.kt @@ -4,82 +4,134 @@ package dev.arcade.services.async.tools import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions +import dev.arcade.core.checkRequired +import dev.arcade.core.handlers.errorBodyHandler import dev.arcade.core.handlers.errorHandler import dev.arcade.core.handlers.jsonHandler -import dev.arcade.core.handlers.withErrorHandler import dev.arcade.core.http.HttpMethod import dev.arcade.core.http.HttpRequest +import dev.arcade.core.http.HttpResponse import dev.arcade.core.http.HttpResponse.Handler +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.core.http.parseable import dev.arcade.core.prepareAsync -import dev.arcade.errors.ArcadeError -import dev.arcade.models.ToolFormattedGetParams -import dev.arcade.models.ToolFormattedGetResponse -import dev.arcade.models.ToolFormattedListPageAsync -import dev.arcade.models.ToolFormattedListParams +import dev.arcade.models.tools.formatted.FormattedGetParams +import dev.arcade.models.tools.formatted.FormattedGetResponse +import dev.arcade.models.tools.formatted.FormattedListPageAsync +import dev.arcade.models.tools.formatted.FormattedListPageResponse +import dev.arcade.models.tools.formatted.FormattedListParams import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull class FormattedServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : FormattedServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: FormattedServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): FormattedServiceAsync.WithRawResponse = withRawResponse - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withOptions(modifier: Consumer): FormattedServiceAsync = + FormattedServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) - /** - * Returns a page of tools from the engine configuration, optionally filtered by toolkit, - * formatted for a specific provider - */ override fun list( - params: ToolFormattedListParams, + params: FormattedListParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "formatted_tools") - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - .let { ToolFormattedListPageAsync.of(this, params, it) } - } - } + ): CompletableFuture = + // get /v1/formatted_tools + withRawResponse().list(params, requestOptions).thenApply { it.parse() } - private val getHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** Returns the formatted tool specification for a specific tool, given a provider */ override fun get( - params: ToolFormattedGetParams, + params: FormattedGetParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "formatted_tools", params.getPathParam(0)) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { getHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): CompletableFuture = + // get /v1/formatted_tools/{name} + withRawResponse().get(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + FormattedServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): FormattedServiceAsync.WithRawResponse = + FormattedServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: FormattedListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "formatted_tools") + .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.validate() + } + } + .let { + FormattedListPageAsync.builder() + .service(FormattedServiceAsyncImpl(clientOptions)) + .streamHandlerExecutor(clientOptions.streamHandlerExecutor) + .params(params) + .response(it) + .build() + } + } + } + } + + private val getHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun get( + params: FormattedGetParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("name", params.name().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "formatted_tools", 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/arcade-java-core/src/main/kotlin/dev/arcade/services/async/tools/ScheduledServiceAsync.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/tools/ScheduledServiceAsync.kt index c0ea1ea..e72a50c 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/tools/ScheduledServiceAsync.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/tools/ScheduledServiceAsync.kt @@ -1,29 +1,159 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package dev.arcade.services.async.tools +import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions -import dev.arcade.models.ToolScheduledGetParams -import dev.arcade.models.ToolScheduledGetResponse -import dev.arcade.models.ToolScheduledListPageAsync -import dev.arcade.models.ToolScheduledListParams +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.models.tools.scheduled.ScheduledGetParams +import dev.arcade.models.tools.scheduled.ScheduledGetResponse +import dev.arcade.models.tools.scheduled.ScheduledListPageAsync +import dev.arcade.models.tools.scheduled.ScheduledListParams import java.util.concurrent.CompletableFuture +import java.util.function.Consumer interface ScheduledServiceAsync { + /** + * 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): ScheduledServiceAsync + /** Returns a page of scheduled tool executions */ - @JvmOverloads + fun list(): CompletableFuture = list(ScheduledListParams.none()) + + /** @see list */ fun list( - params: ToolScheduledListParams, + params: ScheduledListParams = ScheduledListParams.none(), requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture + ): CompletableFuture + + /** @see list */ + fun list( + params: ScheduledListParams = ScheduledListParams.none() + ): CompletableFuture = list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): CompletableFuture = + list(ScheduledListParams.none(), requestOptions) /** Returns the details for a specific scheduled tool execution */ - @JvmOverloads + fun get(id: String): CompletableFuture = + get(id, ScheduledGetParams.none()) + + /** @see get */ fun get( - params: ToolScheduledGetParams, + id: String, + params: ScheduledGetParams = ScheduledGetParams.none(), requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture + ): CompletableFuture = + get(params.toBuilder().id(id).build(), requestOptions) + + /** @see get */ + fun get( + id: String, + params: ScheduledGetParams = ScheduledGetParams.none(), + ): CompletableFuture = get(id, params, RequestOptions.none()) + + /** @see get */ + fun get( + params: ScheduledGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see get */ + fun get(params: ScheduledGetParams): CompletableFuture = + get(params, RequestOptions.none()) + + /** @see get */ + fun get(id: String, requestOptions: RequestOptions): CompletableFuture = + get(id, ScheduledGetParams.none(), requestOptions) + + /** + * A view of [ScheduledServiceAsync] 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 + ): ScheduledServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `get /v1/scheduled_tools`, but is otherwise the same as + * [ScheduledServiceAsync.list]. + */ + fun list(): CompletableFuture> = + list(ScheduledListParams.none()) + + /** @see list */ + fun list( + params: ScheduledListParams = ScheduledListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list( + params: ScheduledListParams = ScheduledListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(ScheduledListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/scheduled_tools/{id}`, but is otherwise the same + * as [ScheduledServiceAsync.get]. + */ + fun get(id: String): CompletableFuture> = + get(id, ScheduledGetParams.none()) + + /** @see get */ + fun get( + id: String, + params: ScheduledGetParams = ScheduledGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + get(params.toBuilder().id(id).build(), requestOptions) + + /** @see get */ + fun get( + id: String, + params: ScheduledGetParams = ScheduledGetParams.none(), + ): CompletableFuture> = + get(id, params, RequestOptions.none()) + + /** @see get */ + fun get( + params: ScheduledGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see get */ + fun get( + params: ScheduledGetParams + ): CompletableFuture> = + get(params, RequestOptions.none()) + + /** @see get */ + fun get( + id: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + get(id, ScheduledGetParams.none(), requestOptions) + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/tools/ScheduledServiceAsyncImpl.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/tools/ScheduledServiceAsyncImpl.kt index cedb983..a448a07 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/async/tools/ScheduledServiceAsyncImpl.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/async/tools/ScheduledServiceAsyncImpl.kt @@ -4,79 +4,134 @@ package dev.arcade.services.async.tools import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions +import dev.arcade.core.checkRequired +import dev.arcade.core.handlers.errorBodyHandler import dev.arcade.core.handlers.errorHandler import dev.arcade.core.handlers.jsonHandler -import dev.arcade.core.handlers.withErrorHandler import dev.arcade.core.http.HttpMethod import dev.arcade.core.http.HttpRequest +import dev.arcade.core.http.HttpResponse import dev.arcade.core.http.HttpResponse.Handler +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.core.http.parseable import dev.arcade.core.prepareAsync -import dev.arcade.errors.ArcadeError -import dev.arcade.models.ToolScheduledGetParams -import dev.arcade.models.ToolScheduledGetResponse -import dev.arcade.models.ToolScheduledListPageAsync -import dev.arcade.models.ToolScheduledListParams +import dev.arcade.models.tools.scheduled.ScheduledGetParams +import dev.arcade.models.tools.scheduled.ScheduledGetResponse +import dev.arcade.models.tools.scheduled.ScheduledListPageAsync +import dev.arcade.models.tools.scheduled.ScheduledListPageResponse +import dev.arcade.models.tools.scheduled.ScheduledListParams import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull class ScheduledServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : ScheduledServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: ScheduledServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): ScheduledServiceAsync.WithRawResponse = withRawResponse - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withOptions(modifier: Consumer): ScheduledServiceAsync = + ScheduledServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) - /** Returns a page of scheduled tool executions */ override fun list( - params: ToolScheduledListParams, + params: ScheduledListParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "scheduled_tools") - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - .let { ToolScheduledListPageAsync.of(this, params, it) } - } - } + ): CompletableFuture = + // get /v1/scheduled_tools + withRawResponse().list(params, requestOptions).thenApply { it.parse() } - private val getHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** Returns the details for a specific scheduled tool execution */ override fun get( - params: ToolScheduledGetParams, + params: ScheduledGetParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "scheduled_tools", params.getPathParam(0)) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { getHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): CompletableFuture = + // get /v1/scheduled_tools/{id} + withRawResponse().get(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ScheduledServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): ScheduledServiceAsync.WithRawResponse = + ScheduledServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: ScheduledListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "scheduled_tools") + .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.validate() + } + } + .let { + ScheduledListPageAsync.builder() + .service(ScheduledServiceAsyncImpl(clientOptions)) + .streamHandlerExecutor(clientOptions.streamHandlerExecutor) + .params(params) + .response(it) + .build() + } + } + } + } + + private val getHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun get( + params: ScheduledGetParams, + 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", "scheduled_tools", 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/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/AdminService.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/AdminService.kt index 3483ce8..3938980 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/AdminService.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/AdminService.kt @@ -2,15 +2,46 @@ package dev.arcade.services.blocking +import dev.arcade.core.ClientOptions import dev.arcade.services.blocking.admin.AuthProviderService import dev.arcade.services.blocking.admin.SecretService import dev.arcade.services.blocking.admin.UserConnectionService +import java.util.function.Consumer interface AdminService { + /** + * 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): AdminService + fun userConnections(): UserConnectionService fun authProviders(): AuthProviderService fun secrets(): SecretService + + /** A view of [AdminService] 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): AdminService.WithRawResponse + + fun userConnections(): UserConnectionService.WithRawResponse + + fun authProviders(): AuthProviderService.WithRawResponse + + fun secrets(): SecretService.WithRawResponse + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/AdminServiceImpl.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/AdminServiceImpl.kt index b08d2d5..cd24528 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/AdminServiceImpl.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/AdminServiceImpl.kt @@ -9,10 +9,15 @@ import dev.arcade.services.blocking.admin.SecretService import dev.arcade.services.blocking.admin.SecretServiceImpl import dev.arcade.services.blocking.admin.UserConnectionService import dev.arcade.services.blocking.admin.UserConnectionServiceImpl +import java.util.function.Consumer class AdminServiceImpl internal constructor(private val clientOptions: ClientOptions) : AdminService { + private val withRawResponse: AdminService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + private val userConnections: UserConnectionService by lazy { UserConnectionServiceImpl(clientOptions) } @@ -23,9 +28,43 @@ class AdminServiceImpl internal constructor(private val clientOptions: ClientOpt private val secrets: SecretService by lazy { SecretServiceImpl(clientOptions) } + override fun withRawResponse(): AdminService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): AdminService = + AdminServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + override fun userConnections(): UserConnectionService = userConnections override fun authProviders(): AuthProviderService = authProviders override fun secrets(): SecretService = secrets + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + AdminService.WithRawResponse { + + private val userConnections: UserConnectionService.WithRawResponse by lazy { + UserConnectionServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val authProviders: AuthProviderService.WithRawResponse by lazy { + AuthProviderServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val secrets: SecretService.WithRawResponse by lazy { + SecretServiceImpl.WithRawResponseImpl(clientOptions) + } + + override fun withOptions( + modifier: Consumer + ): AdminService.WithRawResponse = + AdminServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun userConnections(): UserConnectionService.WithRawResponse = userConnections + + override fun authProviders(): AuthProviderService.WithRawResponse = authProviders + + override fun secrets(): SecretService.WithRawResponse = secrets + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/AuthService.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/AuthService.kt index 966d8dc..625fa2f 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/AuthService.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/AuthService.kt @@ -1,40 +1,219 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package dev.arcade.services.blocking +import com.google.errorprone.annotations.MustBeClosed +import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions -import dev.arcade.models.AuthAuthorizeParams -import dev.arcade.models.AuthConfirmUserParams -import dev.arcade.models.AuthStatusParams +import dev.arcade.core.http.HttpResponseFor import dev.arcade.models.AuthorizationResponse -import dev.arcade.models.ConfirmUserResponse +import dev.arcade.models.auth.AuthAuthorizeParams +import dev.arcade.models.auth.AuthConfirmUserParams +import dev.arcade.models.auth.AuthRequest +import dev.arcade.models.auth.AuthStatusParams +import dev.arcade.models.auth.ConfirmUserRequest +import dev.arcade.models.auth.ConfirmUserResponse +import java.util.function.Consumer interface AuthService { + /** + * 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): AuthService + /** Starts the authorization process for given authorization requirements */ - @JvmOverloads + fun authorize(params: AuthAuthorizeParams): AuthorizationResponse = + authorize(params, RequestOptions.none()) + + /** @see authorize */ fun authorize( params: AuthAuthorizeParams, requestOptions: RequestOptions = RequestOptions.none(), ): AuthorizationResponse + /** @see authorize */ + fun authorize( + authRequest: AuthRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): AuthorizationResponse = + authorize(AuthAuthorizeParams.builder().authRequest(authRequest).build(), requestOptions) + + /** @see authorize */ + fun authorize(authRequest: AuthRequest): AuthorizationResponse = + authorize(authRequest, RequestOptions.none()) + /** Confirms a user's details during an authorization flow */ - @JvmOverloads + fun confirmUser(params: AuthConfirmUserParams): ConfirmUserResponse = + confirmUser(params, RequestOptions.none()) + + /** @see confirmUser */ fun confirmUser( params: AuthConfirmUserParams, requestOptions: RequestOptions = RequestOptions.none(), ): ConfirmUserResponse + /** @see confirmUser */ + fun confirmUser( + confirmUserRequest: ConfirmUserRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): ConfirmUserResponse = + confirmUser( + AuthConfirmUserParams.builder().confirmUserRequest(confirmUserRequest).build(), + requestOptions, + ) + + /** @see confirmUser */ + fun confirmUser(confirmUserRequest: ConfirmUserRequest): ConfirmUserResponse = + confirmUser(confirmUserRequest, RequestOptions.none()) + /** * Checks the status of an ongoing authorization process for a specific tool. If 'wait' param is * present, does not respond until either the auth status becomes completed or the timeout is * reached. */ - @JvmOverloads + fun status(params: AuthStatusParams): AuthorizationResponse = + status(params, RequestOptions.none()) + + /** @see status */ fun status( params: AuthStatusParams, requestOptions: RequestOptions = RequestOptions.none(), ): AuthorizationResponse + + /** A view of [AuthService] 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): AuthService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/auth/authorize`, but is otherwise the same as + * [AuthService.authorize]. + */ + @MustBeClosed + fun authorize(params: AuthAuthorizeParams): HttpResponseFor = + authorize(params, RequestOptions.none()) + + /** @see authorize */ + @MustBeClosed + fun authorize( + params: AuthAuthorizeParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see authorize */ + @MustBeClosed + fun authorize( + authRequest: AuthRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + authorize( + AuthAuthorizeParams.builder().authRequest(authRequest).build(), + requestOptions, + ) + + /** @see authorize */ + @MustBeClosed + fun authorize(authRequest: AuthRequest): HttpResponseFor = + authorize(authRequest, RequestOptions.none()) + + /** + * Returns a raw HTTP response for `post /v1/auth/confirm_user`, but is otherwise the same + * as [AuthService.confirmUser]. + */ + @MustBeClosed + fun confirmUser(params: AuthConfirmUserParams): HttpResponseFor = + confirmUser(params, RequestOptions.none()) + + /** @see confirmUser */ + @MustBeClosed + fun confirmUser( + params: AuthConfirmUserParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see confirmUser */ + @MustBeClosed + fun confirmUser( + confirmUserRequest: ConfirmUserRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + confirmUser( + AuthConfirmUserParams.builder().confirmUserRequest(confirmUserRequest).build(), + requestOptions, + ) + + /** @see confirmUser */ + @MustBeClosed + fun confirmUser( + confirmUserRequest: ConfirmUserRequest + ): HttpResponseFor = + confirmUser(confirmUserRequest, RequestOptions.none()) + + /** + * Returns a raw HTTP response for `get /v1/auth/status`, but is otherwise the same as + * [AuthService.status]. + */ + @MustBeClosed + fun status(params: AuthStatusParams): HttpResponseFor = + status(params, RequestOptions.none()) + + /** @see status */ + @MustBeClosed + fun status( + params: AuthStatusParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } + + // ------------------------------------------------------------------------- + // Start of manually added code + // ------------------------------------------------------------------------- + + /** + * Starts the authorization process for a given provider and scopes. + * + * @param userId The user ID for which authorization is being requested. + * @param provider The authorization provider (e.g., 'github', 'google', 'linkedin', + * 'microsoft', 'slack', 'spotify', 'x', 'zoom'). + * @param providerType The type of authorization provider. Optional, defaults to 'oauth2'. + * @param scopes A list of scopes required for authorization, if any. + * @return The authorization response based on the request. + */ + fun start( + userId: String, + provider: String, + providerType: String = "oauth2", + scopes: List = emptyList(), + ): AuthorizationResponse + + /** + * Waits for the authorization process to complete, for example, + *

+     *     val authResponse = client.auth().start("you@example.com", "github")
+     *     val authResult = client.auth().waitForCompletion(authResponse)
+     * 
+ */ + fun waitForCompletion(authorizationResponse: AuthorizationResponse): AuthorizationResponse + + /** + * Waits for the authorization process to complete, for example, + *

+     *     val authResponse = client.auth().start("you@example.com", "github")
+     *     val authResult = client.auth().waitForCompletion(authResponse.id().get())
+     * 
+ */ + fun waitForCompletion(authorizationResponseId: String): AuthorizationResponse } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/AuthServiceImpl.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/AuthServiceImpl.kt index 3f29cc3..9170dba 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/AuthServiceImpl.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/AuthServiceImpl.kt @@ -4,100 +4,214 @@ package dev.arcade.services.blocking import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions +import dev.arcade.core.handlers.errorBodyHandler import dev.arcade.core.handlers.errorHandler import dev.arcade.core.handlers.jsonHandler -import dev.arcade.core.handlers.withErrorHandler import dev.arcade.core.http.HttpMethod import dev.arcade.core.http.HttpRequest +import dev.arcade.core.http.HttpResponse import dev.arcade.core.http.HttpResponse.Handler -import dev.arcade.core.json +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.core.http.json +import dev.arcade.core.http.parseable import dev.arcade.core.prepare -import dev.arcade.errors.ArcadeError -import dev.arcade.models.AuthAuthorizeParams -import dev.arcade.models.AuthConfirmUserParams -import dev.arcade.models.AuthStatusParams import dev.arcade.models.AuthorizationResponse -import dev.arcade.models.ConfirmUserResponse +import dev.arcade.models.auth.AuthAuthorizeParams +import dev.arcade.models.auth.AuthConfirmUserParams +import dev.arcade.models.auth.AuthRequest +import dev.arcade.models.auth.AuthStatusParams +import dev.arcade.models.auth.ConfirmUserResponse +import java.util.function.Consumer class AuthServiceImpl internal constructor(private val clientOptions: ClientOptions) : AuthService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + companion object { + const val DEFAULT_LONGPOLL_WAIT_TIME = 45L + } + + private val withRawResponse: AuthService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val authorizeHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withRawResponse(): AuthService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): AuthService = + AuthServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) - /** Starts the authorization process for given authorization requirements */ override fun authorize( params: AuthAuthorizeParams, requestOptions: RequestOptions, - ): AuthorizationResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "auth", "authorize") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { authorizeHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } + ): AuthorizationResponse = + // post /v1/auth/authorize + withRawResponse().authorize(params, requestOptions).parse() - private val confirmUserHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** Confirms a user's details during an authorization flow */ override fun confirmUser( params: AuthConfirmUserParams, requestOptions: RequestOptions, - ): ConfirmUserResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "auth", "confirm_user") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { confirmUserHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } + ): ConfirmUserResponse = + // post /v1/auth/confirm_user + withRawResponse().confirmUser(params, requestOptions).parse() - private val statusHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** - * Checks the status of an ongoing authorization process for a specific tool. If 'wait' param is - * present, does not respond until either the auth status becomes completed or the timeout is - * reached. - */ override fun status( params: AuthStatusParams, requestOptions: RequestOptions, + ): AuthorizationResponse = + // get /v1/auth/status + withRawResponse().status(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + AuthService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): AuthService.WithRawResponse = + AuthServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val authorizeHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun authorize( + params: AuthAuthorizeParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "auth", "authorize") + .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 { authorizeHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val confirmUserHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun confirmUser( + params: AuthConfirmUserParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "auth", "confirm_user") + .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 { confirmUserHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val statusHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun status( + params: AuthStatusParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "auth", "status") + .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 { statusHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + // ------------------------------------------------------------------------- + // Start of manually added code + // ------------------------------------------------------------------------- + + override fun start( + userId: String, + provider: String, + providerType: String, + scopes: List, ): AuthorizationResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "auth", "status") + return authorize( + AuthAuthorizeParams.builder() + .authRequest( + AuthRequest.builder() + .userId(userId) + .authRequirement( + AuthRequest.AuthRequirement.builder() + .providerId(provider) + .providerType(providerType) + .oauth2( + AuthRequest.AuthRequirement.Oauth2.builder() + .scopes(scopes) + .build() + ) + .build() + ) + .build() + ) .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) + ) + } + + override fun waitForCompletion( + authorizationResponse: AuthorizationResponse + ): AuthorizationResponse { + var response = authorizationResponse + while (AuthorizationResponse.Status.COMPLETED != response.status().get()) { + response = + status( + AuthStatusParams.builder() + .id(response.id().get()) + .wait(DEFAULT_LONGPOLL_WAIT_TIME) + .build() + ) + } return response - .use { statusHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } + } + + override fun waitForCompletion(authorizationResponseId: String): AuthorizationResponse { + return waitForCompletion( + status( + AuthStatusParams.builder() + .id(authorizationResponseId) + .wait(DEFAULT_LONGPOLL_WAIT_TIME) + .build() + ) + ) } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/ChatService.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/ChatService.kt index 4cd9d6d..a341edd 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/ChatService.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/ChatService.kt @@ -2,9 +2,36 @@ package dev.arcade.services.blocking +import dev.arcade.core.ClientOptions import dev.arcade.services.blocking.chat.CompletionService +import java.util.function.Consumer interface ChatService { + /** + * 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): ChatService + fun completions(): CompletionService + + /** A view of [ChatService] 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): ChatService.WithRawResponse + + fun completions(): CompletionService.WithRawResponse + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/ChatServiceImpl.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/ChatServiceImpl.kt index 50b6e51..8a86055 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/ChatServiceImpl.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/ChatServiceImpl.kt @@ -5,10 +5,37 @@ package dev.arcade.services.blocking import dev.arcade.core.ClientOptions import dev.arcade.services.blocking.chat.CompletionService import dev.arcade.services.blocking.chat.CompletionServiceImpl +import java.util.function.Consumer class ChatServiceImpl internal constructor(private val clientOptions: ClientOptions) : ChatService { + private val withRawResponse: ChatService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + private val completions: CompletionService by lazy { CompletionServiceImpl(clientOptions) } + override fun withRawResponse(): ChatService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): ChatService = + ChatServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + override fun completions(): CompletionService = completions + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ChatService.WithRawResponse { + + private val completions: CompletionService.WithRawResponse by lazy { + CompletionServiceImpl.WithRawResponseImpl(clientOptions) + } + + override fun withOptions( + modifier: Consumer + ): ChatService.WithRawResponse = + ChatServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun completions(): CompletionService.WithRawResponse = completions + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/HealthService.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/HealthService.kt index 3245258..8c471f3 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/HealthService.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/HealthService.kt @@ -1,19 +1,78 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package dev.arcade.services.blocking +import com.google.errorprone.annotations.MustBeClosed +import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions -import dev.arcade.models.HealthCheckParams -import dev.arcade.models.HealthSchema +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.models.health.HealthCheckParams +import dev.arcade.models.health.HealthSchema +import java.util.function.Consumer interface HealthService { + /** + * 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): HealthService + /** Check if Arcade Engine is healthy */ - @JvmOverloads + fun check(): HealthSchema = check(HealthCheckParams.none()) + + /** @see check */ fun check( - params: HealthCheckParams, + params: HealthCheckParams = HealthCheckParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): HealthSchema + + /** @see check */ + fun check(params: HealthCheckParams = HealthCheckParams.none()): HealthSchema = + check(params, RequestOptions.none()) + + /** @see check */ + fun check(requestOptions: RequestOptions): HealthSchema = + check(HealthCheckParams.none(), requestOptions) + + /** A view of [HealthService] 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): HealthService.WithRawResponse + + /** + * Returns a raw HTTP response for `get /v1/health`, but is otherwise the same as + * [HealthService.check]. + */ + @MustBeClosed fun check(): HttpResponseFor = check(HealthCheckParams.none()) + + /** @see check */ + @MustBeClosed + fun check( + params: HealthCheckParams = HealthCheckParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see check */ + @MustBeClosed + fun check( + params: HealthCheckParams = HealthCheckParams.none() + ): HttpResponseFor = check(params, RequestOptions.none()) + + /** @see check */ + @MustBeClosed + fun check(requestOptions: RequestOptions): HttpResponseFor = + check(HealthCheckParams.none(), requestOptions) + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/HealthServiceImpl.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/HealthServiceImpl.kt index 51d6afa..73620ef 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/HealthServiceImpl.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/HealthServiceImpl.kt @@ -4,40 +4,74 @@ package dev.arcade.services.blocking import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions +import dev.arcade.core.handlers.errorBodyHandler import dev.arcade.core.handlers.errorHandler import dev.arcade.core.handlers.jsonHandler -import dev.arcade.core.handlers.withErrorHandler import dev.arcade.core.http.HttpMethod import dev.arcade.core.http.HttpRequest +import dev.arcade.core.http.HttpResponse import dev.arcade.core.http.HttpResponse.Handler +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.core.http.parseable import dev.arcade.core.prepare -import dev.arcade.errors.ArcadeError -import dev.arcade.models.HealthCheckParams -import dev.arcade.models.HealthSchema +import dev.arcade.models.health.HealthCheckParams +import dev.arcade.models.health.HealthSchema +import java.util.function.Consumer class HealthServiceImpl internal constructor(private val clientOptions: ClientOptions) : HealthService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) - - private val checkHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** Check if Arcade Engine is healthy */ - override fun check(params: HealthCheckParams, requestOptions: RequestOptions): HealthSchema { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "health") - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { checkHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + private val withRawResponse: HealthService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): HealthService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): HealthService = + HealthServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun check(params: HealthCheckParams, requestOptions: RequestOptions): HealthSchema = + // get /v1/health + withRawResponse().check(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + HealthService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): HealthService.WithRawResponse = + HealthServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val checkHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun check( + params: HealthCheckParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "health") + .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 { checkHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } + } } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/ToolService.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/ToolService.kt index 3ed53bc..22a6d53 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/ToolService.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/ToolService.kt @@ -1,52 +1,274 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package dev.arcade.services.blocking +import com.google.errorprone.annotations.MustBeClosed +import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions +import dev.arcade.core.http.HttpResponseFor import dev.arcade.models.AuthorizationResponse -import dev.arcade.models.ExecuteToolResponse -import dev.arcade.models.ToolAuthorizeParams -import dev.arcade.models.ToolDefinition -import dev.arcade.models.ToolExecuteParams -import dev.arcade.models.ToolGetParams -import dev.arcade.models.ToolListPage -import dev.arcade.models.ToolListParams +import dev.arcade.models.tools.AuthorizeToolRequest +import dev.arcade.models.tools.ExecuteToolRequest +import dev.arcade.models.tools.ExecuteToolResponse +import dev.arcade.models.tools.ToolAuthorizeParams +import dev.arcade.models.tools.ToolDefinition +import dev.arcade.models.tools.ToolExecuteParams +import dev.arcade.models.tools.ToolGetParams +import dev.arcade.models.tools.ToolListPage +import dev.arcade.models.tools.ToolListParams import dev.arcade.services.blocking.tools.FormattedService import dev.arcade.services.blocking.tools.ScheduledService +import java.util.function.Consumer interface ToolService { + /** + * 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): ToolService + fun scheduled(): ScheduledService fun formatted(): FormattedService /** Returns a page of tools from the engine configuration, optionally filtered by toolkit */ - @JvmOverloads + fun list(): ToolListPage = list(ToolListParams.none()) + + /** @see list */ fun list( - params: ToolListParams, + params: ToolListParams = ToolListParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): ToolListPage + /** @see list */ + fun list(params: ToolListParams = ToolListParams.none()): ToolListPage = + list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): ToolListPage = + list(ToolListParams.none(), requestOptions) + /** Authorizes a user for a specific tool by name */ - @JvmOverloads + fun authorize(params: ToolAuthorizeParams): AuthorizationResponse = + authorize(params, RequestOptions.none()) + + /** @see authorize */ fun authorize( params: ToolAuthorizeParams, requestOptions: RequestOptions = RequestOptions.none(), ): AuthorizationResponse + /** @see authorize */ + fun authorize( + authorizeToolRequest: AuthorizeToolRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): AuthorizationResponse = + authorize( + ToolAuthorizeParams.builder().authorizeToolRequest(authorizeToolRequest).build(), + requestOptions, + ) + + /** @see authorize */ + fun authorize(authorizeToolRequest: AuthorizeToolRequest): AuthorizationResponse = + authorize(authorizeToolRequest, RequestOptions.none()) + /** Executes a tool by name and arguments */ - @JvmOverloads + fun execute(params: ToolExecuteParams): ExecuteToolResponse = + execute(params, RequestOptions.none()) + + /** @see execute */ fun execute( params: ToolExecuteParams, requestOptions: RequestOptions = RequestOptions.none(), ): ExecuteToolResponse + /** @see execute */ + fun execute( + executeToolRequest: ExecuteToolRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): ExecuteToolResponse = + execute( + ToolExecuteParams.builder().executeToolRequest(executeToolRequest).build(), + requestOptions, + ) + + /** @see execute */ + fun execute(executeToolRequest: ExecuteToolRequest): ExecuteToolResponse = + execute(executeToolRequest, RequestOptions.none()) + /** Returns the arcade tool specification for a specific tool */ - @JvmOverloads + fun get(name: String): ToolDefinition = get(name, ToolGetParams.none()) + + /** @see get */ + fun get( + name: String, + params: ToolGetParams = ToolGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): ToolDefinition = get(params.toBuilder().name(name).build(), requestOptions) + + /** @see get */ + fun get(name: String, params: ToolGetParams = ToolGetParams.none()): ToolDefinition = + get(name, params, RequestOptions.none()) + + /** @see get */ fun get( params: ToolGetParams, requestOptions: RequestOptions = RequestOptions.none(), ): ToolDefinition + + /** @see get */ + fun get(params: ToolGetParams): ToolDefinition = get(params, RequestOptions.none()) + + /** @see get */ + fun get(name: String, requestOptions: RequestOptions): ToolDefinition = + get(name, ToolGetParams.none(), requestOptions) + + /** A view of [ToolService] 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): ToolService.WithRawResponse + + fun scheduled(): ScheduledService.WithRawResponse + + fun formatted(): FormattedService.WithRawResponse + + /** + * Returns a raw HTTP response for `get /v1/tools`, but is otherwise the same as + * [ToolService.list]. + */ + @MustBeClosed fun list(): HttpResponseFor = list(ToolListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: ToolListParams = ToolListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see list */ + @MustBeClosed + fun list(params: ToolListParams = ToolListParams.none()): HttpResponseFor = + list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(ToolListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `post /v1/tools/authorize`, but is otherwise the same as + * [ToolService.authorize]. + */ + @MustBeClosed + fun authorize(params: ToolAuthorizeParams): HttpResponseFor = + authorize(params, RequestOptions.none()) + + /** @see authorize */ + @MustBeClosed + fun authorize( + params: ToolAuthorizeParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see authorize */ + @MustBeClosed + fun authorize( + authorizeToolRequest: AuthorizeToolRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + authorize( + ToolAuthorizeParams.builder().authorizeToolRequest(authorizeToolRequest).build(), + requestOptions, + ) + + /** @see authorize */ + @MustBeClosed + fun authorize( + authorizeToolRequest: AuthorizeToolRequest + ): HttpResponseFor = + authorize(authorizeToolRequest, RequestOptions.none()) + + /** + * Returns a raw HTTP response for `post /v1/tools/execute`, but is otherwise the same as + * [ToolService.execute]. + */ + @MustBeClosed + fun execute(params: ToolExecuteParams): HttpResponseFor = + execute(params, RequestOptions.none()) + + /** @see execute */ + @MustBeClosed + fun execute( + params: ToolExecuteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see execute */ + @MustBeClosed + fun execute( + executeToolRequest: ExecuteToolRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + execute( + ToolExecuteParams.builder().executeToolRequest(executeToolRequest).build(), + requestOptions, + ) + + /** @see execute */ + @MustBeClosed + fun execute(executeToolRequest: ExecuteToolRequest): HttpResponseFor = + execute(executeToolRequest, RequestOptions.none()) + + /** + * Returns a raw HTTP response for `get /v1/tools/{name}`, but is otherwise the same as + * [ToolService.get]. + */ + @MustBeClosed + fun get(name: String): HttpResponseFor = get(name, ToolGetParams.none()) + + /** @see get */ + @MustBeClosed + fun get( + name: String, + params: ToolGetParams = ToolGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + get(params.toBuilder().name(name).build(), requestOptions) + + /** @see get */ + @MustBeClosed + fun get( + name: String, + params: ToolGetParams = ToolGetParams.none(), + ): HttpResponseFor = get(name, params, RequestOptions.none()) + + /** @see get */ + @MustBeClosed + fun get( + params: ToolGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see get */ + @MustBeClosed + fun get(params: ToolGetParams): HttpResponseFor = + get(params, RequestOptions.none()) + + /** @see get */ + @MustBeClosed + fun get(name: String, requestOptions: RequestOptions): HttpResponseFor = + get(name, ToolGetParams.none(), requestOptions) + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/ToolServiceImpl.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/ToolServiceImpl.kt index 7dc3997..553f1de 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/ToolServiceImpl.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/ToolServiceImpl.kt @@ -4,130 +4,218 @@ package dev.arcade.services.blocking import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions +import dev.arcade.core.checkRequired +import dev.arcade.core.handlers.errorBodyHandler import dev.arcade.core.handlers.errorHandler import dev.arcade.core.handlers.jsonHandler -import dev.arcade.core.handlers.withErrorHandler import dev.arcade.core.http.HttpMethod import dev.arcade.core.http.HttpRequest +import dev.arcade.core.http.HttpResponse import dev.arcade.core.http.HttpResponse.Handler -import dev.arcade.core.json +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.core.http.json +import dev.arcade.core.http.parseable import dev.arcade.core.prepare -import dev.arcade.errors.ArcadeError import dev.arcade.models.AuthorizationResponse -import dev.arcade.models.ExecuteToolResponse -import dev.arcade.models.ToolAuthorizeParams -import dev.arcade.models.ToolDefinition -import dev.arcade.models.ToolExecuteParams -import dev.arcade.models.ToolGetParams -import dev.arcade.models.ToolListPage -import dev.arcade.models.ToolListParams +import dev.arcade.models.tools.ExecuteToolResponse +import dev.arcade.models.tools.ToolAuthorizeParams +import dev.arcade.models.tools.ToolDefinition +import dev.arcade.models.tools.ToolExecuteParams +import dev.arcade.models.tools.ToolGetParams +import dev.arcade.models.tools.ToolListPage +import dev.arcade.models.tools.ToolListPageResponse +import dev.arcade.models.tools.ToolListParams import dev.arcade.services.blocking.tools.FormattedService import dev.arcade.services.blocking.tools.FormattedServiceImpl import dev.arcade.services.blocking.tools.ScheduledService import dev.arcade.services.blocking.tools.ScheduledServiceImpl +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull class ToolServiceImpl internal constructor(private val clientOptions: ClientOptions) : ToolService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: ToolService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } private val scheduled: ScheduledService by lazy { ScheduledServiceImpl(clientOptions) } private val formatted: FormattedService by lazy { FormattedServiceImpl(clientOptions) } + override fun withRawResponse(): ToolService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): ToolService = + ToolServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + override fun scheduled(): ScheduledService = scheduled override fun formatted(): FormattedService = formatted - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** Returns a page of tools from the engine configuration, optionally filtered by toolkit */ - override fun list(params: ToolListParams, requestOptions: RequestOptions): ToolListPage { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "tools") - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - .let { ToolListPage.of(this, params, it) } - } - - private val authorizeHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun list(params: ToolListParams, requestOptions: RequestOptions): ToolListPage = + // get /v1/tools + withRawResponse().list(params, requestOptions).parse() - /** Authorizes a user for a specific tool by name */ override fun authorize( params: ToolAuthorizeParams, requestOptions: RequestOptions, - ): AuthorizationResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "tools", "authorize") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { authorizeHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - - private val executeHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + ): AuthorizationResponse = + // post /v1/tools/authorize + withRawResponse().authorize(params, requestOptions).parse() - /** Executes a tool by name and arguments */ override fun execute( params: ToolExecuteParams, requestOptions: RequestOptions, - ): ExecuteToolResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "tools", "execute") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { executeHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): ExecuteToolResponse = + // post /v1/tools/execute + withRawResponse().execute(params, requestOptions).parse() + + override fun get(params: ToolGetParams, requestOptions: RequestOptions): ToolDefinition = + // get /v1/tools/{name} + withRawResponse().get(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ToolService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + private val scheduled: ScheduledService.WithRawResponse by lazy { + ScheduledServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val formatted: FormattedService.WithRawResponse by lazy { + FormattedServiceImpl.WithRawResponseImpl(clientOptions) + } + + override fun withOptions( + modifier: Consumer + ): ToolService.WithRawResponse = + ToolServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun scheduled(): ScheduledService.WithRawResponse = scheduled + + override fun formatted(): FormattedService.WithRawResponse = formatted + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: ToolListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "tools") + .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.validate() + } + } + .let { + ToolListPage.builder() + .service(ToolServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } } - } - - private val getHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** Returns the arcade tool specification for a specific tool */ - override fun get(params: ToolGetParams, requestOptions: RequestOptions): ToolDefinition { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "tools", params.getPathParam(0)) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { getHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + } + + private val authorizeHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun authorize( + params: ToolAuthorizeParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "tools", "authorize") + .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 { authorizeHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val executeHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun execute( + params: ToolExecuteParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "tools", "execute") + .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 { executeHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val getHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun get( + params: ToolGetParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("name", params.name().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "tools", 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/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/WorkerService.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/WorkerService.kt index 00a55f6..562514d 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/WorkerService.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/WorkerService.kt @@ -1,67 +1,461 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package dev.arcade.services.blocking +import com.google.errorprone.annotations.MustBeClosed +import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions -import dev.arcade.models.WorkerCreateParams -import dev.arcade.models.WorkerDeleteParams -import dev.arcade.models.WorkerGetParams -import dev.arcade.models.WorkerHealthParams -import dev.arcade.models.WorkerHealthResponse -import dev.arcade.models.WorkerListPage -import dev.arcade.models.WorkerListParams -import dev.arcade.models.WorkerResponse -import dev.arcade.models.WorkerToolsPage -import dev.arcade.models.WorkerToolsParams -import dev.arcade.models.WorkerUpdateParams +import dev.arcade.core.http.HttpResponse +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.models.workers.CreateWorkerRequest +import dev.arcade.models.workers.WorkerCreateParams +import dev.arcade.models.workers.WorkerDeleteParams +import dev.arcade.models.workers.WorkerGetParams +import dev.arcade.models.workers.WorkerHealthParams +import dev.arcade.models.workers.WorkerHealthResponse +import dev.arcade.models.workers.WorkerListPage +import dev.arcade.models.workers.WorkerListParams +import dev.arcade.models.workers.WorkerResponse +import dev.arcade.models.workers.WorkerToolsPage +import dev.arcade.models.workers.WorkerToolsParams +import dev.arcade.models.workers.WorkerUpdateParams +import java.util.function.Consumer interface WorkerService { + /** + * 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): WorkerService + /** Create a worker */ - @JvmOverloads + fun create(params: WorkerCreateParams): WorkerResponse = create(params, RequestOptions.none()) + + /** @see create */ fun create( params: WorkerCreateParams, requestOptions: RequestOptions = RequestOptions.none(), ): WorkerResponse + /** @see create */ + fun create( + createWorkerRequest: CreateWorkerRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): WorkerResponse = + create( + WorkerCreateParams.builder().createWorkerRequest(createWorkerRequest).build(), + requestOptions, + ) + + /** @see create */ + fun create(createWorkerRequest: CreateWorkerRequest): WorkerResponse = + create(createWorkerRequest, RequestOptions.none()) + /** Update a worker */ - @JvmOverloads + fun update(id: String, params: WorkerUpdateParams): WorkerResponse = + update(id, params, RequestOptions.none()) + + /** @see update */ + fun update( + id: String, + params: WorkerUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): WorkerResponse = update(params.toBuilder().id(id).build(), requestOptions) + + /** @see update */ + fun update(params: WorkerUpdateParams): WorkerResponse = update(params, RequestOptions.none()) + + /** @see update */ fun update( params: WorkerUpdateParams, requestOptions: RequestOptions = RequestOptions.none(), ): WorkerResponse /** List all workers with their definitions */ - @JvmOverloads + fun list(): WorkerListPage = list(WorkerListParams.none()) + + /** @see list */ fun list( - params: WorkerListParams, + params: WorkerListParams = WorkerListParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): WorkerListPage + /** @see list */ + fun list(params: WorkerListParams = WorkerListParams.none()): WorkerListPage = + list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): WorkerListPage = + list(WorkerListParams.none(), requestOptions) + /** Delete a worker */ - @JvmOverloads + fun delete(id: String) = delete(id, WorkerDeleteParams.none()) + + /** @see delete */ + fun delete( + id: String, + params: WorkerDeleteParams = WorkerDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ) = delete(params.toBuilder().id(id).build(), requestOptions) + + /** @see delete */ + fun delete(id: String, params: WorkerDeleteParams = WorkerDeleteParams.none()) = + delete(id, params, RequestOptions.none()) + + /** @see delete */ fun delete(params: WorkerDeleteParams, requestOptions: RequestOptions = RequestOptions.none()) + /** @see delete */ + fun delete(params: WorkerDeleteParams) = delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(id: String, requestOptions: RequestOptions) = + delete(id, WorkerDeleteParams.none(), requestOptions) + /** Get a worker by ID */ - @JvmOverloads + fun get(id: String): WorkerResponse = get(id, WorkerGetParams.none()) + + /** @see get */ + fun get( + id: String, + params: WorkerGetParams = WorkerGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): WorkerResponse = get(params.toBuilder().id(id).build(), requestOptions) + + /** @see get */ + fun get(id: String, params: WorkerGetParams = WorkerGetParams.none()): WorkerResponse = + get(id, params, RequestOptions.none()) + + /** @see get */ fun get( params: WorkerGetParams, requestOptions: RequestOptions = RequestOptions.none(), ): WorkerResponse + /** @see get */ + fun get(params: WorkerGetParams): WorkerResponse = get(params, RequestOptions.none()) + + /** @see get */ + fun get(id: String, requestOptions: RequestOptions): WorkerResponse = + get(id, WorkerGetParams.none(), requestOptions) + /** Get the health of a worker */ - @JvmOverloads + fun health(id: String): WorkerHealthResponse = health(id, WorkerHealthParams.none()) + + /** @see health */ + fun health( + id: String, + params: WorkerHealthParams = WorkerHealthParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): WorkerHealthResponse = health(params.toBuilder().id(id).build(), requestOptions) + + /** @see health */ + fun health( + id: String, + params: WorkerHealthParams = WorkerHealthParams.none(), + ): WorkerHealthResponse = health(id, params, RequestOptions.none()) + + /** @see health */ fun health( params: WorkerHealthParams, requestOptions: RequestOptions = RequestOptions.none(), ): WorkerHealthResponse + /** @see health */ + fun health(params: WorkerHealthParams): WorkerHealthResponse = + health(params, RequestOptions.none()) + + /** @see health */ + fun health(id: String, requestOptions: RequestOptions): WorkerHealthResponse = + health(id, WorkerHealthParams.none(), requestOptions) + /** Returns a page of tools */ - @JvmOverloads + fun tools(id: String): WorkerToolsPage = tools(id, WorkerToolsParams.none()) + + /** @see tools */ + fun tools( + id: String, + params: WorkerToolsParams = WorkerToolsParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): WorkerToolsPage = tools(params.toBuilder().id(id).build(), requestOptions) + + /** @see tools */ + fun tools(id: String, params: WorkerToolsParams = WorkerToolsParams.none()): WorkerToolsPage = + tools(id, params, RequestOptions.none()) + + /** @see tools */ fun tools( params: WorkerToolsParams, requestOptions: RequestOptions = RequestOptions.none(), ): WorkerToolsPage + + /** @see tools */ + fun tools(params: WorkerToolsParams): WorkerToolsPage = tools(params, RequestOptions.none()) + + /** @see tools */ + fun tools(id: String, requestOptions: RequestOptions): WorkerToolsPage = + tools(id, WorkerToolsParams.none(), requestOptions) + + /** A view of [WorkerService] 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): WorkerService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/workers`, but is otherwise the same as + * [WorkerService.create]. + */ + @MustBeClosed + fun create(params: WorkerCreateParams): HttpResponseFor = + create(params, RequestOptions.none()) + + /** @see create */ + @MustBeClosed + fun create( + params: WorkerCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see create */ + @MustBeClosed + fun create( + createWorkerRequest: CreateWorkerRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + create( + WorkerCreateParams.builder().createWorkerRequest(createWorkerRequest).build(), + requestOptions, + ) + + /** @see create */ + @MustBeClosed + fun create(createWorkerRequest: CreateWorkerRequest): HttpResponseFor = + create(createWorkerRequest, RequestOptions.none()) + + /** + * Returns a raw HTTP response for `patch /v1/workers/{id}`, but is otherwise the same as + * [WorkerService.update]. + */ + @MustBeClosed + fun update(id: String, params: WorkerUpdateParams): HttpResponseFor = + update(id, params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + id: String, + params: WorkerUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + update(params.toBuilder().id(id).build(), requestOptions) + + /** @see update */ + @MustBeClosed + fun update(params: WorkerUpdateParams): HttpResponseFor = + update(params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + params: WorkerUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/workers`, but is otherwise the same as + * [WorkerService.list]. + */ + @MustBeClosed fun list(): HttpResponseFor = list(WorkerListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: WorkerListParams = WorkerListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see list */ + @MustBeClosed + fun list( + params: WorkerListParams = WorkerListParams.none() + ): HttpResponseFor = list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(WorkerListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/workers/{id}`, but is otherwise the same as + * [WorkerService.delete]. + */ + @MustBeClosed fun delete(id: String): HttpResponse = delete(id, WorkerDeleteParams.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + id: String, + params: WorkerDeleteParams = WorkerDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponse = delete(params.toBuilder().id(id).build(), requestOptions) + + /** @see delete */ + @MustBeClosed + fun delete( + id: String, + params: WorkerDeleteParams = WorkerDeleteParams.none(), + ): HttpResponse = delete(id, params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + params: WorkerDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponse + + /** @see delete */ + @MustBeClosed + fun delete(params: WorkerDeleteParams): HttpResponse = delete(params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete(id: String, requestOptions: RequestOptions): HttpResponse = + delete(id, WorkerDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/workers/{id}`, but is otherwise the same as + * [WorkerService.get]. + */ + @MustBeClosed + fun get(id: String): HttpResponseFor = get(id, WorkerGetParams.none()) + + /** @see get */ + @MustBeClosed + fun get( + id: String, + params: WorkerGetParams = WorkerGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = get(params.toBuilder().id(id).build(), requestOptions) + + /** @see get */ + @MustBeClosed + fun get( + id: String, + params: WorkerGetParams = WorkerGetParams.none(), + ): HttpResponseFor = get(id, params, RequestOptions.none()) + + /** @see get */ + @MustBeClosed + fun get( + params: WorkerGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see get */ + @MustBeClosed + fun get(params: WorkerGetParams): HttpResponseFor = + get(params, RequestOptions.none()) + + /** @see get */ + @MustBeClosed + fun get(id: String, requestOptions: RequestOptions): HttpResponseFor = + get(id, WorkerGetParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/workers/{id}/health`, but is otherwise the same + * as [WorkerService.health]. + */ + @MustBeClosed + fun health(id: String): HttpResponseFor = + health(id, WorkerHealthParams.none()) + + /** @see health */ + @MustBeClosed + fun health( + id: String, + params: WorkerHealthParams = WorkerHealthParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + health(params.toBuilder().id(id).build(), requestOptions) + + /** @see health */ + @MustBeClosed + fun health( + id: String, + params: WorkerHealthParams = WorkerHealthParams.none(), + ): HttpResponseFor = health(id, params, RequestOptions.none()) + + /** @see health */ + @MustBeClosed + fun health( + params: WorkerHealthParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see health */ + @MustBeClosed + fun health(params: WorkerHealthParams): HttpResponseFor = + health(params, RequestOptions.none()) + + /** @see health */ + @MustBeClosed + fun health( + id: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + health(id, WorkerHealthParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/workers/{id}/tools`, but is otherwise the same + * as [WorkerService.tools]. + */ + @MustBeClosed + fun tools(id: String): HttpResponseFor = + tools(id, WorkerToolsParams.none()) + + /** @see tools */ + @MustBeClosed + fun tools( + id: String, + params: WorkerToolsParams = WorkerToolsParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + tools(params.toBuilder().id(id).build(), requestOptions) + + /** @see tools */ + @MustBeClosed + fun tools( + id: String, + params: WorkerToolsParams = WorkerToolsParams.none(), + ): HttpResponseFor = tools(id, params, RequestOptions.none()) + + /** @see tools */ + @MustBeClosed + fun tools( + params: WorkerToolsParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see tools */ + @MustBeClosed + fun tools(params: WorkerToolsParams): HttpResponseFor = + tools(params, RequestOptions.none()) + + /** @see tools */ + @MustBeClosed + fun tools(id: String, requestOptions: RequestOptions): HttpResponseFor = + tools(id, WorkerToolsParams.none(), requestOptions) + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/WorkerServiceImpl.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/WorkerServiceImpl.kt index 85ad6c5..cbfccd2 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/WorkerServiceImpl.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/WorkerServiceImpl.kt @@ -4,186 +4,310 @@ package dev.arcade.services.blocking import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions +import dev.arcade.core.checkRequired import dev.arcade.core.handlers.emptyHandler +import dev.arcade.core.handlers.errorBodyHandler import dev.arcade.core.handlers.errorHandler import dev.arcade.core.handlers.jsonHandler -import dev.arcade.core.handlers.withErrorHandler import dev.arcade.core.http.HttpMethod import dev.arcade.core.http.HttpRequest +import dev.arcade.core.http.HttpResponse import dev.arcade.core.http.HttpResponse.Handler -import dev.arcade.core.json +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.core.http.json +import dev.arcade.core.http.parseable import dev.arcade.core.prepare -import dev.arcade.errors.ArcadeError -import dev.arcade.models.WorkerCreateParams -import dev.arcade.models.WorkerDeleteParams -import dev.arcade.models.WorkerGetParams -import dev.arcade.models.WorkerHealthParams -import dev.arcade.models.WorkerHealthResponse -import dev.arcade.models.WorkerListPage -import dev.arcade.models.WorkerListParams -import dev.arcade.models.WorkerResponse -import dev.arcade.models.WorkerToolsPage -import dev.arcade.models.WorkerToolsParams -import dev.arcade.models.WorkerUpdateParams +import dev.arcade.models.workers.WorkerCreateParams +import dev.arcade.models.workers.WorkerDeleteParams +import dev.arcade.models.workers.WorkerGetParams +import dev.arcade.models.workers.WorkerHealthParams +import dev.arcade.models.workers.WorkerHealthResponse +import dev.arcade.models.workers.WorkerListPage +import dev.arcade.models.workers.WorkerListPageResponse +import dev.arcade.models.workers.WorkerListParams +import dev.arcade.models.workers.WorkerResponse +import dev.arcade.models.workers.WorkerToolsPage +import dev.arcade.models.workers.WorkerToolsPageResponse +import dev.arcade.models.workers.WorkerToolsParams +import dev.arcade.models.workers.WorkerUpdateParams +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull class WorkerServiceImpl internal constructor(private val clientOptions: ClientOptions) : WorkerService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: WorkerService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): WorkerService.WithRawResponse = withRawResponse - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withOptions(modifier: Consumer): WorkerService = + WorkerServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) - /** Create a worker */ override fun create( params: WorkerCreateParams, requestOptions: RequestOptions, - ): WorkerResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "workers") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { createHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - - private val updateHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + ): WorkerResponse = + // post /v1/workers + withRawResponse().create(params, requestOptions).parse() - /** Update a worker */ override fun update( params: WorkerUpdateParams, requestOptions: RequestOptions, - ): WorkerResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.PATCH) - .addPathSegments("v1", "workers", params.getPathParam(0)) - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { updateHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** List all workers with their definitions */ - override fun list(params: WorkerListParams, requestOptions: RequestOptions): WorkerListPage { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "workers") - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - .let { WorkerListPage.of(this, params, it) } - } + ): WorkerResponse = + // patch /v1/workers/{id} + withRawResponse().update(params, requestOptions).parse() - private val deleteHandler: Handler = emptyHandler().withErrorHandler(errorHandler) + override fun list(params: WorkerListParams, requestOptions: RequestOptions): WorkerListPage = + // get /v1/workers + withRawResponse().list(params, requestOptions).parse() - /** Delete a worker */ override fun delete(params: WorkerDeleteParams, requestOptions: RequestOptions) { - val request = - HttpRequest.builder() - .method(HttpMethod.DELETE) - .addPathSegments("v1", "workers", params.getPathParam(0)) - .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - response.use { deleteHandler.handle(it) } + // delete /v1/workers/{id} + withRawResponse().delete(params, requestOptions) } - private val getHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** Get a worker by ID */ - override fun get(params: WorkerGetParams, requestOptions: RequestOptions): WorkerResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "workers", params.getPathParam(0)) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { getHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } + override fun get(params: WorkerGetParams, requestOptions: RequestOptions): WorkerResponse = + // get /v1/workers/{id} + withRawResponse().get(params, requestOptions).parse() - private val healthHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** Get the health of a worker */ override fun health( params: WorkerHealthParams, requestOptions: RequestOptions, - ): WorkerHealthResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "workers", params.getPathParam(0), "health") - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { healthHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): WorkerHealthResponse = + // get /v1/workers/{id}/health + withRawResponse().health(params, requestOptions).parse() + + override fun tools(params: WorkerToolsParams, requestOptions: RequestOptions): WorkerToolsPage = + // get /v1/workers/{id}/tools + withRawResponse().tools(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + WorkerService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): WorkerService.WithRawResponse = + WorkerServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: WorkerCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "workers") + .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: WorkerUpdateParams, + 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", "workers", 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: WorkerListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "workers") + .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.validate() + } + } + .let { + WorkerListPage.builder() + .service(WorkerServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } + } + } + + private val deleteHandler: Handler = emptyHandler() + + override fun delete( + params: WorkerDeleteParams, + 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", "workers", 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: WorkerGetParams, + 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", "workers", 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() + } + } + } + } + + private val healthHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun health( + params: WorkerHealthParams, + 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", "workers", params._pathParam(0), "health") + .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 { healthHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val toolsHandler: Handler = + jsonHandler(clientOptions.jsonMapper) - private val toolsHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** Returns a page of tools */ - override fun tools(params: WorkerToolsParams, requestOptions: RequestOptions): WorkerToolsPage { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "workers", params.getPathParam(0), "tools") - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { toolsHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + override fun tools( + params: WorkerToolsParams, + 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", "workers", params._pathParam(0), "tools") + .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 { toolsHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + WorkerToolsPage.builder() + .service(WorkerServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } } - .let { WorkerToolsPage.of(this, params, it) } + } } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/admin/AuthProviderService.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/admin/AuthProviderService.kt index 57855d9..953bfd9 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/admin/AuthProviderService.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/admin/AuthProviderService.kt @@ -1,52 +1,348 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package dev.arcade.services.blocking.admin +import com.google.errorprone.annotations.MustBeClosed +import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions -import dev.arcade.models.AdminAuthProviderCreateParams -import dev.arcade.models.AdminAuthProviderDeleteParams -import dev.arcade.models.AdminAuthProviderGetParams -import dev.arcade.models.AdminAuthProviderListParams -import dev.arcade.models.AdminAuthProviderListResponse -import dev.arcade.models.AdminAuthProviderPatchParams -import dev.arcade.models.AuthProviderResponse +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.models.admin.authproviders.AuthProviderCreateParams +import dev.arcade.models.admin.authproviders.AuthProviderCreateRequest +import dev.arcade.models.admin.authproviders.AuthProviderDeleteParams +import dev.arcade.models.admin.authproviders.AuthProviderGetParams +import dev.arcade.models.admin.authproviders.AuthProviderListParams +import dev.arcade.models.admin.authproviders.AuthProviderListResponse +import dev.arcade.models.admin.authproviders.AuthProviderPatchParams +import dev.arcade.models.admin.authproviders.AuthProviderResponse +import java.util.function.Consumer interface AuthProviderService { + /** + * 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): AuthProviderService + /** Create a new auth provider */ - @JvmOverloads + fun create(params: AuthProviderCreateParams): AuthProviderResponse = + create(params, RequestOptions.none()) + + /** @see create */ fun create( - params: AdminAuthProviderCreateParams, + params: AuthProviderCreateParams, requestOptions: RequestOptions = RequestOptions.none(), ): AuthProviderResponse + /** @see create */ + fun create( + authProviderCreateRequest: AuthProviderCreateRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): AuthProviderResponse = + create( + AuthProviderCreateParams.builder() + .authProviderCreateRequest(authProviderCreateRequest) + .build(), + requestOptions, + ) + + /** @see create */ + fun create(authProviderCreateRequest: AuthProviderCreateRequest): AuthProviderResponse = + create(authProviderCreateRequest, RequestOptions.none()) + /** List a page of auth providers that are available to the caller */ - @JvmOverloads + fun list(): AuthProviderListResponse = list(AuthProviderListParams.none()) + + /** @see list */ fun list( - params: AdminAuthProviderListParams, + params: AuthProviderListParams = AuthProviderListParams.none(), requestOptions: RequestOptions = RequestOptions.none(), - ): AdminAuthProviderListResponse + ): AuthProviderListResponse + + /** @see list */ + fun list( + params: AuthProviderListParams = AuthProviderListParams.none() + ): AuthProviderListResponse = list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): AuthProviderListResponse = + list(AuthProviderListParams.none(), requestOptions) /** Delete a specific auth provider */ - @JvmOverloads + fun delete(id: String): AuthProviderResponse = delete(id, AuthProviderDeleteParams.none()) + + /** @see delete */ + fun delete( + id: String, + params: AuthProviderDeleteParams = AuthProviderDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): AuthProviderResponse = delete(params.toBuilder().id(id).build(), requestOptions) + + /** @see delete */ + fun delete( + id: String, + params: AuthProviderDeleteParams = AuthProviderDeleteParams.none(), + ): AuthProviderResponse = delete(id, params, RequestOptions.none()) + + /** @see delete */ fun delete( - params: AdminAuthProviderDeleteParams, + params: AuthProviderDeleteParams, requestOptions: RequestOptions = RequestOptions.none(), ): AuthProviderResponse + /** @see delete */ + fun delete(params: AuthProviderDeleteParams): AuthProviderResponse = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(id: String, requestOptions: RequestOptions): AuthProviderResponse = + delete(id, AuthProviderDeleteParams.none(), requestOptions) + /** Get the details of a specific auth provider */ - @JvmOverloads + fun get(id: String): AuthProviderResponse = get(id, AuthProviderGetParams.none()) + + /** @see get */ fun get( - params: AdminAuthProviderGetParams, + id: String, + params: AuthProviderGetParams = AuthProviderGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): AuthProviderResponse = get(params.toBuilder().id(id).build(), requestOptions) + + /** @see get */ + fun get( + id: String, + params: AuthProviderGetParams = AuthProviderGetParams.none(), + ): AuthProviderResponse = get(id, params, RequestOptions.none()) + + /** @see get */ + fun get( + params: AuthProviderGetParams, requestOptions: RequestOptions = RequestOptions.none(), ): AuthProviderResponse + /** @see get */ + fun get(params: AuthProviderGetParams): AuthProviderResponse = + get(params, RequestOptions.none()) + + /** @see get */ + fun get(id: String, requestOptions: RequestOptions): AuthProviderResponse = + get(id, AuthProviderGetParams.none(), requestOptions) + /** Patch an existing auth provider */ - @JvmOverloads + fun patch(pathId: String, params: AuthProviderPatchParams): AuthProviderResponse = + patch(pathId, params, RequestOptions.none()) + + /** @see patch */ fun patch( - params: AdminAuthProviderPatchParams, + pathId: String, + params: AuthProviderPatchParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): AuthProviderResponse = patch(params.toBuilder().pathId(pathId).build(), requestOptions) + + /** @see patch */ + fun patch(params: AuthProviderPatchParams): AuthProviderResponse = + patch(params, RequestOptions.none()) + + /** @see patch */ + fun patch( + params: AuthProviderPatchParams, requestOptions: RequestOptions = RequestOptions.none(), ): AuthProviderResponse + + /** + * A view of [AuthProviderService] 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 + ): AuthProviderService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/admin/auth_providers`, but is otherwise the + * same as [AuthProviderService.create]. + */ + @MustBeClosed + fun create(params: AuthProviderCreateParams): HttpResponseFor = + create(params, RequestOptions.none()) + + /** @see create */ + @MustBeClosed + fun create( + params: AuthProviderCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see create */ + @MustBeClosed + fun create( + authProviderCreateRequest: AuthProviderCreateRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + create( + AuthProviderCreateParams.builder() + .authProviderCreateRequest(authProviderCreateRequest) + .build(), + requestOptions, + ) + + /** @see create */ + @MustBeClosed + fun create( + authProviderCreateRequest: AuthProviderCreateRequest + ): HttpResponseFor = + create(authProviderCreateRequest, RequestOptions.none()) + + /** + * Returns a raw HTTP response for `get /v1/admin/auth_providers`, but is otherwise the same + * as [AuthProviderService.list]. + */ + @MustBeClosed + fun list(): HttpResponseFor = list(AuthProviderListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: AuthProviderListParams = AuthProviderListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see list */ + @MustBeClosed + fun list( + params: AuthProviderListParams = AuthProviderListParams.none() + ): HttpResponseFor = list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(AuthProviderListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/admin/auth_providers/{id}`, but is otherwise + * the same as [AuthProviderService.delete]. + */ + @MustBeClosed + fun delete(id: String): HttpResponseFor = + delete(id, AuthProviderDeleteParams.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + id: String, + params: AuthProviderDeleteParams = AuthProviderDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + delete(params.toBuilder().id(id).build(), requestOptions) + + /** @see delete */ + @MustBeClosed + fun delete( + id: String, + params: AuthProviderDeleteParams = AuthProviderDeleteParams.none(), + ): HttpResponseFor = delete(id, params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + params: AuthProviderDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see delete */ + @MustBeClosed + fun delete(params: AuthProviderDeleteParams): HttpResponseFor = + delete(params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + id: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + delete(id, AuthProviderDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/admin/auth_providers/{id}`, but is otherwise the + * same as [AuthProviderService.get]. + */ + @MustBeClosed + fun get(id: String): HttpResponseFor = + get(id, AuthProviderGetParams.none()) + + /** @see get */ + @MustBeClosed + fun get( + id: String, + params: AuthProviderGetParams = AuthProviderGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + get(params.toBuilder().id(id).build(), requestOptions) + + /** @see get */ + @MustBeClosed + fun get( + id: String, + params: AuthProviderGetParams = AuthProviderGetParams.none(), + ): HttpResponseFor = get(id, params, RequestOptions.none()) + + /** @see get */ + @MustBeClosed + fun get( + params: AuthProviderGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see get */ + @MustBeClosed + fun get(params: AuthProviderGetParams): HttpResponseFor = + get(params, RequestOptions.none()) + + /** @see get */ + @MustBeClosed + fun get(id: String, requestOptions: RequestOptions): HttpResponseFor = + get(id, AuthProviderGetParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/admin/auth_providers/{id}`, but is otherwise + * the same as [AuthProviderService.patch]. + */ + @MustBeClosed + fun patch( + pathId: String, + params: AuthProviderPatchParams, + ): HttpResponseFor = patch(pathId, params, RequestOptions.none()) + + /** @see patch */ + @MustBeClosed + fun patch( + pathId: String, + params: AuthProviderPatchParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + patch(params.toBuilder().pathId(pathId).build(), requestOptions) + + /** @see patch */ + @MustBeClosed + fun patch(params: AuthProviderPatchParams): HttpResponseFor = + patch(params, RequestOptions.none()) + + /** @see patch */ + @MustBeClosed + fun patch( + params: AuthProviderPatchParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/admin/AuthProviderServiceImpl.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/admin/AuthProviderServiceImpl.kt index b07bac5..db3050f 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/admin/AuthProviderServiceImpl.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/admin/AuthProviderServiceImpl.kt @@ -4,149 +4,233 @@ package dev.arcade.services.blocking.admin import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions +import dev.arcade.core.checkRequired +import dev.arcade.core.handlers.errorBodyHandler import dev.arcade.core.handlers.errorHandler import dev.arcade.core.handlers.jsonHandler -import dev.arcade.core.handlers.withErrorHandler import dev.arcade.core.http.HttpMethod import dev.arcade.core.http.HttpRequest +import dev.arcade.core.http.HttpResponse import dev.arcade.core.http.HttpResponse.Handler -import dev.arcade.core.json +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.core.http.json +import dev.arcade.core.http.parseable import dev.arcade.core.prepare -import dev.arcade.errors.ArcadeError -import dev.arcade.models.AdminAuthProviderCreateParams -import dev.arcade.models.AdminAuthProviderDeleteParams -import dev.arcade.models.AdminAuthProviderGetParams -import dev.arcade.models.AdminAuthProviderListParams -import dev.arcade.models.AdminAuthProviderListResponse -import dev.arcade.models.AdminAuthProviderPatchParams -import dev.arcade.models.AuthProviderResponse +import dev.arcade.models.admin.authproviders.AuthProviderCreateParams +import dev.arcade.models.admin.authproviders.AuthProviderDeleteParams +import dev.arcade.models.admin.authproviders.AuthProviderGetParams +import dev.arcade.models.admin.authproviders.AuthProviderListParams +import dev.arcade.models.admin.authproviders.AuthProviderListResponse +import dev.arcade.models.admin.authproviders.AuthProviderPatchParams +import dev.arcade.models.admin.authproviders.AuthProviderResponse +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull class AuthProviderServiceImpl internal constructor(private val clientOptions: ClientOptions) : AuthProviderService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: AuthProviderService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): AuthProviderService.WithRawResponse = withRawResponse - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withOptions(modifier: Consumer): AuthProviderService = + AuthProviderServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) - /** Create a new auth provider */ override fun create( - params: AdminAuthProviderCreateParams, + params: AuthProviderCreateParams, requestOptions: RequestOptions, - ): AuthProviderResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "admin", "auth_providers") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { createHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } + ): AuthProviderResponse = + // post /v1/admin/auth_providers + withRawResponse().create(params, requestOptions).parse() - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** List a page of auth providers that are available to the caller */ override fun list( - params: AdminAuthProviderListParams, + params: AuthProviderListParams, requestOptions: RequestOptions, - ): AdminAuthProviderListResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "admin", "auth_providers") - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - - private val deleteHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + ): AuthProviderListResponse = + // get /v1/admin/auth_providers + withRawResponse().list(params, requestOptions).parse() - /** Delete a specific auth provider */ override fun delete( - params: AdminAuthProviderDeleteParams, + params: AuthProviderDeleteParams, requestOptions: RequestOptions, - ): AuthProviderResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.DELETE) - .addPathSegments("v1", "admin", "auth_providers", params.getPathParam(0)) - .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { deleteHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } + ): AuthProviderResponse = + // delete /v1/admin/auth_providers/{id} + withRawResponse().delete(params, requestOptions).parse() - private val getHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** Get the details of a specific auth provider */ override fun get( - params: AdminAuthProviderGetParams, + params: AuthProviderGetParams, requestOptions: RequestOptions, - ): AuthProviderResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "admin", "auth_providers", params.getPathParam(0)) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { getHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - - private val patchHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + ): AuthProviderResponse = + // get /v1/admin/auth_providers/{id} + withRawResponse().get(params, requestOptions).parse() - /** Patch an existing auth provider */ override fun patch( - params: AdminAuthProviderPatchParams, + params: AuthProviderPatchParams, requestOptions: RequestOptions, - ): AuthProviderResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.PATCH) - .addPathSegments("v1", "admin", "auth_providers", params.getPathParam(0)) - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { patchHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): AuthProviderResponse = + // patch /v1/admin/auth_providers/{id} + withRawResponse().patch(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + AuthProviderService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): AuthProviderService.WithRawResponse = + AuthProviderServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: AuthProviderCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "admin", "auth_providers") + .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 listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: AuthProviderListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "admin", "auth_providers") + .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.validate() + } + } + } + } + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: AuthProviderDeleteParams, + 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", "admin", "auth_providers", 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() + } + } + } + } + + private val getHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun get( + params: AuthProviderGetParams, + 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", "admin", "auth_providers", 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() + } + } + } + } + + private val patchHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun patch( + params: AuthProviderPatchParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("pathId", params.pathId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "admin", "auth_providers", 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 { patchHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } + } } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/admin/SecretService.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/admin/SecretService.kt index 504e99b..4c6b0dc 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/admin/SecretService.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/admin/SecretService.kt @@ -1,36 +1,194 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package dev.arcade.services.blocking.admin +import com.google.errorprone.annotations.MustBeClosed +import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions -import dev.arcade.models.AdminSecretCreateParams -import dev.arcade.models.AdminSecretDeleteParams -import dev.arcade.models.AdminSecretListParams -import dev.arcade.models.AdminSecretListResponse -import dev.arcade.models.SecretResponse +import dev.arcade.core.http.HttpResponse +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.models.admin.secrets.SecretCreateParams +import dev.arcade.models.admin.secrets.SecretDeleteParams +import dev.arcade.models.admin.secrets.SecretListParams +import dev.arcade.models.admin.secrets.SecretListResponse +import dev.arcade.models.admin.secrets.SecretResponse +import java.util.function.Consumer interface SecretService { + /** + * 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): SecretService + /** Create or update a secret */ - @JvmOverloads + fun create(secretKey: String, params: SecretCreateParams): SecretResponse = + create(secretKey, params, RequestOptions.none()) + + /** @see create */ + fun create( + secretKey: String, + params: SecretCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): SecretResponse = create(params.toBuilder().secretKey(secretKey).build(), requestOptions) + + /** @see create */ + fun create(params: SecretCreateParams): SecretResponse = create(params, RequestOptions.none()) + + /** @see create */ fun create( - params: AdminSecretCreateParams, + params: SecretCreateParams, requestOptions: RequestOptions = RequestOptions.none(), ): SecretResponse /** List all secrets that are visible to the caller */ - @JvmOverloads + fun list(): SecretListResponse = list(SecretListParams.none()) + + /** @see list */ fun list( - params: AdminSecretListParams, + params: SecretListParams = SecretListParams.none(), requestOptions: RequestOptions = RequestOptions.none(), - ): AdminSecretListResponse + ): SecretListResponse + + /** @see list */ + fun list(params: SecretListParams = SecretListParams.none()): SecretListResponse = + list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): SecretListResponse = + list(SecretListParams.none(), requestOptions) /** Delete a secret by its ID */ - @JvmOverloads + fun delete(secretId: String) = delete(secretId, SecretDeleteParams.none()) + + /** @see delete */ fun delete( - params: AdminSecretDeleteParams, + secretId: String, + params: SecretDeleteParams = SecretDeleteParams.none(), requestOptions: RequestOptions = RequestOptions.none(), - ) + ) = delete(params.toBuilder().secretId(secretId).build(), requestOptions) + + /** @see delete */ + fun delete(secretId: String, params: SecretDeleteParams = SecretDeleteParams.none()) = + delete(secretId, params, RequestOptions.none()) + + /** @see delete */ + fun delete(params: SecretDeleteParams, requestOptions: RequestOptions = RequestOptions.none()) + + /** @see delete */ + fun delete(params: SecretDeleteParams) = delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(secretId: String, requestOptions: RequestOptions) = + delete(secretId, SecretDeleteParams.none(), requestOptions) + + /** A view of [SecretService] 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): SecretService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/admin/secrets/{secret_key}`, but is otherwise + * the same as [SecretService.create]. + */ + @MustBeClosed + fun create(secretKey: String, params: SecretCreateParams): HttpResponseFor = + create(secretKey, params, RequestOptions.none()) + + /** @see create */ + @MustBeClosed + fun create( + secretKey: String, + params: SecretCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + create(params.toBuilder().secretKey(secretKey).build(), requestOptions) + + /** @see create */ + @MustBeClosed + fun create(params: SecretCreateParams): HttpResponseFor = + create(params, RequestOptions.none()) + + /** @see create */ + @MustBeClosed + fun create( + params: SecretCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/admin/secrets`, but is otherwise the same as + * [SecretService.list]. + */ + @MustBeClosed + fun list(): HttpResponseFor = list(SecretListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: SecretListParams = SecretListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see list */ + @MustBeClosed + fun list( + params: SecretListParams = SecretListParams.none() + ): HttpResponseFor = list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(SecretListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/admin/secrets/{secret_id}`, but is otherwise + * the same as [SecretService.delete]. + */ + @MustBeClosed + fun delete(secretId: String): HttpResponse = delete(secretId, SecretDeleteParams.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + secretId: String, + params: SecretDeleteParams = SecretDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponse = delete(params.toBuilder().secretId(secretId).build(), requestOptions) + + /** @see delete */ + @MustBeClosed + fun delete( + secretId: String, + params: SecretDeleteParams = SecretDeleteParams.none(), + ): HttpResponse = delete(secretId, params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + params: SecretDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponse + + /** @see delete */ + @MustBeClosed + fun delete(params: SecretDeleteParams): HttpResponse = delete(params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete(secretId: String, requestOptions: RequestOptions): HttpResponse = + delete(secretId, SecretDeleteParams.none(), requestOptions) + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/admin/SecretServiceImpl.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/admin/SecretServiceImpl.kt index f1aac7c..c276e71 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/admin/SecretServiceImpl.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/admin/SecretServiceImpl.kt @@ -4,89 +4,151 @@ package dev.arcade.services.blocking.admin import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions +import dev.arcade.core.checkRequired import dev.arcade.core.handlers.emptyHandler +import dev.arcade.core.handlers.errorBodyHandler import dev.arcade.core.handlers.errorHandler import dev.arcade.core.handlers.jsonHandler -import dev.arcade.core.handlers.withErrorHandler import dev.arcade.core.http.HttpMethod import dev.arcade.core.http.HttpRequest +import dev.arcade.core.http.HttpResponse import dev.arcade.core.http.HttpResponse.Handler -import dev.arcade.core.json +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.core.http.json +import dev.arcade.core.http.parseable import dev.arcade.core.prepare -import dev.arcade.errors.ArcadeError -import dev.arcade.models.AdminSecretCreateParams -import dev.arcade.models.AdminSecretDeleteParams -import dev.arcade.models.AdminSecretListParams -import dev.arcade.models.AdminSecretListResponse -import dev.arcade.models.SecretResponse +import dev.arcade.models.admin.secrets.SecretCreateParams +import dev.arcade.models.admin.secrets.SecretDeleteParams +import dev.arcade.models.admin.secrets.SecretListParams +import dev.arcade.models.admin.secrets.SecretListResponse +import dev.arcade.models.admin.secrets.SecretResponse +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull class SecretServiceImpl internal constructor(private val clientOptions: ClientOptions) : SecretService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: SecretService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): SecretService.WithRawResponse = withRawResponse - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withOptions(modifier: Consumer): SecretService = + SecretServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) - /** Create or update a secret */ override fun create( - params: AdminSecretCreateParams, + params: SecretCreateParams, requestOptions: RequestOptions, - ): SecretResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "admin", "secrets", params.getPathParam(0)) - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { createHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + ): SecretResponse = + // post /v1/admin/secrets/{secret_key} + withRawResponse().create(params, requestOptions).parse() - /** List all secrets that are visible to the caller */ override fun list( - params: AdminSecretListParams, + params: SecretListParams, requestOptions: RequestOptions, - ): AdminSecretListResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "admin", "secrets") - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } + ): SecretListResponse = + // get /v1/admin/secrets + withRawResponse().list(params, requestOptions).parse() + + override fun delete(params: SecretDeleteParams, requestOptions: RequestOptions) { + // delete /v1/admin/secrets/{secret_id} + withRawResponse().delete(params, requestOptions) } - private val deleteHandler: Handler = emptyHandler().withErrorHandler(errorHandler) - - /** Delete a secret by its ID */ - override fun delete(params: AdminSecretDeleteParams, requestOptions: RequestOptions) { - val request = - HttpRequest.builder() - .method(HttpMethod.DELETE) - .addPathSegments("v1", "admin", "secrets", params.getPathParam(0)) - .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - response.use { deleteHandler.handle(it) } + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + SecretService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): SecretService.WithRawResponse = + SecretServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: SecretCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("secretKey", params.secretKey().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "admin", "secrets", 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 { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: SecretListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "admin", "secrets") + .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.validate() + } + } + } + } + + private val deleteHandler: Handler = emptyHandler() + + override fun delete( + params: SecretDeleteParams, + requestOptions: RequestOptions, + ): HttpResponse { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("secretId", params.secretId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "admin", "secrets", 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) } + } + } } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/admin/UserConnectionService.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/admin/UserConnectionService.kt index 8f021ab..c7a701c 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/admin/UserConnectionService.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/admin/UserConnectionService.kt @@ -1,27 +1,152 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package dev.arcade.services.blocking.admin +import com.google.errorprone.annotations.MustBeClosed +import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions -import dev.arcade.models.AdminUserConnectionDeleteParams -import dev.arcade.models.AdminUserConnectionListPage -import dev.arcade.models.AdminUserConnectionListParams +import dev.arcade.core.http.HttpResponse +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.models.admin.userconnections.UserConnectionDeleteParams +import dev.arcade.models.admin.userconnections.UserConnectionListPage +import dev.arcade.models.admin.userconnections.UserConnectionListParams +import java.util.function.Consumer interface UserConnectionService { + /** + * 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): UserConnectionService + /** List all auth connections */ - @JvmOverloads + fun list(): UserConnectionListPage = list(UserConnectionListParams.none()) + + /** @see list */ fun list( - params: AdminUserConnectionListParams, + params: UserConnectionListParams = UserConnectionListParams.none(), requestOptions: RequestOptions = RequestOptions.none(), - ): AdminUserConnectionListPage + ): UserConnectionListPage + + /** @see list */ + fun list( + params: UserConnectionListParams = UserConnectionListParams.none() + ): UserConnectionListPage = list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): UserConnectionListPage = + list(UserConnectionListParams.none(), requestOptions) /** Delete a user/auth provider connection */ - @JvmOverloads + fun delete(id: String) = delete(id, UserConnectionDeleteParams.none()) + + /** @see delete */ + fun delete( + id: String, + params: UserConnectionDeleteParams = UserConnectionDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ) = delete(params.toBuilder().id(id).build(), requestOptions) + + /** @see delete */ + fun delete(id: String, params: UserConnectionDeleteParams = UserConnectionDeleteParams.none()) = + delete(id, params, RequestOptions.none()) + + /** @see delete */ fun delete( - params: AdminUserConnectionDeleteParams, + params: UserConnectionDeleteParams, requestOptions: RequestOptions = RequestOptions.none(), ) + + /** @see delete */ + fun delete(params: UserConnectionDeleteParams) = delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(id: String, requestOptions: RequestOptions) = + delete(id, UserConnectionDeleteParams.none(), requestOptions) + + /** + * A view of [UserConnectionService] 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 + ): UserConnectionService.WithRawResponse + + /** + * Returns a raw HTTP response for `get /v1/admin/user_connections`, but is otherwise the + * same as [UserConnectionService.list]. + */ + @MustBeClosed + fun list(): HttpResponseFor = list(UserConnectionListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: UserConnectionListParams = UserConnectionListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see list */ + @MustBeClosed + fun list( + params: UserConnectionListParams = UserConnectionListParams.none() + ): HttpResponseFor = list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(UserConnectionListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/admin/user_connections/{id}`, but is + * otherwise the same as [UserConnectionService.delete]. + */ + @MustBeClosed + fun delete(id: String): HttpResponse = delete(id, UserConnectionDeleteParams.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + id: String, + params: UserConnectionDeleteParams = UserConnectionDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponse = delete(params.toBuilder().id(id).build(), requestOptions) + + /** @see delete */ + @MustBeClosed + fun delete( + id: String, + params: UserConnectionDeleteParams = UserConnectionDeleteParams.none(), + ): HttpResponse = delete(id, params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + params: UserConnectionDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponse + + /** @see delete */ + @MustBeClosed + fun delete(params: UserConnectionDeleteParams): HttpResponse = + delete(params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete(id: String, requestOptions: RequestOptions): HttpResponse = + delete(id, UserConnectionDeleteParams.none(), requestOptions) + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/admin/UserConnectionServiceImpl.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/admin/UserConnectionServiceImpl.kt index 4b7e321..c691b9a 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/admin/UserConnectionServiceImpl.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/admin/UserConnectionServiceImpl.kt @@ -4,63 +4,119 @@ package dev.arcade.services.blocking.admin import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions +import dev.arcade.core.checkRequired import dev.arcade.core.handlers.emptyHandler +import dev.arcade.core.handlers.errorBodyHandler import dev.arcade.core.handlers.errorHandler import dev.arcade.core.handlers.jsonHandler -import dev.arcade.core.handlers.withErrorHandler import dev.arcade.core.http.HttpMethod import dev.arcade.core.http.HttpRequest +import dev.arcade.core.http.HttpResponse import dev.arcade.core.http.HttpResponse.Handler -import dev.arcade.core.json +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.core.http.json +import dev.arcade.core.http.parseable import dev.arcade.core.prepare -import dev.arcade.errors.ArcadeError -import dev.arcade.models.AdminUserConnectionDeleteParams -import dev.arcade.models.AdminUserConnectionListPage -import dev.arcade.models.AdminUserConnectionListParams +import dev.arcade.models.admin.userconnections.UserConnectionDeleteParams +import dev.arcade.models.admin.userconnections.UserConnectionListPage +import dev.arcade.models.admin.userconnections.UserConnectionListPageResponse +import dev.arcade.models.admin.userconnections.UserConnectionListParams +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull class UserConnectionServiceImpl internal constructor(private val clientOptions: ClientOptions) : UserConnectionService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: UserConnectionService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): UserConnectionService.WithRawResponse = withRawResponse - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withOptions(modifier: Consumer): UserConnectionService = + UserConnectionServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) - /** List all auth connections */ override fun list( - params: AdminUserConnectionListParams, + params: UserConnectionListParams, requestOptions: RequestOptions, - ): AdminUserConnectionListPage { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "admin", "user_connections") - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - .let { AdminUserConnectionListPage.of(this, params, it) } + ): UserConnectionListPage = + // get /v1/admin/user_connections + withRawResponse().list(params, requestOptions).parse() + + override fun delete(params: UserConnectionDeleteParams, requestOptions: RequestOptions) { + // delete /v1/admin/user_connections/{id} + withRawResponse().delete(params, requestOptions) } - private val deleteHandler: Handler = emptyHandler().withErrorHandler(errorHandler) + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + UserConnectionService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): UserConnectionService.WithRawResponse = + UserConnectionServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) - /** Delete a user/auth provider connection */ - override fun delete(params: AdminUserConnectionDeleteParams, requestOptions: RequestOptions) { - val request = - HttpRequest.builder() - .method(HttpMethod.DELETE) - .addPathSegments("v1", "admin", "user_connections", params.getPathParam(0)) - .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - response.use { deleteHandler.handle(it) } + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: UserConnectionListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "admin", "user_connections") + .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.validate() + } + } + .let { + UserConnectionListPage.builder() + .service(UserConnectionServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } + } + } + + private val deleteHandler: Handler = emptyHandler() + + override fun delete( + params: UserConnectionDeleteParams, + 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", "admin", "user_connections", 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) } + } + } } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/chat/CompletionService.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/chat/CompletionService.kt index 293871d..9d96d7e 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/chat/CompletionService.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/chat/CompletionService.kt @@ -1,19 +1,90 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package dev.arcade.services.blocking.chat +import com.google.errorprone.annotations.MustBeClosed +import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions -import dev.arcade.models.ChatCompletionCreateParams -import dev.arcade.models.ChatResponse +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.models.chat.ChatRequest +import dev.arcade.models.chat.ChatResponse +import dev.arcade.models.chat.completions.CompletionCreateParams +import java.util.function.Consumer interface CompletionService { + /** + * 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): CompletionService + /** Interact with language models via OpenAI's chat completions API */ - @JvmOverloads + fun create(params: CompletionCreateParams): ChatResponse = create(params, RequestOptions.none()) + + /** @see create */ fun create( - params: ChatCompletionCreateParams, + params: CompletionCreateParams, requestOptions: RequestOptions = RequestOptions.none(), ): ChatResponse + + /** @see create */ + fun create( + chatRequest: ChatRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): ChatResponse = + create(CompletionCreateParams.builder().chatRequest(chatRequest).build(), requestOptions) + + /** @see create */ + fun create(chatRequest: ChatRequest): ChatResponse = create(chatRequest, RequestOptions.none()) + + /** A view of [CompletionService] 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 + ): CompletionService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/chat/completions`, but is otherwise the same as + * [CompletionService.create]. + */ + @MustBeClosed + fun create(params: CompletionCreateParams): HttpResponseFor = + create(params, RequestOptions.none()) + + /** @see create */ + @MustBeClosed + fun create( + params: CompletionCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see create */ + @MustBeClosed + fun create( + chatRequest: ChatRequest, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + create( + CompletionCreateParams.builder().chatRequest(chatRequest).build(), + requestOptions, + ) + + /** @see create */ + @MustBeClosed + fun create(chatRequest: ChatRequest): HttpResponseFor = + create(chatRequest, RequestOptions.none()) + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/chat/CompletionServiceImpl.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/chat/CompletionServiceImpl.kt index cd21893..acd4067 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/chat/CompletionServiceImpl.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/chat/CompletionServiceImpl.kt @@ -4,45 +4,79 @@ package dev.arcade.services.blocking.chat import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions +import dev.arcade.core.handlers.errorBodyHandler import dev.arcade.core.handlers.errorHandler import dev.arcade.core.handlers.jsonHandler -import dev.arcade.core.handlers.withErrorHandler import dev.arcade.core.http.HttpMethod import dev.arcade.core.http.HttpRequest +import dev.arcade.core.http.HttpResponse import dev.arcade.core.http.HttpResponse.Handler -import dev.arcade.core.json +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.core.http.json +import dev.arcade.core.http.parseable import dev.arcade.core.prepare -import dev.arcade.errors.ArcadeError -import dev.arcade.models.ChatCompletionCreateParams -import dev.arcade.models.ChatResponse +import dev.arcade.models.chat.ChatResponse +import dev.arcade.models.chat.completions.CompletionCreateParams +import java.util.function.Consumer class CompletionServiceImpl internal constructor(private val clientOptions: ClientOptions) : CompletionService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: CompletionService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): CompletionService.WithRawResponse = withRawResponse - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withOptions(modifier: Consumer): CompletionService = + CompletionServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) - /** Interact with language models via OpenAI's chat completions API */ override fun create( - params: ChatCompletionCreateParams, + params: CompletionCreateParams, requestOptions: RequestOptions, - ): ChatResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "chat", "completions") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { createHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): ChatResponse = + // post /v1/chat/completions + withRawResponse().create(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + CompletionService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): CompletionService.WithRawResponse = + CompletionServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: CompletionCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "chat", "completions") + .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() + } + } } + } } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/tools/FormattedService.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/tools/FormattedService.kt index 70dd77b..d055878 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/tools/FormattedService.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/tools/FormattedService.kt @@ -1,31 +1,157 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package dev.arcade.services.blocking.tools +import com.google.errorprone.annotations.MustBeClosed +import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions -import dev.arcade.models.ToolFormattedGetParams -import dev.arcade.models.ToolFormattedGetResponse -import dev.arcade.models.ToolFormattedListPage -import dev.arcade.models.ToolFormattedListParams +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.models.tools.formatted.FormattedGetParams +import dev.arcade.models.tools.formatted.FormattedGetResponse +import dev.arcade.models.tools.formatted.FormattedListPage +import dev.arcade.models.tools.formatted.FormattedListParams +import java.util.function.Consumer interface FormattedService { + /** + * 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): FormattedService + /** * Returns a page of tools from the engine configuration, optionally filtered by toolkit, * formatted for a specific provider */ - @JvmOverloads + fun list(): FormattedListPage = list(FormattedListParams.none()) + + /** @see list */ fun list( - params: ToolFormattedListParams, + params: FormattedListParams = FormattedListParams.none(), requestOptions: RequestOptions = RequestOptions.none(), - ): ToolFormattedListPage + ): FormattedListPage + + /** @see list */ + fun list(params: FormattedListParams = FormattedListParams.none()): FormattedListPage = + list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): FormattedListPage = + list(FormattedListParams.none(), requestOptions) /** Returns the formatted tool specification for a specific tool, given a provider */ - @JvmOverloads + fun get(name: String): FormattedGetResponse = get(name, FormattedGetParams.none()) + + /** @see get */ + fun get( + name: String, + params: FormattedGetParams = FormattedGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): FormattedGetResponse = get(params.toBuilder().name(name).build(), requestOptions) + + /** @see get */ + fun get( + name: String, + params: FormattedGetParams = FormattedGetParams.none(), + ): FormattedGetResponse = get(name, params, RequestOptions.none()) + + /** @see get */ fun get( - params: ToolFormattedGetParams, + params: FormattedGetParams, requestOptions: RequestOptions = RequestOptions.none(), - ): ToolFormattedGetResponse + ): FormattedGetResponse + + /** @see get */ + fun get(params: FormattedGetParams): FormattedGetResponse = get(params, RequestOptions.none()) + + /** @see get */ + fun get(name: String, requestOptions: RequestOptions): FormattedGetResponse = + get(name, FormattedGetParams.none(), requestOptions) + + /** A view of [FormattedService] 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): FormattedService.WithRawResponse + + /** + * Returns a raw HTTP response for `get /v1/formatted_tools`, but is otherwise the same as + * [FormattedService.list]. + */ + @MustBeClosed + fun list(): HttpResponseFor = list(FormattedListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: FormattedListParams = FormattedListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see list */ + @MustBeClosed + fun list( + params: FormattedListParams = FormattedListParams.none() + ): HttpResponseFor = list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(FormattedListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/formatted_tools/{name}`, but is otherwise the + * same as [FormattedService.get]. + */ + @MustBeClosed + fun get(name: String): HttpResponseFor = + get(name, FormattedGetParams.none()) + + /** @see get */ + @MustBeClosed + fun get( + name: String, + params: FormattedGetParams = FormattedGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + get(params.toBuilder().name(name).build(), requestOptions) + + /** @see get */ + @MustBeClosed + fun get( + name: String, + params: FormattedGetParams = FormattedGetParams.none(), + ): HttpResponseFor = get(name, params, RequestOptions.none()) + + /** @see get */ + @MustBeClosed + fun get( + params: FormattedGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see get */ + @MustBeClosed + fun get(params: FormattedGetParams): HttpResponseFor = + get(params, RequestOptions.none()) + + /** @see get */ + @MustBeClosed + fun get( + name: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + get(name, FormattedGetParams.none(), requestOptions) + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/tools/FormattedServiceImpl.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/tools/FormattedServiceImpl.kt index 027b057..43da1a1 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/tools/FormattedServiceImpl.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/tools/FormattedServiceImpl.kt @@ -4,75 +4,126 @@ package dev.arcade.services.blocking.tools import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions +import dev.arcade.core.checkRequired +import dev.arcade.core.handlers.errorBodyHandler import dev.arcade.core.handlers.errorHandler import dev.arcade.core.handlers.jsonHandler -import dev.arcade.core.handlers.withErrorHandler import dev.arcade.core.http.HttpMethod import dev.arcade.core.http.HttpRequest +import dev.arcade.core.http.HttpResponse import dev.arcade.core.http.HttpResponse.Handler +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.core.http.parseable import dev.arcade.core.prepare -import dev.arcade.errors.ArcadeError -import dev.arcade.models.ToolFormattedGetParams -import dev.arcade.models.ToolFormattedGetResponse -import dev.arcade.models.ToolFormattedListPage -import dev.arcade.models.ToolFormattedListParams +import dev.arcade.models.tools.formatted.FormattedGetParams +import dev.arcade.models.tools.formatted.FormattedGetResponse +import dev.arcade.models.tools.formatted.FormattedListPage +import dev.arcade.models.tools.formatted.FormattedListPageResponse +import dev.arcade.models.tools.formatted.FormattedListParams +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull class FormattedServiceImpl internal constructor(private val clientOptions: ClientOptions) : FormattedService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: FormattedService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): FormattedService.WithRawResponse = withRawResponse - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withOptions(modifier: Consumer): FormattedService = + FormattedServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) - /** - * Returns a page of tools from the engine configuration, optionally filtered by toolkit, - * formatted for a specific provider - */ override fun list( - params: ToolFormattedListParams, + params: FormattedListParams, requestOptions: RequestOptions, - ): ToolFormattedListPage { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "formatted_tools") - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - .let { ToolFormattedListPage.of(this, params, it) } - } + ): FormattedListPage = + // get /v1/formatted_tools + withRawResponse().list(params, requestOptions).parse() - private val getHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** Returns the formatted tool specification for a specific tool, given a provider */ override fun get( - params: ToolFormattedGetParams, + params: FormattedGetParams, requestOptions: RequestOptions, - ): ToolFormattedGetResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "formatted_tools", params.getPathParam(0)) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { getHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): FormattedGetResponse = + // get /v1/formatted_tools/{name} + withRawResponse().get(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + FormattedService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): FormattedService.WithRawResponse = + FormattedServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: FormattedListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "formatted_tools") + .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.validate() + } + } + .let { + FormattedListPage.builder() + .service(FormattedServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } + } + } + + private val getHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun get( + params: FormattedGetParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("name", params.name().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "formatted_tools", 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/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/tools/ScheduledService.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/tools/ScheduledService.kt index 4bfd23d..fc190a4 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/tools/ScheduledService.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/tools/ScheduledService.kt @@ -1,28 +1,151 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package dev.arcade.services.blocking.tools +import com.google.errorprone.annotations.MustBeClosed +import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions -import dev.arcade.models.ToolScheduledGetParams -import dev.arcade.models.ToolScheduledGetResponse -import dev.arcade.models.ToolScheduledListPage -import dev.arcade.models.ToolScheduledListParams +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.models.tools.scheduled.ScheduledGetParams +import dev.arcade.models.tools.scheduled.ScheduledGetResponse +import dev.arcade.models.tools.scheduled.ScheduledListPage +import dev.arcade.models.tools.scheduled.ScheduledListParams +import java.util.function.Consumer interface ScheduledService { + /** + * 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): ScheduledService + /** Returns a page of scheduled tool executions */ - @JvmOverloads + fun list(): ScheduledListPage = list(ScheduledListParams.none()) + + /** @see list */ fun list( - params: ToolScheduledListParams, + params: ScheduledListParams = ScheduledListParams.none(), requestOptions: RequestOptions = RequestOptions.none(), - ): ToolScheduledListPage + ): ScheduledListPage + + /** @see list */ + fun list(params: ScheduledListParams = ScheduledListParams.none()): ScheduledListPage = + list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): ScheduledListPage = + list(ScheduledListParams.none(), requestOptions) /** Returns the details for a specific scheduled tool execution */ - @JvmOverloads + fun get(id: String): ScheduledGetResponse = get(id, ScheduledGetParams.none()) + + /** @see get */ fun get( - params: ToolScheduledGetParams, + id: String, + params: ScheduledGetParams = ScheduledGetParams.none(), requestOptions: RequestOptions = RequestOptions.none(), - ): ToolScheduledGetResponse + ): ScheduledGetResponse = get(params.toBuilder().id(id).build(), requestOptions) + + /** @see get */ + fun get( + id: String, + params: ScheduledGetParams = ScheduledGetParams.none(), + ): ScheduledGetResponse = get(id, params, RequestOptions.none()) + + /** @see get */ + fun get( + params: ScheduledGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): ScheduledGetResponse + + /** @see get */ + fun get(params: ScheduledGetParams): ScheduledGetResponse = get(params, RequestOptions.none()) + + /** @see get */ + fun get(id: String, requestOptions: RequestOptions): ScheduledGetResponse = + get(id, ScheduledGetParams.none(), requestOptions) + + /** A view of [ScheduledService] 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): ScheduledService.WithRawResponse + + /** + * Returns a raw HTTP response for `get /v1/scheduled_tools`, but is otherwise the same as + * [ScheduledService.list]. + */ + @MustBeClosed + fun list(): HttpResponseFor = list(ScheduledListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: ScheduledListParams = ScheduledListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see list */ + @MustBeClosed + fun list( + params: ScheduledListParams = ScheduledListParams.none() + ): HttpResponseFor = list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(ScheduledListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/scheduled_tools/{id}`, but is otherwise the same + * as [ScheduledService.get]. + */ + @MustBeClosed + fun get(id: String): HttpResponseFor = + get(id, ScheduledGetParams.none()) + + /** @see get */ + @MustBeClosed + fun get( + id: String, + params: ScheduledGetParams = ScheduledGetParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + get(params.toBuilder().id(id).build(), requestOptions) + + /** @see get */ + @MustBeClosed + fun get( + id: String, + params: ScheduledGetParams = ScheduledGetParams.none(), + ): HttpResponseFor = get(id, params, RequestOptions.none()) + + /** @see get */ + @MustBeClosed + fun get( + params: ScheduledGetParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see get */ + @MustBeClosed + fun get(params: ScheduledGetParams): HttpResponseFor = + get(params, RequestOptions.none()) + + /** @see get */ + @MustBeClosed + fun get(id: String, requestOptions: RequestOptions): HttpResponseFor = + get(id, ScheduledGetParams.none(), requestOptions) + } } diff --git a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/tools/ScheduledServiceImpl.kt b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/tools/ScheduledServiceImpl.kt index 3c8ac0f..b687c30 100644 --- a/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/tools/ScheduledServiceImpl.kt +++ b/arcade-java-core/src/main/kotlin/dev/arcade/services/blocking/tools/ScheduledServiceImpl.kt @@ -4,72 +4,126 @@ package dev.arcade.services.blocking.tools import dev.arcade.core.ClientOptions import dev.arcade.core.RequestOptions +import dev.arcade.core.checkRequired +import dev.arcade.core.handlers.errorBodyHandler import dev.arcade.core.handlers.errorHandler import dev.arcade.core.handlers.jsonHandler -import dev.arcade.core.handlers.withErrorHandler import dev.arcade.core.http.HttpMethod import dev.arcade.core.http.HttpRequest +import dev.arcade.core.http.HttpResponse import dev.arcade.core.http.HttpResponse.Handler +import dev.arcade.core.http.HttpResponseFor +import dev.arcade.core.http.parseable import dev.arcade.core.prepare -import dev.arcade.errors.ArcadeError -import dev.arcade.models.ToolScheduledGetParams -import dev.arcade.models.ToolScheduledGetResponse -import dev.arcade.models.ToolScheduledListPage -import dev.arcade.models.ToolScheduledListParams +import dev.arcade.models.tools.scheduled.ScheduledGetParams +import dev.arcade.models.tools.scheduled.ScheduledGetResponse +import dev.arcade.models.tools.scheduled.ScheduledListPage +import dev.arcade.models.tools.scheduled.ScheduledListPageResponse +import dev.arcade.models.tools.scheduled.ScheduledListParams +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull class ScheduledServiceImpl internal constructor(private val clientOptions: ClientOptions) : ScheduledService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: ScheduledService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): ScheduledService.WithRawResponse = withRawResponse - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withOptions(modifier: Consumer): ScheduledService = + ScheduledServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) - /** Returns a page of scheduled tool executions */ override fun list( - params: ToolScheduledListParams, + params: ScheduledListParams, requestOptions: RequestOptions, - ): ToolScheduledListPage { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "scheduled_tools") - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - .let { ToolScheduledListPage.of(this, params, it) } - } + ): ScheduledListPage = + // get /v1/scheduled_tools + withRawResponse().list(params, requestOptions).parse() - private val getHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** Returns the details for a specific scheduled tool execution */ override fun get( - params: ToolScheduledGetParams, + params: ScheduledGetParams, requestOptions: RequestOptions, - ): ToolScheduledGetResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "scheduled_tools", params.getPathParam(0)) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { getHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): ScheduledGetResponse = + // get /v1/scheduled_tools/{id} + withRawResponse().get(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ScheduledService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): ScheduledService.WithRawResponse = + ScheduledServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: ScheduledListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "scheduled_tools") + .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.validate() + } + } + .let { + ScheduledListPage.builder() + .service(ScheduledServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } + } + } + + private val getHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun get( + params: ScheduledGetParams, + 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", "scheduled_tools", 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/arcade-java-core/src/main/resources/META-INF/proguard/arcade-java-core.pro b/arcade-java-core/src/main/resources/META-INF/proguard/arcade-java-core.pro new file mode 100644 index 0000000..2aaad0f --- /dev/null +++ b/arcade-java-core/src/main/resources/META-INF/proguard/arcade-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 dev.arcade.** { *; } +-keep @com.fasterxml.jackson.databind.annotation.JsonDeserialize class dev.arcade.** { *; } + +# Jackson uses reflection to serialize and deserialize our classes based on their constructors and annotated members. +-keepclassmembers class dev.arcade.** { + (...); + @com.fasterxml.jackson.annotation.* *; +} \ No newline at end of file diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/TestServerExtension.kt b/arcade-java-core/src/test/kotlin/dev/arcade/TestServerExtension.kt index 45a328c..d7732e6 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/TestServerExtension.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/TestServerExtension.kt @@ -15,25 +15,12 @@ class TestServerExtension : BeforeAllCallback, ExecutionCondition { } catch (e: Exception) { throw RuntimeException( """ - The test suite will not run without a mock Prism server running against your OpenAPI spec. + The test suite will not run without a mock 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 + To fix run `./scripts/mock` in a separate terminal. """ .trimIndent(), e, diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/core/AutoPagerAsyncTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/core/AutoPagerAsyncTest.kt new file mode 100644 index 0000000..3b4c036 --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/core/AutoPagerAsyncTest.kt @@ -0,0 +1,182 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.core + +import dev.arcade.core.http.AsyncStreamResponse +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +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.extension.ExtendWith +import org.mockito.junit.jupiter.MockitoExtension +import org.mockito.kotlin.any +import org.mockito.kotlin.clearInvocations +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.inOrder +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.spy +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever + +@ExtendWith(MockitoExtension::class) +internal class AutoPagerAsyncTest { + + companion object { + + private val ERROR = RuntimeException("ERROR!") + } + + private class PageAsyncImpl( + private val items: List, + private val hasNext: Boolean = true, + ) : PageAsync { + + val nextPageFuture: CompletableFuture> = CompletableFuture() + + override fun hasNextPage(): Boolean = hasNext + + override fun nextPage(): CompletableFuture> = nextPageFuture + + override fun items(): List = items + } + + private val executor = + spy { + doAnswer { invocation -> invocation.getArgument(0).run() } + .whenever(it) + .execute(any()) + } + private val handler = mock>() + + @Test + fun subscribe_whenAlreadySubscribed_throws() { + val autoPagerAsync = AutoPagerAsync.from(PageAsyncImpl(emptyList()), executor) + autoPagerAsync.subscribe {} + clearInvocations(executor) + + val throwable = catchThrowable { autoPagerAsync.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 autoPagerAsync = AutoPagerAsync.from(PageAsyncImpl(emptyList()), executor) + autoPagerAsync.close() + + val throwable = catchThrowable { autoPagerAsync.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_whenFirstPageNonEmpty_runsHandler() { + val page = PageAsyncImpl(listOf("item1", "item2", "item3"), hasNext = false) + val autoPagerAsync = AutoPagerAsync.from(page, executor) + + autoPagerAsync.subscribe(handler) + + inOrder(executor, handler) { + verify(executor, times(1)).execute(any()) + verify(handler, times(1)).onNext("item1") + verify(handler, times(1)).onNext("item2") + verify(handler, times(1)).onNext("item3") + verify(handler, times(1)).onComplete(Optional.empty()) + } + } + + @Test + fun subscribe_whenFutureCompletesAfterClose_doesNothing() { + val page = PageAsyncImpl(listOf("page1")) + val autoPagerAsync = AutoPagerAsync.from(page, executor) + autoPagerAsync.subscribe(handler) + autoPagerAsync.close() + + page.nextPageFuture.complete(PageAsyncImpl(listOf("page2"))) + + verify(handler, times(1)).onNext("page1") + verify(handler, never()).onNext("page2") + verify(handler, times(1)).onComplete(Optional.empty()) + verify(executor, times(1)).execute(any()) + } + + @Test + fun subscribe_whenFutureErrors_callsOnComplete() { + val page = PageAsyncImpl(emptyList()) + val autoPagerAsync = AutoPagerAsync.from(page, executor) + autoPagerAsync.subscribe(handler) + + page.nextPageFuture.completeExceptionally(ERROR) + + verify(executor, times(1)).execute(any()) + verify(handler, never()).onNext(any()) + verify(handler, times(1)).onComplete(Optional.of(ERROR)) + } + + @Test + fun subscribe_whenFutureCompletes_runsHandler() { + val page = PageAsyncImpl(listOf("chunk1", "chunk2")) + val autoPagerAsync = AutoPagerAsync.from(page, executor) + + autoPagerAsync.subscribe(handler) + + verify(handler, never()).onComplete(any()) + inOrder(executor, handler) { + verify(executor, times(1)).execute(any()) + verify(handler, times(1)).onNext("chunk1") + verify(handler, times(1)).onNext("chunk2") + } + clearInvocations(executor, handler) + + page.nextPageFuture.complete(PageAsyncImpl(listOf("chunk3", "chunk4"), hasNext = false)) + + verify(executor, never()).execute(any()) + inOrder(handler) { + verify(handler, times(1)).onNext("chunk3") + verify(handler, times(1)).onNext("chunk4") + verify(handler, times(1)).onComplete(Optional.empty()) + } + } + + @Test + fun onCompleteFuture_whenNextPageFutureNotCompleted_onCompleteFutureNotCompleted() { + val page = PageAsyncImpl(listOf("chunk1", "chunk2")) + val autoPagerAsync = AutoPagerAsync.from(page, executor) + autoPagerAsync.subscribe {} + + val onCompletableFuture = autoPagerAsync.onCompleteFuture() + + assertThat(onCompletableFuture).isNotCompleted + } + + @Test + fun onCompleteFuture_whenNextPageFutureErrors_onCompleteFutureCompletedExceptionally() { + val page = PageAsyncImpl(listOf("chunk1", "chunk2")) + val autoPagerAsync = AutoPagerAsync.from(page, executor) + autoPagerAsync.subscribe {} + page.nextPageFuture.completeExceptionally(ERROR) + + val onCompletableFuture = autoPagerAsync.onCompleteFuture() + + assertThat(onCompletableFuture).isCompletedExceptionally + } + + @Test + fun onCompleteFuture_whenNoNextPage_onCompleteFutureCompleted() { + val page = PageAsyncImpl(listOf("chunk1", "chunk2"), hasNext = false) + val autoPagerAsync = AutoPagerAsync.from(page, executor) + autoPagerAsync.subscribe {} + + val onCompletableFuture = autoPagerAsync.onCompleteFuture() + + assertThat(onCompletableFuture).isCompleted + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/core/AutoPagerTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/core/AutoPagerTest.kt new file mode 100644 index 0000000..eab1c59 --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/core/AutoPagerTest.kt @@ -0,0 +1,41 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.core + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class AutoPagerTest { + + private class PageImpl( + private val items: List, + private val nextPage: Page? = null, + ) : Page { + + override fun hasNextPage(): Boolean = nextPage != null + + override fun nextPage(): Page = nextPage!! + + override fun items(): List = items + } + + @Test + fun iterator() { + val firstPage = + PageImpl(listOf("chunk1", "chunk2"), nextPage = PageImpl(listOf("chunk3", "chunk4"))) + + val autoPager = AutoPager.from(firstPage) + + assertThat(autoPager).containsExactly("chunk1", "chunk2", "chunk3", "chunk4") + } + + @Test + fun stream() { + val firstPage = + PageImpl(listOf("chunk1", "chunk2"), nextPage = PageImpl(listOf("chunk3", "chunk4"))) + + val autoPager = AutoPager.from(firstPage) + + assertThat(autoPager.stream()).containsExactly("chunk1", "chunk2", "chunk3", "chunk4") + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/core/ClientOptionsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/core/ClientOptionsTest.kt new file mode 100644 index 0000000..8a79f69 --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/core/ClientOptionsTest.kt @@ -0,0 +1,34 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.core + +import dev.arcade.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).apiKey("My API Key").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/arcade-java-core/src/test/kotlin/dev/arcade/core/ObjectMappersTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/core/ObjectMappersTest.kt new file mode 100644 index 0000000..75b58e6 --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/core/ObjectMappersTest.kt @@ -0,0 +1,117 @@ +package dev.arcade.core + +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.exc.MismatchedInputException +import com.fasterxml.jackson.module.kotlin.readValue +import java.time.LocalDate +import java.time.LocalTime +import java.time.OffsetDateTime +import java.time.ZoneOffset +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.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, + DOUBLE to FLOAT, + INTEGER to FLOAT, + INTEGER to DOUBLE, + INTEGER to LONG, + LONG to FLOAT, + LONG to DOUBLE, + LONG to INTEGER, + CLASS to MAP, + ) + } + } + + @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 LenientOffsetDateTimeTestCase( + val string: String, + val expectedOffsetDateTime: OffsetDateTime, + ) { + DATE( + "1998-04-21", + expectedOffsetDateTime = + OffsetDateTime.of(LocalDate.of(1998, 4, 21), LocalTime.of(0, 0), ZoneOffset.UTC), + ), + DATE_TIME( + "1998-04-21T04:00:00", + expectedOffsetDateTime = + OffsetDateTime.of(LocalDate.of(1998, 4, 21), LocalTime.of(4, 0), ZoneOffset.UTC), + ), + ZONED_DATE_TIME_1( + "1998-04-21T04:00:00+03:00", + expectedOffsetDateTime = + OffsetDateTime.of( + LocalDate.of(1998, 4, 21), + LocalTime.of(4, 0), + ZoneOffset.ofHours(3), + ), + ), + ZONED_DATE_TIME_2( + "1998-04-21T04:00:00Z", + expectedOffsetDateTime = + OffsetDateTime.of(LocalDate.of(1998, 4, 21), LocalTime.of(4, 0), ZoneOffset.UTC), + ), + } + + @ParameterizedTest + @EnumSource + fun readOffsetDateTime_lenient(testCase: LenientOffsetDateTimeTestCase) { + val jsonMapper = jsonMapper() + val json = jsonMapper.writeValueAsString(testCase.string) + + val offsetDateTime = jsonMapper().readValue(json) + + assertThat(offsetDateTime).isEqualTo(testCase.expectedOffsetDateTime) + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/core/PhantomReachableTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/core/PhantomReachableTest.kt index 2fd148a..183b8d7 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/core/PhantomReachableTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/core/PhantomReachableTest.kt @@ -20,7 +20,7 @@ internal class PhantomReachableTest { assertThat(closed).isFalse() System.gc() - Thread.sleep(3000) + Thread.sleep(100) assertThat(closed).isTrue() } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/core/UtilsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/core/UtilsTest.kt new file mode 100644 index 0000000..4c07cf4 --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/core/UtilsTest.kt @@ -0,0 +1,33 @@ +package dev.arcade.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/arcade-java-core/src/test/kotlin/dev/arcade/core/http/AsyncStreamResponseTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/core/http/AsyncStreamResponseTest.kt new file mode 100644 index 0000000..b404055 --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/core/http/AsyncStreamResponseTest.kt @@ -0,0 +1,268 @@ +package dev.arcade.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/arcade-java-core/src/test/kotlin/dev/arcade/core/http/HeadersTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/core/http/HeadersTest.kt index 90e1b5a..6c7ff0f 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/core/http/HeadersTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/core/http/HeadersTest.kt @@ -1,8 +1,6 @@ package dev.arcade.core.http import org.assertj.core.api.Assertions.assertThat -import org.assertj.core.api.Assertions.catchThrowable -import org.assertj.core.api.Assumptions.assumeThat import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.EnumSource @@ -241,34 +239,4 @@ internal class HeadersTest { assertThat(size).isEqualTo(testCase.expectedSize) } - - @ParameterizedTest - @EnumSource - fun namesAreImmutable(testCase: TestCase) { - val headers = testCase.headers - val headerNamesCopy = headers.names().toSet() - - val throwable = catchThrowable { - (headers.names() as MutableSet).add("another name") - } - - assertThat(throwable).isInstanceOf(UnsupportedOperationException::class.java) - assertThat(headers.names()).isEqualTo(headerNamesCopy) - } - - @ParameterizedTest - @EnumSource - fun valuesAreImmutable(testCase: TestCase) { - val headers = testCase.headers - assumeThat(headers.size).isNotEqualTo(0) - val name = headers.names().first() - val headerValuesCopy = headers.values(name).toList() - - val throwable = catchThrowable { - (headers.values(name) as MutableList).add("another value") - } - - assertThat(throwable).isInstanceOf(UnsupportedOperationException::class.java) - assertThat(headers.values(name)).isEqualTo(headerValuesCopy) - } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/core/http/HttpRequestBodiesTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/core/http/HttpRequestBodiesTest.kt new file mode 100644 index 0000000..de23baf --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/core/http/HttpRequestBodiesTest.kt @@ -0,0 +1,729 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.core.http + +import dev.arcade.core.MultipartField +import dev.arcade.core.jsonMapper +import java.io.ByteArrayOutputStream +import java.io.InputStream +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class HttpRequestBodiesTest { + + @Test + fun multipartFormData_serializesFieldWithFilename() { + val body = + multipartFormData( + jsonMapper(), + mapOf( + "file" to + MultipartField.builder() + .value("hello") + .filename("hello.txt") + .contentType("text/plain") + .build() + ), + ) + + val output = ByteArrayOutputStream() + body.writeTo(output) + + assertThat(body.repeatable()).isTrue() + assertThat(output.size().toLong()).isEqualTo(body.contentLength()) + val boundary = body.contentType()!!.substringAfter("multipart/form-data; boundary=") + assertThat(output.toString("UTF-8")) + .isEqualTo( + """ + |--$boundary + |Content-Disposition: form-data; name="file"; filename="hello.txt" + |Content-Type: text/plain + | + |hello + |--$boundary-- + | + """ + .trimMargin() + .replace("\n", "\r\n") + ) + } + + @Test + fun multipartFormData_serializesFieldWithoutFilename() { + val body = + multipartFormData( + jsonMapper(), + mapOf( + "field" to + MultipartField.builder() + .value("value") + .contentType("text/plain") + .build() + ), + ) + + val output = ByteArrayOutputStream() + body.writeTo(output) + + assertThat(body.repeatable()).isTrue() + assertThat(output.size().toLong()).isEqualTo(body.contentLength()) + val boundary = boundary(body) + assertThat(output.toString("UTF-8")) + .isEqualTo( + """ + |--$boundary + |Content-Disposition: form-data; name="field" + |Content-Type: text/plain + | + |value + |--$boundary-- + | + """ + .trimMargin() + .replace("\n", "\r\n") + ) + } + + @Test + fun multipartFormData_serializesInputStream() { + // Use `.buffered()` to get a non-ByteArrayInputStream, which hits the non-repeatable code + // path. + val inputStream = "stream content".byteInputStream().buffered() + val body = + multipartFormData( + jsonMapper(), + mapOf( + "data" to + MultipartField.builder() + .value(inputStream) + .contentType("application/octet-stream") + .build() + ), + ) + + val output = ByteArrayOutputStream() + body.writeTo(output) + + assertThat(body.repeatable()).isFalse() + assertThat(body.contentLength()).isEqualTo(-1L) + val boundary = boundary(body) + assertThat(output.toString("UTF-8")) + .isEqualTo( + """ + |--$boundary + |Content-Disposition: form-data; name="data" + |Content-Type: application/octet-stream + | + |stream content + |--$boundary-- + | + """ + .trimMargin() + .replace("\n", "\r\n") + ) + } + + @Test + fun multipartFormData_serializesByteArray() { + val body = + multipartFormData( + jsonMapper(), + mapOf( + "binary" to + MultipartField.builder() + .value("abc".toByteArray()) + .contentType("application/octet-stream") + .build() + ), + ) + + val output = ByteArrayOutputStream() + body.writeTo(output) + + assertThat(body.repeatable()).isTrue() + assertThat(body.contentLength()).isEqualTo(output.size().toLong()) + val boundary = boundary(body) + assertThat(output.toString("UTF-8")) + .isEqualTo( + """ + |--$boundary + |Content-Disposition: form-data; name="binary" + |Content-Type: application/octet-stream + | + |abc + |--$boundary-- + | + """ + .trimMargin() + .replace("\n", "\r\n") + ) + } + + @Test + fun multipartFormData_serializesBooleanValue() { + val body = + multipartFormData( + jsonMapper(), + mapOf( + "flag" to + MultipartField.builder() + .value(true) + .contentType("text/plain") + .build() + ), + ) + + val output = ByteArrayOutputStream() + body.writeTo(output) + + assertThat(body.repeatable()).isTrue() + assertThat(body.contentLength()).isEqualTo(output.size().toLong()) + val boundary = boundary(body) + assertThat(output.toString("UTF-8")) + .isEqualTo( + """ + |--$boundary + |Content-Disposition: form-data; name="flag" + |Content-Type: text/plain + | + |true + |--$boundary-- + | + """ + .trimMargin() + .replace("\n", "\r\n") + ) + } + + @Test + fun multipartFormData_serializesNumberValue() { + val body = + multipartFormData( + jsonMapper(), + mapOf( + "count" to + MultipartField.builder().value(42).contentType("text/plain").build() + ), + ) + + val output = ByteArrayOutputStream() + body.writeTo(output) + + assertThat(body.repeatable()).isTrue() + assertThat(body.contentLength()).isEqualTo(output.size().toLong()) + val boundary = boundary(body) + assertThat(output.toString("UTF-8")) + .isEqualTo( + """ + |--$boundary + |Content-Disposition: form-data; name="count" + |Content-Type: text/plain + | + |42 + |--$boundary-- + | + """ + .trimMargin() + .replace("\n", "\r\n") + ) + } + + @Test + fun multipartFormData_serializesNullValueAsNoParts() { + val body = + multipartFormData( + jsonMapper(), + mapOf( + "present" to + MultipartField.builder() + .value("yes") + .contentType("text/plain") + .build(), + "absent" to + MultipartField.builder() + .value(null as String?) + .contentType("text/plain") + .build(), + ), + ) + + val output = ByteArrayOutputStream() + body.writeTo(output) + + assertThat(body.repeatable()).isTrue() + assertThat(body.contentLength()).isEqualTo(output.size().toLong()) + val boundary = boundary(body) + assertThat(output.toString("UTF-8")) + .isEqualTo( + """ + |--$boundary + |Content-Disposition: form-data; name="present" + |Content-Type: text/plain + | + |yes + |--$boundary-- + | + """ + .trimMargin() + .replace("\n", "\r\n") + ) + } + + @Test + fun multipartFormData_serializesArray() { + val body = + multipartFormData( + jsonMapper(), + mapOf( + "items" to + MultipartField.builder>() + .value(listOf("alpha", "beta", "gamma")) + .contentType("text/plain") + .build() + ), + ) + + val output = ByteArrayOutputStream() + body.writeTo(output) + + assertThat(body.repeatable()).isTrue() + assertThat(body.contentLength()).isEqualTo(output.size().toLong()) + val boundary = boundary(body) + assertThat(output.toString("UTF-8")) + .isEqualTo( + """ + |--$boundary + |Content-Disposition: form-data; name="items" + |Content-Type: text/plain + | + |alpha,beta,gamma + |--$boundary-- + | + """ + .trimMargin() + .replace("\n", "\r\n") + ) + } + + @Test + fun multipartFormData_serializesObjectAsNestedParts() { + val body = + multipartFormData( + jsonMapper(), + mapOf( + "meta" to + MultipartField.builder>() + .value(mapOf("key1" to "val1", "key2" to "val2")) + .contentType("text/plain") + .build() + ), + ) + + val output = ByteArrayOutputStream() + body.writeTo(output) + + assertThat(body.repeatable()).isTrue() + assertThat(body.contentLength()).isEqualTo(output.size().toLong()) + val boundary = boundary(body) + assertThat(output.toString("UTF-8")) + .isEqualTo( + """ + |--$boundary + |Content-Disposition: form-data; name="meta[key1]" + |Content-Type: text/plain + | + |val1 + |--$boundary + |Content-Disposition: form-data; name="meta[key2]" + |Content-Type: text/plain + | + |val2 + |--$boundary-- + | + """ + .trimMargin() + .replace("\n", "\r\n") + ) + } + + @Test + fun multipartFormData_serializesMultipleFields() { + val body = + multipartFormData( + jsonMapper(), + mapOf( + "name" to + MultipartField.builder() + .value("Alice") + .contentType("text/plain") + .build(), + "age" to + MultipartField.builder().value(30).contentType("text/plain").build(), + "file" to + MultipartField.builder() + .value("file contents") + .filename("doc.txt") + .contentType("text/plain") + .build(), + ), + ) + + val output = ByteArrayOutputStream() + body.writeTo(output) + + assertThat(body.repeatable()).isTrue() + assertThat(body.contentLength()).isEqualTo(output.size().toLong()) + val boundary = boundary(body) + assertThat(output.toString("UTF-8")) + .isEqualTo( + """ + |--$boundary + |Content-Disposition: form-data; name="name" + |Content-Type: text/plain + | + |Alice + |--$boundary + |Content-Disposition: form-data; name="age" + |Content-Type: text/plain + | + |30 + |--$boundary + |Content-Disposition: form-data; name="file"; filename="doc.txt" + |Content-Type: text/plain + | + |file contents + |--$boundary-- + | + """ + .trimMargin() + .replace("\n", "\r\n") + ) + } + + @Test + fun multipartFormData_quotesSpecialCharactersInNameAndFilename() { + val body = + multipartFormData( + jsonMapper(), + mapOf( + "field\nname" to + MultipartField.builder() + .value("value") + .filename("file\r\"name.txt") + .contentType("text/plain") + .build() + ), + ) + + val output = ByteArrayOutputStream() + body.writeTo(output) + + assertThat(body.repeatable()).isTrue() + assertThat(body.contentLength()).isEqualTo(output.size().toLong()) + val boundary = boundary(body) + assertThat(output.toString("UTF-8")) + .isEqualTo( + """ + |--$boundary + |Content-Disposition: form-data; name="field%0Aname"; filename="file%0D%22name.txt" + |Content-Type: text/plain + | + |value + |--$boundary-- + | + """ + .trimMargin() + .replace("\n", "\r\n") + ) + } + + @Test + fun multipartFormData_writeIsRepeatable() { + val body = + multipartFormData( + jsonMapper(), + mapOf( + "field" to + MultipartField.builder() + .value("repeatable") + .contentType("text/plain") + .build() + ), + ) + + val output1 = ByteArrayOutputStream() + body.writeTo(output1) + val output2 = ByteArrayOutputStream() + body.writeTo(output2) + + assertThat(body.repeatable()).isTrue() + assertThat(body.contentLength()).isEqualTo(output1.size().toLong()) + val boundary = boundary(body) + val expected = + """ + |--$boundary + |Content-Disposition: form-data; name="field" + |Content-Type: text/plain + | + |repeatable + |--$boundary-- + | + """ + .trimMargin() + .replace("\n", "\r\n") + assertThat(output1.toString("UTF-8")).isEqualTo(expected) + assertThat(output2.toString("UTF-8")).isEqualTo(expected) + } + + @Test + fun multipartFormData_serializesByteArrayInputStream() { + // ByteArrayInputStream is specifically handled as repeatable with known content length. + val inputStream = "byte array stream".byteInputStream() + val body = + multipartFormData( + jsonMapper(), + mapOf( + "data" to + MultipartField.builder() + .value(inputStream) + .contentType("application/octet-stream") + .build() + ), + ) + + val output = ByteArrayOutputStream() + body.writeTo(output) + + assertThat(body.repeatable()).isTrue() + assertThat(body.contentLength()).isEqualTo(output.size().toLong()) + val boundary = boundary(body) + assertThat(output.toString("UTF-8")) + .isEqualTo( + """ + |--$boundary + |Content-Disposition: form-data; name="data" + |Content-Type: application/octet-stream + | + |byte array stream + |--$boundary-- + | + """ + .trimMargin() + .replace("\n", "\r\n") + ) + } + + @Test + fun multipartFormData_serializesInputStreamWithFilename() { + // Use `.buffered()` to get a non-ByteArrayInputStream, which hits the non-repeatable code + // path. + val inputStream = "file data".byteInputStream().buffered() + val body = + multipartFormData( + jsonMapper(), + mapOf( + "upload" to + MultipartField.builder() + .value(inputStream) + .filename("upload.bin") + .contentType("application/octet-stream") + .build() + ), + ) + + val output = ByteArrayOutputStream() + body.writeTo(output) + + assertThat(body.repeatable()).isFalse() + assertThat(body.contentLength()).isEqualTo(-1L) + val boundary = boundary(body) + assertThat(output.toString("UTF-8")) + .isEqualTo( + """ + |--$boundary + |Content-Disposition: form-data; name="upload"; filename="upload.bin" + |Content-Type: application/octet-stream + | + |file data + |--$boundary-- + | + """ + .trimMargin() + .replace("\n", "\r\n") + ) + } + + @Test + fun multipartFormData_serializesNestedArrayInObject() { + val body = + multipartFormData( + jsonMapper(), + mapOf( + "data" to + MultipartField.builder>>() + .value(mapOf("tags" to listOf("a", "b"))) + .contentType("text/plain") + .build() + ), + ) + + val output = ByteArrayOutputStream() + body.writeTo(output) + + assertThat(body.repeatable()).isTrue() + assertThat(body.contentLength()).isEqualTo(output.size().toLong()) + val boundary = boundary(body) + assertThat(output.toString("UTF-8")) + .isEqualTo( + """ + |--$boundary + |Content-Disposition: form-data; name="data[tags]" + |Content-Type: text/plain + | + |a,b + |--$boundary-- + | + """ + .trimMargin() + .replace("\n", "\r\n") + ) + } + + @Test + fun multipartFormData_contentLengthIsUnknownWhenInputStreamPresent() { + val body = + multipartFormData( + jsonMapper(), + mapOf( + "text" to + MultipartField.builder() + .value("hello") + .contentType("text/plain") + .build(), + "stream" to + MultipartField.builder() + // Use `.buffered()` to get a non-ByteArrayInputStream, which hits the + // non-repeatable code path. + .value("data".byteInputStream().buffered()) + .contentType("application/octet-stream") + .build(), + ), + ) + + val output = ByteArrayOutputStream() + body.writeTo(output) + + assertThat(body.repeatable()).isFalse() + assertThat(body.contentLength()).isEqualTo(-1L) + val boundary = boundary(body) + assertThat(output.toString("UTF-8")) + .isEqualTo( + """ + |--$boundary + |Content-Disposition: form-data; name="text" + |Content-Type: text/plain + | + |hello + |--$boundary + |Content-Disposition: form-data; name="stream" + |Content-Type: application/octet-stream + | + |data + |--$boundary-- + | + """ + .trimMargin() + .replace("\n", "\r\n") + ) + } + + @Test + fun multipartFormData_serializesEmptyArray() { + val body = + multipartFormData( + jsonMapper(), + mapOf( + "required" to + MultipartField.builder() + .value("present") + .contentType("text/plain") + .build(), + "items" to + MultipartField.builder>() + .value(emptyList()) + .contentType("text/plain") + .build(), + ), + ) + + val output = ByteArrayOutputStream() + body.writeTo(output) + + assertThat(body.repeatable()).isTrue() + assertThat(body.contentLength()).isEqualTo(output.size().toLong()) + val boundary = boundary(body) + assertThat(output.toString("UTF-8")) + .isEqualTo( + """ + |--$boundary + |Content-Disposition: form-data; name="required" + |Content-Type: text/plain + | + |present + |--$boundary + |Content-Disposition: form-data; name="items" + |Content-Type: text/plain + | + | + |--$boundary-- + | + """ + .trimMargin() + .replace("\n", "\r\n") + ) + } + + @Test + fun multipartFormData_serializesEmptyObject() { + val body = + multipartFormData( + jsonMapper(), + mapOf( + "required" to + MultipartField.builder() + .value("present") + .contentType("text/plain") + .build(), + "meta" to + MultipartField.builder>() + .value(emptyMap()) + .contentType("text/plain") + .build(), + ), + ) + + val output = ByteArrayOutputStream() + body.writeTo(output) + + assertThat(body.repeatable()).isTrue() + assertThat(body.contentLength()).isEqualTo(output.size().toLong()) + val boundary = boundary(body) + assertThat(output.toString("UTF-8")) + .isEqualTo( + """ + |--$boundary + |Content-Disposition: form-data; name="required" + |Content-Type: text/plain + | + |present + |--$boundary-- + | + """ + .trimMargin() + .replace("\n", "\r\n") + ) + } + + private fun boundary(body: HttpRequestBody): String = + body.contentType()!!.substringAfter("multipart/form-data; boundary=") +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/core/http/HttpRequestTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/core/http/HttpRequestTest.kt new file mode 100644 index 0000000..ed1ad53 --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/core/http/HttpRequestTest.kt @@ -0,0 +1,110 @@ +package dev.arcade.core.http + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.EnumSource + +internal class HttpRequestTest { + + enum class UrlTestCase(val request: HttpRequest, val expectedUrl: String) { + BASE_URL_ONLY( + HttpRequest.builder().method(HttpMethod.GET).baseUrl("https://api.example.com").build(), + expectedUrl = "https://api.example.com", + ), + BASE_URL_WITH_TRAILING_SLASH( + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl("https://api.example.com/") + .build(), + expectedUrl = "https://api.example.com/", + ), + SINGLE_PATH_SEGMENT( + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl("https://api.example.com") + .addPathSegment("users") + .build(), + expectedUrl = "https://api.example.com/users", + ), + MULTIPLE_PATH_SEGMENTS( + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl("https://api.example.com") + .addPathSegments("users", "123", "profile") + .build(), + expectedUrl = "https://api.example.com/users/123/profile", + ), + PATH_SEGMENT_WITH_SPECIAL_CHARS( + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl("https://api.example.com") + .addPathSegment("user name") + .build(), + expectedUrl = "https://api.example.com/user+name", + ), + SINGLE_QUERY_PARAM( + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl("https://api.example.com") + .addPathSegment("users") + .putQueryParam("limit", "10") + .build(), + expectedUrl = "https://api.example.com/users?limit=10", + ), + MULTIPLE_QUERY_PARAMS( + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl("https://api.example.com") + .addPathSegment("users") + .putQueryParam("limit", "10") + .putQueryParam("offset", "20") + .build(), + expectedUrl = "https://api.example.com/users?limit=10&offset=20", + ), + QUERY_PARAM_WITH_SPECIAL_CHARS( + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl("https://api.example.com") + .addPathSegment("search") + .putQueryParam("q", "hello world") + .build(), + expectedUrl = "https://api.example.com/search?q=hello+world", + ), + MULTIPLE_VALUES_SAME_PARAM( + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl("https://api.example.com") + .addPathSegment("users") + .putQueryParams("tags", listOf("admin", "user")) + .build(), + expectedUrl = "https://api.example.com/users?tags=admin&tags=user", + ), + BASE_URL_WITH_TRAILING_SLASH_AND_PATH( + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl("https://api.example.com/") + .addPathSegment("users") + .build(), + expectedUrl = "https://api.example.com/users", + ), + COMPLEX_URL( + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl("https://api.example.com") + .addPathSegments("v1", "users", "123") + .putQueryParams("include", listOf("profile", "settings")) + .putQueryParam("format", "json") + .build(), + expectedUrl = + "https://api.example.com/v1/users/123?include=profile&include=settings&format=json", + ), + } + + @ParameterizedTest + @EnumSource + fun url(testCase: UrlTestCase) { + val actualUrl = testCase.request.url() + + assertThat(actualUrl).isEqualTo(testCase.expectedUrl) + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/core/http/QueryParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/core/http/QueryParamsTest.kt index 90bbefe..23d2e27 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/core/http/QueryParamsTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/core/http/QueryParamsTest.kt @@ -1,8 +1,6 @@ package dev.arcade.core.http import org.assertj.core.api.Assertions.assertThat -import org.assertj.core.api.Assertions.catchThrowable -import org.assertj.core.api.Assumptions.assumeThat import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.EnumSource @@ -179,34 +177,4 @@ internal class QueryParamsTest { assertThat(size).isEqualTo(testCase.expectedSize) } - - @ParameterizedTest - @EnumSource - fun keysAreImmutable(testCase: TestCase) { - val queryParams = testCase.queryParams - val queryParamKeysCopy = queryParams.keys().toSet() - - val throwable = catchThrowable { - (queryParams.keys() as MutableSet).add("another key") - } - - assertThat(throwable).isInstanceOf(UnsupportedOperationException::class.java) - assertThat(queryParams.keys()).isEqualTo(queryParamKeysCopy) - } - - @ParameterizedTest - @EnumSource - fun valuesAreImmutable(testCase: TestCase) { - val queryParams = testCase.queryParams - assumeThat(queryParams.size).isNotEqualTo(0) - val key = queryParams.keys().first() - val queryParamValuesCopy = queryParams.values(key).toList() - - val throwable = catchThrowable { - (queryParams.values(key) as MutableList).add("another value") - } - - assertThat(throwable).isInstanceOf(UnsupportedOperationException::class.java) - assertThat(queryParams.values(key)).isEqualTo(queryParamValuesCopy) - } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/core/http/RetryingHttpClientTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/core/http/RetryingHttpClientTest.kt index 68d25e5..eb6750d 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/core/http/RetryingHttpClientTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/core/http/RetryingHttpClientTest.kt @@ -1,29 +1,48 @@ +// File generated from our OpenAPI spec by Stainless. + package dev.arcade.core.http -import com.github.tomakehurst.wiremock.client.WireMock.* +import com.github.tomakehurst.wiremock.client.WireMock.equalTo +import com.github.tomakehurst.wiremock.client.WireMock.matching +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.resetAllScenarios +import com.github.tomakehurst.wiremock.client.WireMock.serviceUnavailable +import com.github.tomakehurst.wiremock.client.WireMock.stubFor +import com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo +import com.github.tomakehurst.wiremock.client.WireMock.verify import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo import com.github.tomakehurst.wiremock.junit5.WireMockTest import com.github.tomakehurst.wiremock.stubbing.Scenario import dev.arcade.client.okhttp.OkHttpClient import dev.arcade.core.RequestOptions +import dev.arcade.core.Sleeper +import dev.arcade.errors.ArcadeRetryableException 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) { - val okHttpClient = OkHttpClient.builder().baseUrl(wmRuntimeInfo.httpBaseUrl).build() + baseUrl = wmRuntimeInfo.httpBaseUrl + val okHttpClient = OkHttpClient.builder().build() httpClient = object : HttpClient { + override fun execute( request: HttpRequest, requestOptions: RequestOptions, @@ -40,6 +59,7 @@ internal class RetryingHttpClientTest { private fun trackClose(response: HttpResponse): HttpResponse { openResponseCount++ return object : HttpResponse { + private var isClosed = false override fun statusCode(): Int = response.statusCode() @@ -66,11 +86,15 @@ internal class RetryingHttpClientTest { @ValueSource(booleans = [false, true]) fun execute(async: Boolean) { stubFor(post(urlPathEqualTo("/something")).willReturn(ok())) - val retryingClient = RetryingHttpClient.builder().httpClient(httpClient).build() + val retryingClient = retryingHttpClientBuilder().build() val response = retryingClient.execute( - HttpRequest.builder().method(HttpMethod.POST).addPathSegment("something").build(), + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(baseUrl) + .addPathSegment("something") + .build(), async, ) @@ -88,15 +112,15 @@ internal class RetryingHttpClientTest { .willReturn(ok()) ) val retryingClient = - RetryingHttpClient.builder() - .httpClient(httpClient) - .maxRetries(2) - .idempotencyHeader("X-Some-Header") - .build() + retryingHttpClientBuilder().maxRetries(2).idempotencyHeader("X-Some-Header").build() val response = retryingClient.execute( - HttpRequest.builder().method(HttpMethod.POST).addPathSegment("something").build(), + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(baseUrl) + .addPathSegment("something") + .build(), async, ) @@ -134,12 +158,15 @@ internal class RetryingHttpClientTest { .willReturn(ok()) .willSetStateTo("COMPLETED") ) - val retryingClient = - RetryingHttpClient.builder().httpClient(httpClient).maxRetries(2).build() + val retryingClient = retryingHttpClientBuilder().maxRetries(2).build() val response = retryingClient.execute( - HttpRequest.builder().method(HttpMethod.POST).addPathSegment("something").build(), + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(baseUrl) + .addPathSegment("something") + .build(), async, ) @@ -181,13 +208,13 @@ internal class RetryingHttpClientTest { .willReturn(ok()) .willSetStateTo("COMPLETED") ) - val retryingClient = - RetryingHttpClient.builder().httpClient(httpClient).maxRetries(2).build() + 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(), @@ -220,12 +247,15 @@ internal class RetryingHttpClientTest { .willReturn(ok()) .willSetStateTo("COMPLETED") ) - val retryingClient = - RetryingHttpClient.builder().httpClient(httpClient).maxRetries(1).build() + val retryingClient = retryingHttpClientBuilder().maxRetries(1).build() val response = retryingClient.execute( - HttpRequest.builder().method(HttpMethod.POST).addPathSegment("something").build(), + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(baseUrl) + .addPathSegment("something") + .build(), async, ) @@ -234,6 +264,100 @@ internal class RetryingHttpClientTest { 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 ArcadeRetryableException("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( + ArcadeRetryableException("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 : Sleeper { + + override fun sleep(duration: Duration) {} + + override fun sleepAsync(duration: Duration): CompletableFuture = + CompletableFuture.completedFuture(null) + + override fun close() {} + } + ) + .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 : Sleeper { + + override fun sleep(duration: Duration) {} + + override fun sleepAsync(duration: Duration): CompletableFuture = + CompletableFuture.completedFuture(null) + + override fun close() {} + } + ) + private fun HttpClient.execute(request: HttpRequest, async: Boolean): HttpResponse = if (async) executeAsync(request).get() else execute(request) diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/core/http/SerializerTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/core/http/SerializerTest.kt deleted file mode 100644 index 72cf6b2..0000000 --- a/arcade-java-core/src/test/kotlin/dev/arcade/core/http/SerializerTest.kt +++ /dev/null @@ -1,99 +0,0 @@ -package dev.arcade.core.http - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import dev.arcade.core.* -import java.util.* -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -internal class SerializerTest { - @JsonDeserialize(builder = ClassWithBooleanFieldPrefixedWithIs.Builder::class) - @NoAutoDetect - class ClassWithBooleanFieldPrefixedWithIs - private constructor( - private val isActive: JsonField, - private val additionalProperties: Map, - ) { - private var validated: Boolean = false - - private var hashCode: Int = 0 - - fun isActive(): Boolean? = isActive.getNullable("is_active") - - @JsonProperty("is_active") @ExcludeMissing fun _isActive() = isActive - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate() = apply { - if (!validated) { - isActive() - validated = true - } - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ClassWithBooleanFieldPrefixedWithIs && - isActive == other.isActive && - additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(isActive, additionalProperties) - } - return hashCode - } - - override fun toString() = - "MyClass{isActive=$isActive, additionalProperties=$additionalProperties}" - - companion object { - fun builder() = Builder() - } - - @NoAutoDetect - class Builder internal constructor() { - - private var isActive: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - fun isActive(isActive: Boolean) = isActive(JsonField.of(isActive)) - - @JsonProperty("is_active") - @ExcludeMissing - fun isActive(isActive: JsonField) = apply { this.isActive = isActive } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) - } - - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun build(): ClassWithBooleanFieldPrefixedWithIs = - ClassWithBooleanFieldPrefixedWithIs(isActive, additionalProperties.toImmutable()) - } - } - - @Test - fun serializeBooleanPrefixedWithIs() { - val value = ClassWithBooleanFieldPrefixedWithIs.builder().isActive(true).build() - assertThat(jsonMapper().writeValueAsString(value)).isEqualTo("{\"is_active\":true}") - } -} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminAuthProviderDeleteParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminAuthProviderDeleteParamsTest.kt deleted file mode 100644 index f8cb244..0000000 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminAuthProviderDeleteParamsTest.kt +++ /dev/null @@ -1,24 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.models - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class AdminAuthProviderDeleteParamsTest { - - @Test - fun create() { - AdminAuthProviderDeleteParams.builder().id("id").build() - } - - @Test - fun getPathParam() { - val params = AdminAuthProviderDeleteParams.builder().id("id").build() - assertThat(params).isNotNull - // path param "id" - assertThat(params.getPathParam(0)).isEqualTo("id") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") - } -} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminAuthProviderGetParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminAuthProviderGetParamsTest.kt deleted file mode 100644 index 2a6766a..0000000 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminAuthProviderGetParamsTest.kt +++ /dev/null @@ -1,24 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.models - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class AdminAuthProviderGetParamsTest { - - @Test - fun create() { - AdminAuthProviderGetParams.builder().id("id").build() - } - - @Test - fun getPathParam() { - val params = AdminAuthProviderGetParams.builder().id("id").build() - assertThat(params).isNotNull - // path param "id" - assertThat(params.getPathParam(0)).isEqualTo("id") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") - } -} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminSecretDeleteParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminSecretDeleteParamsTest.kt deleted file mode 100644 index cd2cc87..0000000 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminSecretDeleteParamsTest.kt +++ /dev/null @@ -1,24 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.models - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class AdminSecretDeleteParamsTest { - - @Test - fun create() { - AdminSecretDeleteParams.builder().secretId("secret_id").build() - } - - @Test - fun getPathParam() { - val params = AdminSecretDeleteParams.builder().secretId("secret_id").build() - assertThat(params).isNotNull - // path param "secretId" - assertThat(params.getPathParam(0)).isEqualTo("secret_id") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") - } -} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminSecretListParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminSecretListParamsTest.kt deleted file mode 100644 index 869cd2d..0000000 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminSecretListParamsTest.kt +++ /dev/null @@ -1,13 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.models - -import org.junit.jupiter.api.Test - -class AdminSecretListParamsTest { - - @Test - fun create() { - AdminSecretListParams.builder().build() - } -} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminSecretListResponseTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminSecretListResponseTest.kt deleted file mode 100644 index a3377d3..0000000 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminSecretListResponseTest.kt +++ /dev/null @@ -1,60 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.models - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class AdminSecretListResponseTest { - - @Test - fun createAdminSecretListResponse() { - val adminSecretListResponse = - AdminSecretListResponse.builder() - .addItem( - SecretResponse.builder() - .id("id") - .binding( - SecretResponse.Binding.builder() - .id("id") - .type(SecretResponse.Binding.Type.STATIC) - .build() - ) - .createdAt("created_at") - .description("description") - .hint("hint") - .key("key") - .lastAccessedAt("last_accessed_at") - .updatedAt("updated_at") - .build() - ) - .limit(0L) - .offset(0L) - .pageCount(0L) - .totalCount(0L) - .build() - assertThat(adminSecretListResponse).isNotNull - assertThat(adminSecretListResponse.items().get()) - .containsExactly( - SecretResponse.builder() - .id("id") - .binding( - SecretResponse.Binding.builder() - .id("id") - .type(SecretResponse.Binding.Type.STATIC) - .build() - ) - .createdAt("created_at") - .description("description") - .hint("hint") - .key("key") - .lastAccessedAt("last_accessed_at") - .updatedAt("updated_at") - .build() - ) - assertThat(adminSecretListResponse.limit()).contains(0L) - assertThat(adminSecretListResponse.offset()).contains(0L) - assertThat(adminSecretListResponse.pageCount()).contains(0L) - assertThat(adminSecretListResponse.totalCount()).contains(0L) - } -} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminUserConnectionDeleteParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminUserConnectionDeleteParamsTest.kt deleted file mode 100644 index 74e4428..0000000 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminUserConnectionDeleteParamsTest.kt +++ /dev/null @@ -1,24 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.models - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class AdminUserConnectionDeleteParamsTest { - - @Test - fun create() { - AdminUserConnectionDeleteParams.builder().id("id").build() - } - - @Test - fun getPathParam() { - val params = AdminUserConnectionDeleteParams.builder().id("id").build() - assertThat(params).isNotNull - // path param "id" - assertThat(params.getPathParam(0)).isEqualTo("id") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") - } -} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminUserConnectionListParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminUserConnectionListParamsTest.kt deleted file mode 100644 index 487252b..0000000 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminUserConnectionListParamsTest.kt +++ /dev/null @@ -1,52 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.models - -import dev.arcade.core.http.QueryParams -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class AdminUserConnectionListParamsTest { - - @Test - fun create() { - AdminUserConnectionListParams.builder() - .limit(0L) - .offset(0L) - .provider(AdminUserConnectionListParams.Provider.builder().id("id").build()) - .user(AdminUserConnectionListParams.User.builder().id("id").build()) - .build() - } - - @Test - fun queryParams() { - val params = - AdminUserConnectionListParams.builder() - .limit(0L) - .offset(0L) - .provider(AdminUserConnectionListParams.Provider.builder().id("id").build()) - .user(AdminUserConnectionListParams.User.builder().id("id").build()) - .build() - val expected = QueryParams.builder() - expected.put("limit", "0") - expected.put("offset", "0") - AdminUserConnectionListParams.Provider.builder().id("id").build().forEachQueryParam { - key, - values -> - expected.put("provider[$key]", values) - } - AdminUserConnectionListParams.User.builder().id("id").build().forEachQueryParam { - key, - values -> - expected.put("user[$key]", values) - } - assertThat(params._queryParams()).isEqualTo(expected.build()) - } - - @Test - fun queryParamsWithoutOptionalFields() { - val params = AdminUserConnectionListParams.builder().build() - val expected = QueryParams.builder() - assertThat(params._queryParams()).isEqualTo(expected.build()) - } -} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/AuthorizationContextTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/AuthorizationContextTest.kt index b025c1f..8e33186 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/AuthorizationContextTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/AuthorizationContextTest.kt @@ -2,14 +2,16 @@ package dev.arcade.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import dev.arcade.core.JsonValue +import dev.arcade.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class AuthorizationContextTest { +internal class AuthorizationContextTest { @Test - fun createAuthorizationContext() { + fun create() { val authorizationContext = AuthorizationContext.builder() .token("token") @@ -19,7 +21,7 @@ class AuthorizationContextTest { .build() ) .build() - assertThat(authorizationContext).isNotNull + assertThat(authorizationContext.token()).contains("token") assertThat(authorizationContext.userInfo()) .contains( @@ -28,4 +30,26 @@ class AuthorizationContextTest { .build() ) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val authorizationContext = + AuthorizationContext.builder() + .token("token") + .userInfo( + AuthorizationContext.UserInfo.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + + val roundtrippedAuthorizationContext = + jsonMapper.readValue( + jsonMapper.writeValueAsString(authorizationContext), + jacksonTypeRef(), + ) + + assertThat(roundtrippedAuthorizationContext).isEqualTo(authorizationContext) + } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/AuthorizationResponseTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/AuthorizationResponseTest.kt index 5dc22a4..1a59ec6 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/AuthorizationResponseTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/AuthorizationResponseTest.kt @@ -2,14 +2,17 @@ package dev.arcade.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import dev.arcade.core.JsonValue +import dev.arcade.core.jsonMapper +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class AuthorizationResponseTest { +internal class AuthorizationResponseTest { @Test - fun createAuthorizationResponse() { + fun create() { val authorizationResponse = AuthorizationResponse.builder() .id("id") @@ -29,7 +32,7 @@ class AuthorizationResponseTest { .url("url") .userId("user_id") .build() - assertThat(authorizationResponse).isNotNull + assertThat(authorizationResponse.id()).contains("id") assertThat(authorizationResponse.context()) .contains( @@ -43,10 +46,42 @@ class AuthorizationResponseTest { .build() ) assertThat(authorizationResponse.providerId()).contains("provider_id") - assertThat(authorizationResponse.scopes().get()).containsExactly("string") + assertThat(authorizationResponse.scopes().getOrNull()).containsExactly("string") assertThat(authorizationResponse.status()) .contains(AuthorizationResponse.Status.NOT_STARTED) assertThat(authorizationResponse.url()).contains("url") assertThat(authorizationResponse.userId()).contains("user_id") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val authorizationResponse = + AuthorizationResponse.builder() + .id("id") + .context( + AuthorizationContext.builder() + .token("token") + .userInfo( + AuthorizationContext.UserInfo.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .providerId("provider_id") + .addScope("string") + .status(AuthorizationResponse.Status.NOT_STARTED) + .url("url") + .userId("user_id") + .build() + + val roundtrippedAuthorizationResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(authorizationResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedAuthorizationResponse).isEqualTo(authorizationResponse) + } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/AuthorizeToolRequestTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/AuthorizeToolRequestTest.kt deleted file mode 100644 index d703ef6..0000000 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/AuthorizeToolRequestTest.kt +++ /dev/null @@ -1,25 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.models - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class AuthorizeToolRequestTest { - - @Test - fun createAuthorizeToolRequest() { - val authorizeToolRequest = - AuthorizeToolRequest.builder() - .toolName("tool_name") - .nextUri("next_uri") - .toolVersion("tool_version") - .userId("user_id") - .build() - assertThat(authorizeToolRequest).isNotNull - assertThat(authorizeToolRequest.toolName()).isEqualTo("tool_name") - assertThat(authorizeToolRequest.nextUri()).contains("next_uri") - assertThat(authorizeToolRequest.toolVersion()).contains("tool_version") - assertThat(authorizeToolRequest.userId()).contains("user_id") - } -} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/ConfirmUserRequestTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/ConfirmUserRequestTest.kt deleted file mode 100644 index 41a9555..0000000 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/ConfirmUserRequestTest.kt +++ /dev/null @@ -1,18 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.models - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class ConfirmUserRequestTest { - - @Test - fun createConfirmUserRequest() { - val confirmUserRequest = - ConfirmUserRequest.builder().flowId("flow_id").userId("user_id").build() - assertThat(confirmUserRequest).isNotNull - assertThat(confirmUserRequest.flowId()).isEqualTo("flow_id") - assertThat(confirmUserRequest.userId()).isEqualTo("user_id") - } -} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/ConfirmUserResponseTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/ConfirmUserResponseTest.kt deleted file mode 100644 index bc2aa26..0000000 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/ConfirmUserResponseTest.kt +++ /dev/null @@ -1,18 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.models - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class ConfirmUserResponseTest { - - @Test - fun createConfirmUserResponse() { - val confirmUserResponse = - ConfirmUserResponse.builder().authId("auth_id").nextUri("next_uri").build() - assertThat(confirmUserResponse).isNotNull - assertThat(confirmUserResponse.authId()).isEqualTo("auth_id") - assertThat(confirmUserResponse.nextUri()).contains("next_uri") - } -} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/ErrorTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/ErrorTest.kt index 6e0a37a..ee81c28 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/ErrorTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/ErrorTest.kt @@ -2,16 +2,29 @@ package dev.arcade.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import dev.arcade.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ErrorTest { +internal class ErrorTest { @Test - fun createError() { + fun create() { val error = Error.builder().message("message").name("name").build() - assertThat(error).isNotNull + assertThat(error.message()).contains("message") assertThat(error.name()).contains("name") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val error = Error.builder().message("message").name("name").build() + + val roundtrippedError = + jsonMapper.readValue(jsonMapper.writeValueAsString(error), jacksonTypeRef()) + + assertThat(roundtrippedError).isEqualTo(error) + } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/HealthSchemaTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/HealthSchemaTest.kt deleted file mode 100644 index d511343..0000000 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/HealthSchemaTest.kt +++ /dev/null @@ -1,16 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.models - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class HealthSchemaTest { - - @Test - fun createHealthSchema() { - val healthSchema = HealthSchema.builder().healthy(true).build() - assertThat(healthSchema).isNotNull - assertThat(healthSchema.healthy()).contains(true) - } -} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolFormattedGetParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolFormattedGetParamsTest.kt deleted file mode 100644 index 1f60791..0000000 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolFormattedGetParamsTest.kt +++ /dev/null @@ -1,42 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.models - -import dev.arcade.core.http.QueryParams -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class ToolFormattedGetParamsTest { - - @Test - fun create() { - ToolFormattedGetParams.builder().name("name").format("format").userId("user_id").build() - } - - @Test - fun queryParams() { - val params = - ToolFormattedGetParams.builder().name("name").format("format").userId("user_id").build() - val expected = QueryParams.builder() - expected.put("format", "format") - expected.put("user_id", "user_id") - assertThat(params._queryParams()).isEqualTo(expected.build()) - } - - @Test - fun queryParamsWithoutOptionalFields() { - val params = ToolFormattedGetParams.builder().name("name").build() - val expected = QueryParams.builder() - assertThat(params._queryParams()).isEqualTo(expected.build()) - } - - @Test - fun getPathParam() { - val params = ToolFormattedGetParams.builder().name("name").build() - assertThat(params).isNotNull - // path param "name" - assertThat(params.getPathParam(0)).isEqualTo("name") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") - } -} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolFormattedListParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolFormattedListParamsTest.kt deleted file mode 100644 index 9e908e7..0000000 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolFormattedListParamsTest.kt +++ /dev/null @@ -1,50 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.models - -import dev.arcade.core.http.QueryParams -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class ToolFormattedListParamsTest { - - @Test - fun create() { - ToolFormattedListParams.builder() - .format("format") - .includeAllVersions(true) - .limit(0L) - .offset(0L) - .toolkit("toolkit") - .userId("user_id") - .build() - } - - @Test - fun queryParams() { - val params = - ToolFormattedListParams.builder() - .format("format") - .includeAllVersions(true) - .limit(0L) - .offset(0L) - .toolkit("toolkit") - .userId("user_id") - .build() - val expected = QueryParams.builder() - expected.put("format", "format") - expected.put("include_all_versions", "true") - expected.put("limit", "0") - expected.put("offset", "0") - expected.put("toolkit", "toolkit") - expected.put("user_id", "user_id") - assertThat(params._queryParams()).isEqualTo(expected.build()) - } - - @Test - fun queryParamsWithoutOptionalFields() { - val params = ToolFormattedListParams.builder().build() - val expected = QueryParams.builder() - assertThat(params._queryParams()).isEqualTo(expected.build()) - } -} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolScheduledGetParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolScheduledGetParamsTest.kt deleted file mode 100644 index 1de2b26..0000000 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolScheduledGetParamsTest.kt +++ /dev/null @@ -1,24 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.models - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class ToolScheduledGetParamsTest { - - @Test - fun create() { - ToolScheduledGetParams.builder().id("id").build() - } - - @Test - fun getPathParam() { - val params = ToolScheduledGetParams.builder().id("id").build() - assertThat(params).isNotNull - // path param "id" - assertThat(params.getPathParam(0)).isEqualTo("id") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") - } -} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolScheduledListParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolScheduledListParamsTest.kt deleted file mode 100644 index a0dc93c..0000000 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolScheduledListParamsTest.kt +++ /dev/null @@ -1,31 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.models - -import dev.arcade.core.http.QueryParams -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class ToolScheduledListParamsTest { - - @Test - fun create() { - ToolScheduledListParams.builder().limit(0L).offset(0L).build() - } - - @Test - fun queryParams() { - val params = ToolScheduledListParams.builder().limit(0L).offset(0L).build() - val expected = QueryParams.builder() - expected.put("limit", "0") - expected.put("offset", "0") - assertThat(params._queryParams()).isEqualTo(expected.build()) - } - - @Test - fun queryParamsWithoutOptionalFields() { - val params = ToolScheduledListParams.builder().build() - val expected = QueryParams.builder() - assertThat(params._queryParams()).isEqualTo(expected.build()) - } -} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/UsageTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/UsageTest.kt deleted file mode 100644 index 183a31a..0000000 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/UsageTest.kt +++ /dev/null @@ -1,18 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.models - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class UsageTest { - - @Test - fun createUsage() { - val usage = Usage.builder().completionTokens(0L).promptTokens(0L).totalTokens(0L).build() - assertThat(usage).isNotNull - assertThat(usage.completionTokens()).contains(0L) - assertThat(usage.promptTokens()).contains(0L) - assertThat(usage.totalTokens()).contains(0L) - } -} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/ValueSchemaTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/ValueSchemaTest.kt deleted file mode 100644 index 4905468..0000000 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/ValueSchemaTest.kt +++ /dev/null @@ -1,23 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.models - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class ValueSchemaTest { - - @Test - fun createValueSchema() { - val valueSchema = - ValueSchema.builder() - .valType("val_type") - .addEnum("string") - .innerValType("inner_val_type") - .build() - assertThat(valueSchema).isNotNull - assertThat(valueSchema.valType()).isEqualTo("val_type") - assertThat(valueSchema.enum_().get()).containsExactly("string") - assertThat(valueSchema.innerValType()).contains("inner_val_type") - } -} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/WorkerHealthResponseTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/WorkerHealthResponseTest.kt deleted file mode 100644 index 623bcee..0000000 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/WorkerHealthResponseTest.kt +++ /dev/null @@ -1,25 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package dev.arcade.models - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class WorkerHealthResponseTest { - - @Test - fun createWorkerHealthResponse() { - val workerHealthResponse = - WorkerHealthResponse.builder() - .id("id") - .enabled(true) - .healthy(true) - .message("message") - .build() - assertThat(workerHealthResponse).isNotNull - assertThat(workerHealthResponse.id()).contains("id") - assertThat(workerHealthResponse.enabled()).contains(true) - assertThat(workerHealthResponse.healthy()).contains(true) - assertThat(workerHealthResponse.message()).contains("message") - } -} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminAuthProviderCreateParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/authproviders/AuthProviderCreateParamsTest.kt similarity index 99% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/AdminAuthProviderCreateParamsTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/admin/authproviders/AuthProviderCreateParamsTest.kt index 979de35..81b5640 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminAuthProviderCreateParamsTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/authproviders/AuthProviderCreateParamsTest.kt @@ -1,16 +1,16 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.admin.authproviders import dev.arcade.core.JsonValue import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class AdminAuthProviderCreateParamsTest { +internal class AuthProviderCreateParamsTest { @Test fun create() { - AdminAuthProviderCreateParams.builder() + AuthProviderCreateParams.builder() .authProviderCreateRequest( AuthProviderCreateRequest.builder() .id("id") @@ -210,7 +210,7 @@ class AdminAuthProviderCreateParamsTest { @Test fun body() { val params = - AdminAuthProviderCreateParams.builder() + AuthProviderCreateParams.builder() .authProviderCreateRequest( AuthProviderCreateRequest.builder() .id("id") @@ -647,7 +647,7 @@ class AdminAuthProviderCreateParamsTest { @Test fun bodyWithoutOptionalFields() { val params = - AdminAuthProviderCreateParams.builder() + AuthProviderCreateParams.builder() .authProviderCreateRequest(AuthProviderCreateRequest.builder().id("id").build()) .build() diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/AuthProviderCreateRequestTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/authproviders/AuthProviderCreateRequestTest.kt similarity index 64% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/AuthProviderCreateRequestTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/admin/authproviders/AuthProviderCreateRequestTest.kt index 8f7dd46..34b1d3c 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/AuthProviderCreateRequestTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/authproviders/AuthProviderCreateRequestTest.kt @@ -1,15 +1,17 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.admin.authproviders +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import dev.arcade.core.JsonValue +import dev.arcade.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class AuthProviderCreateRequestTest { +internal class AuthProviderCreateRequestTest { @Test - fun createAuthProviderCreateRequest() { + fun create() { val authProviderCreateRequest = AuthProviderCreateRequest.builder() .id("id") @@ -196,7 +198,7 @@ class AuthProviderCreateRequestTest { .status("status") .type("type") .build() - assertThat(authProviderCreateRequest).isNotNull + assertThat(authProviderCreateRequest.id()).isEqualTo("id") assertThat(authProviderCreateRequest.description()).contains("description") assertThat(authProviderCreateRequest.externalId()).contains("external_id") @@ -370,4 +372,203 @@ class AuthProviderCreateRequestTest { assertThat(authProviderCreateRequest.status()).contains("status") assertThat(authProviderCreateRequest.type()).contains("type") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val authProviderCreateRequest = + AuthProviderCreateRequest.builder() + .id("id") + .description("description") + .externalId("external_id") + .oauth2( + AuthProviderCreateRequest.Oauth2.builder() + .clientId("client_id") + .authorizeRequest( + AuthProviderCreateRequest.Oauth2.AuthorizeRequest.builder() + .endpoint("endpoint") + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .method("method") + .params( + AuthProviderCreateRequest.Oauth2.AuthorizeRequest.Params + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .requestContentType( + AuthProviderCreateRequest.Oauth2.AuthorizeRequest + .RequestContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseContentType( + AuthProviderCreateRequest.Oauth2.AuthorizeRequest + .ResponseContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseMap( + AuthProviderCreateRequest.Oauth2.AuthorizeRequest.ResponseMap + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .build() + ) + .clientSecret("client_secret") + .pkce( + AuthProviderCreateRequest.Oauth2.Pkce.builder() + .codeChallengeMethod("code_challenge_method") + .enabled(true) + .build() + ) + .refreshRequest( + AuthProviderCreateRequest.Oauth2.RefreshRequest.builder() + .endpoint("endpoint") + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .method("method") + .params( + AuthProviderCreateRequest.Oauth2.RefreshRequest.Params.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .requestContentType( + AuthProviderCreateRequest.Oauth2.RefreshRequest + .RequestContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseContentType( + AuthProviderCreateRequest.Oauth2.RefreshRequest + .ResponseContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseMap( + AuthProviderCreateRequest.Oauth2.RefreshRequest.ResponseMap + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .build() + ) + .scopeDelimiter(AuthProviderCreateRequest.Oauth2.ScopeDelimiter.Unknown0) + .tokenIntrospectionRequest( + AuthProviderCreateRequest.Oauth2.TokenIntrospectionRequest.builder() + .endpoint("endpoint") + .triggers( + AuthProviderCreateRequest.Oauth2.TokenIntrospectionRequest + .Triggers + .builder() + .onTokenGrant(true) + .onTokenRefresh(true) + .build() + ) + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .method("method") + .params( + AuthProviderCreateRequest.Oauth2.TokenIntrospectionRequest + .Params + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .requestContentType( + AuthProviderCreateRequest.Oauth2.TokenIntrospectionRequest + .RequestContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseContentType( + AuthProviderCreateRequest.Oauth2.TokenIntrospectionRequest + .ResponseContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseMap( + AuthProviderCreateRequest.Oauth2.TokenIntrospectionRequest + .ResponseMap + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .build() + ) + .tokenRequest( + AuthProviderCreateRequest.Oauth2.TokenRequest.builder() + .endpoint("endpoint") + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .method("method") + .params( + AuthProviderCreateRequest.Oauth2.TokenRequest.Params.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .requestContentType( + AuthProviderCreateRequest.Oauth2.TokenRequest.RequestContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseContentType( + AuthProviderCreateRequest.Oauth2.TokenRequest + .ResponseContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseMap( + AuthProviderCreateRequest.Oauth2.TokenRequest.ResponseMap + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .build() + ) + .userInfoRequest( + AuthProviderCreateRequest.Oauth2.UserInfoRequest.builder() + .endpoint("endpoint") + .triggers( + AuthProviderCreateRequest.Oauth2.UserInfoRequest.Triggers + .builder() + .onTokenGrant(true) + .onTokenRefresh(true) + .build() + ) + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .method("method") + .params( + AuthProviderCreateRequest.Oauth2.UserInfoRequest.Params + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .requestContentType( + AuthProviderCreateRequest.Oauth2.UserInfoRequest + .RequestContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseContentType( + AuthProviderCreateRequest.Oauth2.UserInfoRequest + .ResponseContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseMap( + AuthProviderCreateRequest.Oauth2.UserInfoRequest.ResponseMap + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .build() + ) + .build() + ) + .providerId("provider_id") + .status("status") + .type("type") + .build() + + val roundtrippedAuthProviderCreateRequest = + jsonMapper.readValue( + jsonMapper.writeValueAsString(authProviderCreateRequest), + jacksonTypeRef(), + ) + + assertThat(roundtrippedAuthProviderCreateRequest).isEqualTo(authProviderCreateRequest) + } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/authproviders/AuthProviderDeleteParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/authproviders/AuthProviderDeleteParamsTest.kt new file mode 100644 index 0000000..20620f4 --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/authproviders/AuthProviderDeleteParamsTest.kt @@ -0,0 +1,23 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.admin.authproviders + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class AuthProviderDeleteParamsTest { + + @Test + fun create() { + AuthProviderDeleteParams.builder().id("id").build() + } + + @Test + fun pathParams() { + val params = AuthProviderDeleteParams.builder().id("id").build() + + assertThat(params._pathParam(0)).isEqualTo("id") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/authproviders/AuthProviderGetParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/authproviders/AuthProviderGetParamsTest.kt new file mode 100644 index 0000000..bff9c9d --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/authproviders/AuthProviderGetParamsTest.kt @@ -0,0 +1,23 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.admin.authproviders + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class AuthProviderGetParamsTest { + + @Test + fun create() { + AuthProviderGetParams.builder().id("id").build() + } + + @Test + fun pathParams() { + val params = AuthProviderGetParams.builder().id("id").build() + + assertThat(params._pathParam(0)).isEqualTo("id") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/authproviders/AuthProviderListParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/authproviders/AuthProviderListParamsTest.kt new file mode 100644 index 0000000..bbb6a91 --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/authproviders/AuthProviderListParamsTest.kt @@ -0,0 +1,13 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.admin.authproviders + +import org.junit.jupiter.api.Test + +internal class AuthProviderListParamsTest { + + @Test + fun create() { + AuthProviderListParams.builder().build() + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminAuthProviderListResponseTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/authproviders/AuthProviderListResponseTest.kt similarity index 62% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/AdminAuthProviderListResponseTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/admin/authproviders/AuthProviderListResponseTest.kt index 5e3067d..bf6ff84 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminAuthProviderListResponseTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/authproviders/AuthProviderListResponseTest.kt @@ -1,17 +1,20 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.admin.authproviders +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import dev.arcade.core.JsonValue +import dev.arcade.core.jsonMapper +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class AdminAuthProviderListResponseTest { +internal class AuthProviderListResponseTest { @Test - fun createAdminAuthProviderListResponse() { - val adminAuthProviderListResponse = - AdminAuthProviderListResponse.builder() + fun create() { + val authProviderListResponse = + AuthProviderListResponse.builder() .addItem( AuthProviderResponse.builder() .id("id") @@ -62,7 +65,6 @@ class AdminAuthProviderListResponseTest { ) .editable(true) .exists(true) - .hint("hint") .value("value") .build() ) @@ -221,8 +223,8 @@ class AdminAuthProviderListResponseTest { .pageCount(0L) .totalCount(0L) .build() - assertThat(adminAuthProviderListResponse).isNotNull - assertThat(adminAuthProviderListResponse.items().get()) + + assertThat(authProviderListResponse.items().getOrNull()) .containsExactly( AuthProviderResponse.builder() .id("id") @@ -267,7 +269,6 @@ class AdminAuthProviderListResponseTest { ) .editable(true) .exists(true) - .hint("hint") .value("value") .build() ) @@ -393,9 +394,232 @@ class AdminAuthProviderListResponseTest { .updatedAt("updated_at") .build() ) - assertThat(adminAuthProviderListResponse.limit()).contains(0L) - assertThat(adminAuthProviderListResponse.offset()).contains(0L) - assertThat(adminAuthProviderListResponse.pageCount()).contains(0L) - assertThat(adminAuthProviderListResponse.totalCount()).contains(0L) + assertThat(authProviderListResponse.limit()).contains(0L) + assertThat(authProviderListResponse.offset()).contains(0L) + assertThat(authProviderListResponse.pageCount()).contains(0L) + assertThat(authProviderListResponse.totalCount()).contains(0L) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val authProviderListResponse = + AuthProviderListResponse.builder() + .addItem( + AuthProviderResponse.builder() + .id("id") + .binding( + AuthProviderResponse.Binding.builder() + .id("id") + .type(AuthProviderResponse.Binding.Type.STATIC) + .build() + ) + .createdAt("created_at") + .description("description") + .oauth2( + AuthProviderResponse.Oauth2.builder() + .authorizeRequest( + AuthProviderResponse.Oauth2.AuthorizeRequest.builder() + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .endpoint("endpoint") + .expirationFormat("expiration_format") + .method("method") + .params( + AuthProviderResponse.Oauth2.AuthorizeRequest.Params + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("string"), + ) + .build() + ) + .requestContentType("request_content_type") + .responseContentType("response_content_type") + .responseMap( + AuthProviderResponse.Oauth2.AuthorizeRequest.ResponseMap + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("string"), + ) + .build() + ) + .build() + ) + .clientId("client_id") + .clientSecret( + AuthProviderResponse.Oauth2.ClientSecret.builder() + .binding( + AuthProviderResponse.Oauth2.ClientSecret.Binding.STATIC + ) + .editable(true) + .exists(true) + .value("value") + .build() + ) + .pkce( + AuthProviderResponse.Oauth2.Pkce.builder() + .codeChallengeMethod("code_challenge_method") + .enabled(true) + .build() + ) + .redirectUri("redirect_uri") + .refreshRequest( + AuthProviderResponse.Oauth2.RefreshRequest.builder() + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .endpoint("endpoint") + .expirationFormat("expiration_format") + .method("method") + .params( + AuthProviderResponse.Oauth2.RefreshRequest.Params + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("string"), + ) + .build() + ) + .requestContentType("request_content_type") + .responseContentType("response_content_type") + .responseMap( + AuthProviderResponse.Oauth2.RefreshRequest.ResponseMap + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("string"), + ) + .build() + ) + .build() + ) + .scopeDelimiter("scope_delimiter") + .tokenIntrospectionRequest( + AuthProviderResponse.Oauth2.TokenIntrospectionRequest.builder() + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .enabled(true) + .endpoint("endpoint") + .expirationFormat("expiration_format") + .method("method") + .params( + AuthProviderResponse.Oauth2.TokenIntrospectionRequest + .Params + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("string"), + ) + .build() + ) + .requestContentType("request_content_type") + .responseContentType("response_content_type") + .responseMap( + AuthProviderResponse.Oauth2.TokenIntrospectionRequest + .ResponseMap + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("string"), + ) + .build() + ) + .triggers( + AuthProviderResponse.Oauth2.TokenIntrospectionRequest + .Triggers + .builder() + .onTokenGrant(true) + .onTokenRefresh(true) + .build() + ) + .build() + ) + .tokenRequest( + AuthProviderResponse.Oauth2.TokenRequest.builder() + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .endpoint("endpoint") + .expirationFormat("expiration_format") + .method("method") + .params( + AuthProviderResponse.Oauth2.TokenRequest.Params + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("string"), + ) + .build() + ) + .requestContentType("request_content_type") + .responseContentType("response_content_type") + .responseMap( + AuthProviderResponse.Oauth2.TokenRequest.ResponseMap + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("string"), + ) + .build() + ) + .build() + ) + .userInfoRequest( + AuthProviderResponse.Oauth2.UserInfoRequest.builder() + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .endpoint("endpoint") + .expirationFormat("expiration_format") + .method("method") + .params( + AuthProviderResponse.Oauth2.UserInfoRequest.Params + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("string"), + ) + .build() + ) + .requestContentType("request_content_type") + .responseContentType("response_content_type") + .responseMap( + AuthProviderResponse.Oauth2.UserInfoRequest.ResponseMap + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("string"), + ) + .build() + ) + .triggers( + AuthProviderResponse.Oauth2.UserInfoRequest.Triggers + .builder() + .onTokenGrant(true) + .onTokenRefresh(true) + .build() + ) + .build() + ) + .build() + ) + .providerId("provider_id") + .status("status") + .type("type") + .updatedAt("updated_at") + .build() + ) + .limit(0L) + .offset(0L) + .pageCount(0L) + .totalCount(0L) + .build() + + val roundtrippedAuthProviderListResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(authProviderListResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedAuthProviderListResponse).isEqualTo(authProviderListResponse) } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminAuthProviderPatchParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/authproviders/AuthProviderPatchParamsTest.kt similarity index 97% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/AdminAuthProviderPatchParamsTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/admin/authproviders/AuthProviderPatchParamsTest.kt index 11f0e9b..6e659de 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminAuthProviderPatchParamsTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/authproviders/AuthProviderPatchParamsTest.kt @@ -1,17 +1,17 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.admin.authproviders import dev.arcade.core.JsonValue import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class AdminAuthProviderPatchParamsTest { +internal class AuthProviderPatchParamsTest { @Test fun create() { - AdminAuthProviderPatchParams.builder() - .id("id") + AuthProviderPatchParams.builder() + .pathId("id") .authProviderUpdateRequest( AuthProviderUpdateRequest.builder() .id("id") @@ -88,7 +88,7 @@ class AdminAuthProviderPatchParamsTest { .build() ) .scopeDelimiter( - AuthProviderUpdateRequest.Oauth2.ScopeDelimiter.Unknown1 + AuthProviderUpdateRequest.Oauth2.ScopeDelimiter.Unknown2 ) .tokenRequest( AuthProviderUpdateRequest.Oauth2.TokenRequest.builder() @@ -167,11 +167,24 @@ class AdminAuthProviderPatchParamsTest { .build() } + @Test + fun pathParams() { + val params = + AuthProviderPatchParams.builder() + .pathId("id") + .authProviderUpdateRequest(AuthProviderUpdateRequest.builder().build()) + .build() + + assertThat(params._pathParam(0)).isEqualTo("id") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = - AdminAuthProviderPatchParams.builder() - .id("id") + AuthProviderPatchParams.builder() + .pathId("id") .authProviderUpdateRequest( AuthProviderUpdateRequest.builder() .id("id") @@ -261,7 +274,7 @@ class AdminAuthProviderPatchParamsTest { .build() ) .scopeDelimiter( - AuthProviderUpdateRequest.Oauth2.ScopeDelimiter.Unknown1 + AuthProviderUpdateRequest.Oauth2.ScopeDelimiter.Unknown2 ) .tokenRequest( AuthProviderUpdateRequest.Oauth2.TokenRequest.builder() @@ -433,7 +446,7 @@ class AdminAuthProviderPatchParamsTest { .build() ) .scopeDelimiter( - AuthProviderUpdateRequest.Oauth2.ScopeDelimiter.Unknown1 + AuthProviderUpdateRequest.Oauth2.ScopeDelimiter.Unknown2 ) .tokenRequest( AuthProviderUpdateRequest.Oauth2.TokenRequest.builder() @@ -514,8 +527,8 @@ class AdminAuthProviderPatchParamsTest { @Test fun bodyWithoutOptionalFields() { val params = - AdminAuthProviderPatchParams.builder() - .id("id") + AuthProviderPatchParams.builder() + .pathId("id") .authProviderUpdateRequest(AuthProviderUpdateRequest.builder().build()) .build() @@ -523,18 +536,4 @@ class AdminAuthProviderPatchParamsTest { assertThat(body).isEqualTo(AuthProviderUpdateRequest.builder().build()) } - - @Test - fun getPathParam() { - val params = - AdminAuthProviderPatchParams.builder() - .id("id") - .authProviderUpdateRequest(AuthProviderUpdateRequest.builder().build()) - .build() - assertThat(params).isNotNull - // path param "id" - assertThat(params.getPathParam(0)).isEqualTo("id") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") - } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/AuthProviderResponseTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/authproviders/AuthProviderResponseTest.kt similarity index 64% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/AuthProviderResponseTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/admin/authproviders/AuthProviderResponseTest.kt index 7d71986..a5fe088 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/AuthProviderResponseTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/authproviders/AuthProviderResponseTest.kt @@ -1,15 +1,17 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.admin.authproviders +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import dev.arcade.core.JsonValue +import dev.arcade.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class AuthProviderResponseTest { +internal class AuthProviderResponseTest { @Test - fun createAuthProviderResponse() { + fun create() { val authProviderResponse = AuthProviderResponse.builder() .id("id") @@ -51,7 +53,6 @@ class AuthProviderResponseTest { .binding(AuthProviderResponse.Oauth2.ClientSecret.Binding.STATIC) .editable(true) .exists(true) - .hint("hint") .value("value") .build() ) @@ -172,7 +173,7 @@ class AuthProviderResponseTest { .type("type") .updatedAt("updated_at") .build() - assertThat(authProviderResponse).isNotNull + assertThat(authProviderResponse.id()).contains("id") assertThat(authProviderResponse.binding()) .contains( @@ -213,7 +214,6 @@ class AuthProviderResponseTest { .binding(AuthProviderResponse.Oauth2.ClientSecret.Binding.STATIC) .editable(true) .exists(true) - .hint("hint") .value("value") .build() ) @@ -332,4 +332,178 @@ class AuthProviderResponseTest { assertThat(authProviderResponse.type()).contains("type") assertThat(authProviderResponse.updatedAt()).contains("updated_at") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val authProviderResponse = + AuthProviderResponse.builder() + .id("id") + .binding( + AuthProviderResponse.Binding.builder() + .id("id") + .type(AuthProviderResponse.Binding.Type.STATIC) + .build() + ) + .createdAt("created_at") + .description("description") + .oauth2( + AuthProviderResponse.Oauth2.builder() + .authorizeRequest( + AuthProviderResponse.Oauth2.AuthorizeRequest.builder() + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .endpoint("endpoint") + .expirationFormat("expiration_format") + .method("method") + .params( + AuthProviderResponse.Oauth2.AuthorizeRequest.Params.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .requestContentType("request_content_type") + .responseContentType("response_content_type") + .responseMap( + AuthProviderResponse.Oauth2.AuthorizeRequest.ResponseMap + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .build() + ) + .clientId("client_id") + .clientSecret( + AuthProviderResponse.Oauth2.ClientSecret.builder() + .binding(AuthProviderResponse.Oauth2.ClientSecret.Binding.STATIC) + .editable(true) + .exists(true) + .value("value") + .build() + ) + .pkce( + AuthProviderResponse.Oauth2.Pkce.builder() + .codeChallengeMethod("code_challenge_method") + .enabled(true) + .build() + ) + .redirectUri("redirect_uri") + .refreshRequest( + AuthProviderResponse.Oauth2.RefreshRequest.builder() + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .endpoint("endpoint") + .expirationFormat("expiration_format") + .method("method") + .params( + AuthProviderResponse.Oauth2.RefreshRequest.Params.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .requestContentType("request_content_type") + .responseContentType("response_content_type") + .responseMap( + AuthProviderResponse.Oauth2.RefreshRequest.ResponseMap.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .build() + ) + .scopeDelimiter("scope_delimiter") + .tokenIntrospectionRequest( + AuthProviderResponse.Oauth2.TokenIntrospectionRequest.builder() + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .enabled(true) + .endpoint("endpoint") + .expirationFormat("expiration_format") + .method("method") + .params( + AuthProviderResponse.Oauth2.TokenIntrospectionRequest.Params + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .requestContentType("request_content_type") + .responseContentType("response_content_type") + .responseMap( + AuthProviderResponse.Oauth2.TokenIntrospectionRequest + .ResponseMap + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .triggers( + AuthProviderResponse.Oauth2.TokenIntrospectionRequest.Triggers + .builder() + .onTokenGrant(true) + .onTokenRefresh(true) + .build() + ) + .build() + ) + .tokenRequest( + AuthProviderResponse.Oauth2.TokenRequest.builder() + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .endpoint("endpoint") + .expirationFormat("expiration_format") + .method("method") + .params( + AuthProviderResponse.Oauth2.TokenRequest.Params.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .requestContentType("request_content_type") + .responseContentType("response_content_type") + .responseMap( + AuthProviderResponse.Oauth2.TokenRequest.ResponseMap.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .build() + ) + .userInfoRequest( + AuthProviderResponse.Oauth2.UserInfoRequest.builder() + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .endpoint("endpoint") + .expirationFormat("expiration_format") + .method("method") + .params( + AuthProviderResponse.Oauth2.UserInfoRequest.Params.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .requestContentType("request_content_type") + .responseContentType("response_content_type") + .responseMap( + AuthProviderResponse.Oauth2.UserInfoRequest.ResponseMap + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .triggers( + AuthProviderResponse.Oauth2.UserInfoRequest.Triggers.builder() + .onTokenGrant(true) + .onTokenRefresh(true) + .build() + ) + .build() + ) + .build() + ) + .providerId("provider_id") + .status("status") + .type("type") + .updatedAt("updated_at") + .build() + + val roundtrippedAuthProviderResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(authProviderResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedAuthProviderResponse).isEqualTo(authProviderResponse) + } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/AuthProviderUpdateRequestTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/authproviders/AuthProviderUpdateRequestTest.kt similarity index 64% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/AuthProviderUpdateRequestTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/admin/authproviders/AuthProviderUpdateRequestTest.kt index eda924c..c551713 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/AuthProviderUpdateRequestTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/authproviders/AuthProviderUpdateRequestTest.kt @@ -1,15 +1,17 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.admin.authproviders +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import dev.arcade.core.JsonValue +import dev.arcade.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class AuthProviderUpdateRequestTest { +internal class AuthProviderUpdateRequestTest { @Test - fun createAuthProviderUpdateRequest() { + fun create() { val authProviderUpdateRequest = AuthProviderUpdateRequest.builder() .id("id") @@ -83,7 +85,7 @@ class AuthProviderUpdateRequestTest { ) .build() ) - .scopeDelimiter(AuthProviderUpdateRequest.Oauth2.ScopeDelimiter.Unknown1) + .scopeDelimiter(AuthProviderUpdateRequest.Oauth2.ScopeDelimiter.Unknown2) .tokenRequest( AuthProviderUpdateRequest.Oauth2.TokenRequest.builder() .authHeaderValueFormat("auth_header_value_format") @@ -155,7 +157,7 @@ class AuthProviderUpdateRequestTest { .status("status") .type("type") .build() - assertThat(authProviderUpdateRequest).isNotNull + assertThat(authProviderUpdateRequest.id()).contains("id") assertThat(authProviderUpdateRequest.description()).contains("description") assertThat(authProviderUpdateRequest.oauth2()) @@ -224,7 +226,7 @@ class AuthProviderUpdateRequestTest { ) .build() ) - .scopeDelimiter(AuthProviderUpdateRequest.Oauth2.ScopeDelimiter.Unknown1) + .scopeDelimiter(AuthProviderUpdateRequest.Oauth2.ScopeDelimiter.Unknown2) .tokenRequest( AuthProviderUpdateRequest.Oauth2.TokenRequest.builder() .authHeaderValueFormat("auth_header_value_format") @@ -290,4 +292,162 @@ class AuthProviderUpdateRequestTest { assertThat(authProviderUpdateRequest.status()).contains("status") assertThat(authProviderUpdateRequest.type()).contains("type") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val authProviderUpdateRequest = + AuthProviderUpdateRequest.builder() + .id("id") + .description("description") + .oauth2( + AuthProviderUpdateRequest.Oauth2.builder() + .authorizeRequest( + AuthProviderUpdateRequest.Oauth2.AuthorizeRequest.builder() + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .endpoint("endpoint") + .method("method") + .params( + AuthProviderUpdateRequest.Oauth2.AuthorizeRequest.Params + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .requestContentType( + AuthProviderUpdateRequest.Oauth2.AuthorizeRequest + .RequestContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseContentType( + AuthProviderUpdateRequest.Oauth2.AuthorizeRequest + .ResponseContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseMap( + AuthProviderUpdateRequest.Oauth2.AuthorizeRequest.ResponseMap + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .build() + ) + .clientId("client_id") + .clientSecret("client_secret") + .pkce( + AuthProviderUpdateRequest.Oauth2.Pkce.builder() + .codeChallengeMethod("code_challenge_method") + .enabled(true) + .build() + ) + .refreshRequest( + AuthProviderUpdateRequest.Oauth2.RefreshRequest.builder() + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .endpoint("endpoint") + .method("method") + .params( + AuthProviderUpdateRequest.Oauth2.RefreshRequest.Params.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .requestContentType( + AuthProviderUpdateRequest.Oauth2.RefreshRequest + .RequestContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseContentType( + AuthProviderUpdateRequest.Oauth2.RefreshRequest + .ResponseContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseMap( + AuthProviderUpdateRequest.Oauth2.RefreshRequest.ResponseMap + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .build() + ) + .scopeDelimiter(AuthProviderUpdateRequest.Oauth2.ScopeDelimiter.Unknown2) + .tokenRequest( + AuthProviderUpdateRequest.Oauth2.TokenRequest.builder() + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .endpoint("endpoint") + .method("method") + .params( + AuthProviderUpdateRequest.Oauth2.TokenRequest.Params.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .requestContentType( + AuthProviderUpdateRequest.Oauth2.TokenRequest.RequestContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseContentType( + AuthProviderUpdateRequest.Oauth2.TokenRequest + .ResponseContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseMap( + AuthProviderUpdateRequest.Oauth2.TokenRequest.ResponseMap + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .build() + ) + .userInfoRequest( + AuthProviderUpdateRequest.Oauth2.UserInfoRequest.builder() + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .endpoint("endpoint") + .method("method") + .params( + AuthProviderUpdateRequest.Oauth2.UserInfoRequest.Params + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .requestContentType( + AuthProviderUpdateRequest.Oauth2.UserInfoRequest + .RequestContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseContentType( + AuthProviderUpdateRequest.Oauth2.UserInfoRequest + .ResponseContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseMap( + AuthProviderUpdateRequest.Oauth2.UserInfoRequest.ResponseMap + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .triggers( + AuthProviderUpdateRequest.Oauth2.UserInfoRequest.Triggers + .builder() + .onTokenGrant(true) + .onTokenRefresh(true) + .build() + ) + .build() + ) + .build() + ) + .providerId("provider_id") + .status("status") + .type("type") + .build() + + val roundtrippedAuthProviderUpdateRequest = + jsonMapper.readValue( + jsonMapper.writeValueAsString(authProviderUpdateRequest), + jacksonTypeRef(), + ) + + assertThat(roundtrippedAuthProviderUpdateRequest).isEqualTo(authProviderUpdateRequest) + } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminSecretCreateParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/secrets/SecretCreateParamsTest.kt similarity index 55% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/AdminSecretCreateParamsTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/admin/secrets/SecretCreateParamsTest.kt index 5fbf52f..70bbb98 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminSecretCreateParamsTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/secrets/SecretCreateParamsTest.kt @@ -1,26 +1,34 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.admin.secrets -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class AdminSecretCreateParamsTest { +internal class SecretCreateParamsTest { @Test fun create() { - AdminSecretCreateParams.builder() + SecretCreateParams.builder() .secretKey("secret_key") .value("value") .description("description") .build() } + @Test + fun pathParams() { + val params = SecretCreateParams.builder().secretKey("secret_key").value("value").build() + + assertThat(params._pathParam(0)).isEqualTo("secret_key") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = - AdminSecretCreateParams.builder() + SecretCreateParams.builder() .secretKey("secret_key") .value("value") .description("description") @@ -28,30 +36,16 @@ class AdminSecretCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.value()).isEqualTo("value") assertThat(body.description()).contains("description") } @Test fun bodyWithoutOptionalFields() { - val params = - AdminSecretCreateParams.builder().secretKey("secret_key").value("value").build() + val params = SecretCreateParams.builder().secretKey("secret_key").value("value").build() val body = params._body() - assertNotNull(body) assertThat(body.value()).isEqualTo("value") } - - @Test - fun getPathParam() { - val params = - AdminSecretCreateParams.builder().secretKey("secret_key").value("value").build() - assertThat(params).isNotNull - // path param "secretKey" - assertThat(params.getPathParam(0)).isEqualTo("secret_key") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") - } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/secrets/SecretDeleteParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/secrets/SecretDeleteParamsTest.kt new file mode 100644 index 0000000..e57c65a --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/secrets/SecretDeleteParamsTest.kt @@ -0,0 +1,23 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.admin.secrets + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class SecretDeleteParamsTest { + + @Test + fun create() { + SecretDeleteParams.builder().secretId("secret_id").build() + } + + @Test + fun pathParams() { + val params = SecretDeleteParams.builder().secretId("secret_id").build() + + assertThat(params._pathParam(0)).isEqualTo("secret_id") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminAuthProviderListParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/secrets/SecretListParamsTest.kt similarity index 51% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/AdminAuthProviderListParamsTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/admin/secrets/SecretListParamsTest.kt index 4c8ac92..358a44e 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/AdminAuthProviderListParamsTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/secrets/SecretListParamsTest.kt @@ -1,13 +1,13 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.admin.secrets import org.junit.jupiter.api.Test -class AdminAuthProviderListParamsTest { +internal class SecretListParamsTest { @Test fun create() { - AdminAuthProviderListParams.builder().build() + SecretListParams.builder().build() } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/secrets/SecretListResponseTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/secrets/SecretListResponseTest.kt new file mode 100644 index 0000000..03d5c8f --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/secrets/SecretListResponseTest.kt @@ -0,0 +1,97 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.admin.secrets + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import dev.arcade.core.jsonMapper +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class SecretListResponseTest { + + @Test + fun create() { + val secretListResponse = + SecretListResponse.builder() + .addItem( + SecretResponse.builder() + .id("id") + .binding( + SecretResponse.Binding.builder() + .id("id") + .type(SecretResponse.Binding.Type.STATIC) + .build() + ) + .createdAt("created_at") + .description("description") + .key("key") + .lastAccessedAt("last_accessed_at") + .updatedAt("updated_at") + .build() + ) + .limit(0L) + .offset(0L) + .pageCount(0L) + .totalCount(0L) + .build() + + assertThat(secretListResponse.items().getOrNull()) + .containsExactly( + SecretResponse.builder() + .id("id") + .binding( + SecretResponse.Binding.builder() + .id("id") + .type(SecretResponse.Binding.Type.STATIC) + .build() + ) + .createdAt("created_at") + .description("description") + .key("key") + .lastAccessedAt("last_accessed_at") + .updatedAt("updated_at") + .build() + ) + assertThat(secretListResponse.limit()).contains(0L) + assertThat(secretListResponse.offset()).contains(0L) + assertThat(secretListResponse.pageCount()).contains(0L) + assertThat(secretListResponse.totalCount()).contains(0L) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val secretListResponse = + SecretListResponse.builder() + .addItem( + SecretResponse.builder() + .id("id") + .binding( + SecretResponse.Binding.builder() + .id("id") + .type(SecretResponse.Binding.Type.STATIC) + .build() + ) + .createdAt("created_at") + .description("description") + .key("key") + .lastAccessedAt("last_accessed_at") + .updatedAt("updated_at") + .build() + ) + .limit(0L) + .offset(0L) + .pageCount(0L) + .totalCount(0L) + .build() + + val roundtrippedSecretListResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(secretListResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedSecretListResponse).isEqualTo(secretListResponse) + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/SecretResponseTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/secrets/SecretResponseTest.kt similarity index 55% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/SecretResponseTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/admin/secrets/SecretResponseTest.kt index 86104fc..c36c4f8 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/SecretResponseTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/secrets/SecretResponseTest.kt @@ -1,14 +1,16 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.admin.secrets +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import dev.arcade.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class SecretResponseTest { +internal class SecretResponseTest { @Test - fun createSecretResponse() { + fun create() { val secretResponse = SecretResponse.builder() .id("id") @@ -20,12 +22,11 @@ class SecretResponseTest { ) .createdAt("created_at") .description("description") - .hint("hint") .key("key") .lastAccessedAt("last_accessed_at") .updatedAt("updated_at") .build() - assertThat(secretResponse).isNotNull + assertThat(secretResponse.id()).contains("id") assertThat(secretResponse.binding()) .contains( @@ -36,9 +37,36 @@ class SecretResponseTest { ) assertThat(secretResponse.createdAt()).contains("created_at") assertThat(secretResponse.description()).contains("description") - assertThat(secretResponse.hint()).contains("hint") assertThat(secretResponse.key()).contains("key") assertThat(secretResponse.lastAccessedAt()).contains("last_accessed_at") assertThat(secretResponse.updatedAt()).contains("updated_at") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val secretResponse = + SecretResponse.builder() + .id("id") + .binding( + SecretResponse.Binding.builder() + .id("id") + .type(SecretResponse.Binding.Type.STATIC) + .build() + ) + .createdAt("created_at") + .description("description") + .key("key") + .lastAccessedAt("last_accessed_at") + .updatedAt("updated_at") + .build() + + val roundtrippedSecretResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(secretResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedSecretResponse).isEqualTo(secretResponse) + } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/userconnections/UserConnectionDeleteParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/userconnections/UserConnectionDeleteParamsTest.kt new file mode 100644 index 0000000..0d56138 --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/userconnections/UserConnectionDeleteParamsTest.kt @@ -0,0 +1,23 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.admin.userconnections + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class UserConnectionDeleteParamsTest { + + @Test + fun create() { + UserConnectionDeleteParams.builder().id("id").build() + } + + @Test + fun pathParams() { + val params = UserConnectionDeleteParams.builder().id("id").build() + + assertThat(params._pathParam(0)).isEqualTo("id") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/userconnections/UserConnectionListPageResponseTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/userconnections/UserConnectionListPageResponseTest.kt new file mode 100644 index 0000000..7bf47a3 --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/userconnections/UserConnectionListPageResponseTest.kt @@ -0,0 +1,90 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.admin.userconnections + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import dev.arcade.core.JsonValue +import dev.arcade.core.jsonMapper +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class UserConnectionListPageResponseTest { + + @Test + fun create() { + val userConnectionListPageResponse = + UserConnectionListPageResponse.builder() + .addItem( + UserConnectionResponse.builder() + .id("id") + .connectionId("connection_id") + .connectionStatus("connection_status") + .providerDescription("provider_description") + .providerId("provider_id") + .providerType("provider_type") + .providerUserInfo(JsonValue.from(mapOf())) + .addScope("string") + .userId("user_id") + .build() + ) + .limit(0L) + .offset(0L) + .pageCount(0L) + .totalCount(0L) + .build() + + assertThat(userConnectionListPageResponse.items().getOrNull()) + .containsExactly( + UserConnectionResponse.builder() + .id("id") + .connectionId("connection_id") + .connectionStatus("connection_status") + .providerDescription("provider_description") + .providerId("provider_id") + .providerType("provider_type") + .providerUserInfo(JsonValue.from(mapOf())) + .addScope("string") + .userId("user_id") + .build() + ) + assertThat(userConnectionListPageResponse.limit()).contains(0L) + assertThat(userConnectionListPageResponse.offset()).contains(0L) + assertThat(userConnectionListPageResponse.pageCount()).contains(0L) + assertThat(userConnectionListPageResponse.totalCount()).contains(0L) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val userConnectionListPageResponse = + UserConnectionListPageResponse.builder() + .addItem( + UserConnectionResponse.builder() + .id("id") + .connectionId("connection_id") + .connectionStatus("connection_status") + .providerDescription("provider_description") + .providerId("provider_id") + .providerType("provider_type") + .providerUserInfo(JsonValue.from(mapOf())) + .addScope("string") + .userId("user_id") + .build() + ) + .limit(0L) + .offset(0L) + .pageCount(0L) + .totalCount(0L) + .build() + + val roundtrippedUserConnectionListPageResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(userConnectionListPageResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedUserConnectionListPageResponse) + .isEqualTo(userConnectionListPageResponse) + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/userconnections/UserConnectionListParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/userconnections/UserConnectionListParamsTest.kt new file mode 100644 index 0000000..72afc34 --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/userconnections/UserConnectionListParamsTest.kt @@ -0,0 +1,52 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.admin.userconnections + +import dev.arcade.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class UserConnectionListParamsTest { + + @Test + fun create() { + UserConnectionListParams.builder() + .limit(0L) + .offset(0L) + .providerId("provider_id") + .userId("user_id") + .build() + } + + @Test + fun queryParams() { + val params = + UserConnectionListParams.builder() + .limit(0L) + .offset(0L) + .providerId("provider_id") + .userId("user_id") + .build() + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("limit", "0") + .put("offset", "0") + .put("provider_id", "provider_id") + .put("user_id", "user_id") + .build() + ) + } + + @Test + fun queryParamsWithoutOptionalFields() { + val params = UserConnectionListParams.builder().build() + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/UserConnectionResponseTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/userconnections/UserConnectionResponseTest.kt similarity index 53% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/UserConnectionResponseTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/admin/userconnections/UserConnectionResponseTest.kt index 8e78fba..0f61736 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/UserConnectionResponseTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/admin/userconnections/UserConnectionResponseTest.kt @@ -1,15 +1,18 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.admin.userconnections +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import dev.arcade.core.JsonValue +import dev.arcade.core.jsonMapper +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class UserConnectionResponseTest { +internal class UserConnectionResponseTest { @Test - fun createUserConnectionResponse() { + fun create() { val userConnectionResponse = UserConnectionResponse.builder() .id("id") @@ -22,7 +25,7 @@ class UserConnectionResponseTest { .addScope("string") .userId("user_id") .build() - assertThat(userConnectionResponse).isNotNull + assertThat(userConnectionResponse.id()).contains("id") assertThat(userConnectionResponse.connectionId()).contains("connection_id") assertThat(userConnectionResponse.connectionStatus()).contains("connection_status") @@ -31,7 +34,32 @@ class UserConnectionResponseTest { assertThat(userConnectionResponse.providerType()).contains("provider_type") assertThat(userConnectionResponse._providerUserInfo()) .isEqualTo(JsonValue.from(mapOf())) - assertThat(userConnectionResponse.scopes().get()).containsExactly("string") + assertThat(userConnectionResponse.scopes().getOrNull()).containsExactly("string") assertThat(userConnectionResponse.userId()).contains("user_id") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val userConnectionResponse = + UserConnectionResponse.builder() + .id("id") + .connectionId("connection_id") + .connectionStatus("connection_status") + .providerDescription("provider_description") + .providerId("provider_id") + .providerType("provider_type") + .providerUserInfo(JsonValue.from(mapOf())) + .addScope("string") + .userId("user_id") + .build() + + val roundtrippedUserConnectionResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(userConnectionResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedUserConnectionResponse).isEqualTo(userConnectionResponse) + } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/AuthAuthorizeParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/auth/AuthAuthorizeParamsTest.kt similarity index 97% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/AuthAuthorizeParamsTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/auth/AuthAuthorizeParamsTest.kt index 5fc680c..f963980 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/AuthAuthorizeParamsTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/auth/AuthAuthorizeParamsTest.kt @@ -1,11 +1,11 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.auth import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class AuthAuthorizeParamsTest { +internal class AuthAuthorizeParamsTest { @Test fun create() { diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/AuthConfirmUserParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/auth/AuthConfirmUserParamsTest.kt similarity index 61% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/AuthConfirmUserParamsTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/auth/AuthConfirmUserParamsTest.kt index 1b0d1b9..3fd3e42 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/AuthConfirmUserParamsTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/auth/AuthConfirmUserParamsTest.kt @@ -1,11 +1,11 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.auth import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class AuthConfirmUserParamsTest { +internal class AuthConfirmUserParamsTest { @Test fun create() { @@ -30,19 +30,4 @@ class AuthConfirmUserParamsTest { assertThat(body) .isEqualTo(ConfirmUserRequest.builder().flowId("flow_id").userId("user_id").build()) } - - @Test - fun bodyWithoutOptionalFields() { - val params = - AuthConfirmUserParams.builder() - .confirmUserRequest( - ConfirmUserRequest.builder().flowId("flow_id").userId("user_id").build() - ) - .build() - - val body = params._body() - - assertThat(body) - .isEqualTo(ConfirmUserRequest.builder().flowId("flow_id").userId("user_id").build()) - } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/AuthRequestTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/auth/AuthRequestTest.kt similarity index 53% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/AuthRequestTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/auth/AuthRequestTest.kt index 39b533d..f1d8038 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/AuthRequestTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/auth/AuthRequestTest.kt @@ -1,14 +1,16 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.auth +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import dev.arcade.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class AuthRequestTest { +internal class AuthRequestTest { @Test - fun createAuthRequest() { + fun create() { val authRequest = AuthRequest.builder() .authRequirement( @@ -24,7 +26,7 @@ class AuthRequestTest { .userId("user_id") .nextUri("next_uri") .build() - assertThat(authRequest).isNotNull + assertThat(authRequest.authRequirement()) .isEqualTo( AuthRequest.AuthRequirement.builder() @@ -37,4 +39,32 @@ class AuthRequestTest { assertThat(authRequest.userId()).isEqualTo("user_id") assertThat(authRequest.nextUri()).contains("next_uri") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val authRequest = + AuthRequest.builder() + .authRequirement( + AuthRequest.AuthRequirement.builder() + .id("id") + .oauth2( + AuthRequest.AuthRequirement.Oauth2.builder().addScope("string").build() + ) + .providerId("provider_id") + .providerType("provider_type") + .build() + ) + .userId("user_id") + .nextUri("next_uri") + .build() + + val roundtrippedAuthRequest = + jsonMapper.readValue( + jsonMapper.writeValueAsString(authRequest), + jacksonTypeRef(), + ) + + assertThat(roundtrippedAuthRequest).isEqualTo(authRequest) + } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/AuthStatusParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/auth/AuthStatusParamsTest.kt similarity index 57% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/AuthStatusParamsTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/auth/AuthStatusParamsTest.kt index 78c05c7..7b3adb8 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/AuthStatusParamsTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/auth/AuthStatusParamsTest.kt @@ -1,12 +1,12 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.auth import dev.arcade.core.http.QueryParams import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class AuthStatusParamsTest { +internal class AuthStatusParamsTest { @Test fun create() { @@ -16,17 +16,19 @@ class AuthStatusParamsTest { @Test fun queryParams() { val params = AuthStatusParams.builder().id("id").wait(0L).build() - val expected = QueryParams.builder() - expected.put("id", "id") - expected.put("wait", "0") - assertThat(params._queryParams()).isEqualTo(expected.build()) + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo(QueryParams.builder().put("id", "id").put("wait", "0").build()) } @Test fun queryParamsWithoutOptionalFields() { val params = AuthStatusParams.builder().id("id").build() - val expected = QueryParams.builder() - expected.put("id", "id") - assertThat(params._queryParams()).isEqualTo(expected.build()) + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().put("id", "id").build()) } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/auth/ConfirmUserRequestTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/auth/ConfirmUserRequestTest.kt new file mode 100644 index 0000000..be14fe0 --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/auth/ConfirmUserRequestTest.kt @@ -0,0 +1,35 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.auth + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import dev.arcade.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ConfirmUserRequestTest { + + @Test + fun create() { + val confirmUserRequest = + ConfirmUserRequest.builder().flowId("flow_id").userId("user_id").build() + + assertThat(confirmUserRequest.flowId()).isEqualTo("flow_id") + assertThat(confirmUserRequest.userId()).isEqualTo("user_id") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val confirmUserRequest = + ConfirmUserRequest.builder().flowId("flow_id").userId("user_id").build() + + val roundtrippedConfirmUserRequest = + jsonMapper.readValue( + jsonMapper.writeValueAsString(confirmUserRequest), + jacksonTypeRef(), + ) + + assertThat(roundtrippedConfirmUserRequest).isEqualTo(confirmUserRequest) + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/auth/ConfirmUserResponseTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/auth/ConfirmUserResponseTest.kt new file mode 100644 index 0000000..3680f67 --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/auth/ConfirmUserResponseTest.kt @@ -0,0 +1,35 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.auth + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import dev.arcade.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ConfirmUserResponseTest { + + @Test + fun create() { + val confirmUserResponse = + ConfirmUserResponse.builder().authId("auth_id").nextUri("next_uri").build() + + assertThat(confirmUserResponse.authId()).isEqualTo("auth_id") + assertThat(confirmUserResponse.nextUri()).contains("next_uri") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val confirmUserResponse = + ConfirmUserResponse.builder().authId("auth_id").nextUri("next_uri").build() + + val roundtrippedConfirmUserResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(confirmUserResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedConfirmUserResponse).isEqualTo(confirmUserResponse) + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/ChatMessageTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/chat/ChatMessageTest.kt similarity index 54% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/ChatMessageTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/chat/ChatMessageTest.kt index 4382f57..5b9e6b7 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/ChatMessageTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/chat/ChatMessageTest.kt @@ -1,14 +1,17 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.chat +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import dev.arcade.core.jsonMapper +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ChatMessageTest { +internal class ChatMessageTest { @Test - fun createChatMessage() { + fun create() { val chatMessage = ChatMessage.builder() .content("content") @@ -28,12 +31,12 @@ class ChatMessageTest { .build() ) .build() - assertThat(chatMessage).isNotNull + assertThat(chatMessage.content()).isEqualTo("content") assertThat(chatMessage.role()).isEqualTo("role") assertThat(chatMessage.name()).contains("name") assertThat(chatMessage.toolCallId()).contains("tool_call_id") - assertThat(chatMessage.toolCalls().get()) + assertThat(chatMessage.toolCalls().getOrNull()) .containsExactly( ChatMessage.ToolCall.builder() .id("id") @@ -47,4 +50,36 @@ class ChatMessageTest { .build() ) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val chatMessage = + ChatMessage.builder() + .content("content") + .role("role") + .name("name") + .toolCallId("tool_call_id") + .addToolCall( + ChatMessage.ToolCall.builder() + .id("id") + .function( + ChatMessage.ToolCall.Function.builder() + .arguments("arguments") + .name("name") + .build() + ) + .type(ChatMessage.ToolCall.Type.FUNCTION) + .build() + ) + .build() + + val roundtrippedChatMessage = + jsonMapper.readValue( + jsonMapper.writeValueAsString(chatMessage), + jacksonTypeRef(), + ) + + assertThat(roundtrippedChatMessage).isEqualTo(chatMessage) + } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/ChatRequestTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/chat/ChatRequestTest.kt similarity index 62% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/ChatRequestTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/chat/ChatRequestTest.kt index 08c5e40..e59d8f0 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/ChatRequestTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/chat/ChatRequestTest.kt @@ -1,15 +1,18 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.chat +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import dev.arcade.core.JsonValue +import dev.arcade.core.jsonMapper +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ChatRequestTest { +internal class ChatRequestTest { @Test - fun createChatRequest() { + fun create() { val chatRequest = ChatRequest.builder() .frequencyPenalty(0.0) @@ -60,7 +63,7 @@ class ChatRequestTest { .topP(0.0) .user("user") .build() - assertThat(chatRequest).isNotNull + assertThat(chatRequest.frequencyPenalty()).contains(0.0) assertThat(chatRequest.logitBias()) .contains( @@ -70,7 +73,7 @@ class ChatRequestTest { ) assertThat(chatRequest.logprobs()).contains(true) assertThat(chatRequest.maxTokens()).contains(0L) - assertThat(chatRequest.messages().get()) + assertThat(chatRequest.messages().getOrNull()) .containsExactly( ChatMessage.builder() .content("content") @@ -102,7 +105,7 @@ class ChatRequestTest { .build() ) assertThat(chatRequest.seed()).contains(0L) - assertThat(chatRequest.stop().get()).containsExactly("string") + assertThat(chatRequest.stop().getOrNull()).containsExactly("string") assertThat(chatRequest.stream()).contains(true) assertThat(chatRequest.streamOptions()) .contains(ChatRequest.StreamOptions.builder().includeUsage(true).build()) @@ -113,4 +116,67 @@ class ChatRequestTest { assertThat(chatRequest.topP()).contains(0.0) assertThat(chatRequest.user()).contains("user") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val chatRequest = + ChatRequest.builder() + .frequencyPenalty(0.0) + .logitBias( + ChatRequest.LogitBias.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .logprobs(true) + .maxTokens(0L) + .addMessage( + ChatMessage.builder() + .content("content") + .role("role") + .name("name") + .toolCallId("tool_call_id") + .addToolCall( + ChatMessage.ToolCall.builder() + .id("id") + .function( + ChatMessage.ToolCall.Function.builder() + .arguments("arguments") + .name("name") + .build() + ) + .type(ChatMessage.ToolCall.Type.FUNCTION) + .build() + ) + .build() + ) + .model("model") + .n(0L) + .parallelToolCalls(true) + .presencePenalty(0.0) + .responseFormat( + ChatRequest.ResponseFormat.builder() + .type(ChatRequest.ResponseFormat.Type.JSON_OBJECT) + .build() + ) + .seed(0L) + .addStop("string") + .stream(true) + .streamOptions(ChatRequest.StreamOptions.builder().includeUsage(true).build()) + .temperature(0.0) + .toolChoice(JsonValue.from(mapOf())) + .tools(JsonValue.from(mapOf())) + .topLogprobs(0L) + .topP(0.0) + .user("user") + .build() + + val roundtrippedChatRequest = + jsonMapper.readValue( + jsonMapper.writeValueAsString(chatRequest), + jacksonTypeRef(), + ) + + assertThat(roundtrippedChatRequest).isEqualTo(chatRequest) + } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/ChatResponseTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/chat/ChatResponseTest.kt similarity index 62% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/ChatResponseTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/chat/ChatResponseTest.kt index 8793757..ce487b0 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/ChatResponseTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/chat/ChatResponseTest.kt @@ -1,15 +1,20 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.chat +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import dev.arcade.core.JsonValue +import dev.arcade.core.jsonMapper +import dev.arcade.models.AuthorizationContext +import dev.arcade.models.AuthorizationResponse +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ChatResponseTest { +internal class ChatResponseTest { @Test - fun createChatResponse() { + fun create() { val chatResponse = ChatResponse.builder() .id("id") @@ -88,9 +93,9 @@ class ChatResponseTest { Usage.builder().completionTokens(0L).promptTokens(0L).totalTokens(0L).build() ) .build() - assertThat(chatResponse).isNotNull + assertThat(chatResponse.id()).contains("id") - assertThat(chatResponse.choices().get()) + assertThat(chatResponse.choices().getOrNull()) .containsExactly( Choice.builder() .finishReason("finish_reason") @@ -165,4 +170,95 @@ class ChatResponseTest { assertThat(chatResponse.usage()) .contains(Usage.builder().completionTokens(0L).promptTokens(0L).totalTokens(0L).build()) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val chatResponse = + ChatResponse.builder() + .id("id") + .addChoice( + Choice.builder() + .finishReason("finish_reason") + .index(0L) + .logprobs(JsonValue.from(mapOf())) + .message( + ChatMessage.builder() + .content("content") + .role("role") + .name("name") + .toolCallId("tool_call_id") + .addToolCall( + ChatMessage.ToolCall.builder() + .id("id") + .function( + ChatMessage.ToolCall.Function.builder() + .arguments("arguments") + .name("name") + .build() + ) + .type(ChatMessage.ToolCall.Type.FUNCTION) + .build() + ) + .build() + ) + .addToolAuthorization( + AuthorizationResponse.builder() + .id("id") + .context( + AuthorizationContext.builder() + .token("token") + .userInfo( + AuthorizationContext.UserInfo.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .providerId("provider_id") + .addScope("string") + .status(AuthorizationResponse.Status.NOT_STARTED) + .url("url") + .userId("user_id") + .build() + ) + .addToolMessage( + ChatMessage.builder() + .content("content") + .role("role") + .name("name") + .toolCallId("tool_call_id") + .addToolCall( + ChatMessage.ToolCall.builder() + .id("id") + .function( + ChatMessage.ToolCall.Function.builder() + .arguments("arguments") + .name("name") + .build() + ) + .type(ChatMessage.ToolCall.Type.FUNCTION) + .build() + ) + .build() + ) + .build() + ) + .created(0L) + .model("model") + .object_("object") + .systemFingerprint("system_fingerprint") + .usage( + Usage.builder().completionTokens(0L).promptTokens(0L).totalTokens(0L).build() + ) + .build() + + val roundtrippedChatResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(chatResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedChatResponse).isEqualTo(chatResponse) + } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/ChoiceTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/chat/ChoiceTest.kt similarity index 61% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/ChoiceTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/chat/ChoiceTest.kt index 851e28f..e9cf487 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/ChoiceTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/chat/ChoiceTest.kt @@ -1,15 +1,20 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.chat +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import dev.arcade.core.JsonValue +import dev.arcade.core.jsonMapper +import dev.arcade.models.AuthorizationContext +import dev.arcade.models.AuthorizationResponse +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ChoiceTest { +internal class ChoiceTest { @Test - fun createChoice() { + fun create() { val choice = Choice.builder() .finishReason("finish_reason") @@ -76,7 +81,7 @@ class ChoiceTest { .build() ) .build() - assertThat(choice).isNotNull + assertThat(choice.finishReason()).contains("finish_reason") assertThat(choice.index()).contains(0L) assertThat(choice._logprobs()).isEqualTo(JsonValue.from(mapOf())) @@ -101,7 +106,7 @@ class ChoiceTest { ) .build() ) - assertThat(choice.toolAuthorizations().get()) + assertThat(choice.toolAuthorizations().getOrNull()) .containsExactly( AuthorizationResponse.builder() .id("id") @@ -122,7 +127,7 @@ class ChoiceTest { .userId("user_id") .build() ) - assertThat(choice.toolMessages().get()) + assertThat(choice.toolMessages().getOrNull()) .containsExactly( ChatMessage.builder() .content("content") @@ -144,4 +149,80 @@ class ChoiceTest { .build() ) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val choice = + Choice.builder() + .finishReason("finish_reason") + .index(0L) + .logprobs(JsonValue.from(mapOf())) + .message( + ChatMessage.builder() + .content("content") + .role("role") + .name("name") + .toolCallId("tool_call_id") + .addToolCall( + ChatMessage.ToolCall.builder() + .id("id") + .function( + ChatMessage.ToolCall.Function.builder() + .arguments("arguments") + .name("name") + .build() + ) + .type(ChatMessage.ToolCall.Type.FUNCTION) + .build() + ) + .build() + ) + .addToolAuthorization( + AuthorizationResponse.builder() + .id("id") + .context( + AuthorizationContext.builder() + .token("token") + .userInfo( + AuthorizationContext.UserInfo.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .providerId("provider_id") + .addScope("string") + .status(AuthorizationResponse.Status.NOT_STARTED) + .url("url") + .userId("user_id") + .build() + ) + .addToolMessage( + ChatMessage.builder() + .content("content") + .role("role") + .name("name") + .toolCallId("tool_call_id") + .addToolCall( + ChatMessage.ToolCall.builder() + .id("id") + .function( + ChatMessage.ToolCall.Function.builder() + .arguments("arguments") + .name("name") + .build() + ) + .type(ChatMessage.ToolCall.Type.FUNCTION) + .build() + ) + .build() + ) + .build() + + val roundtrippedChoice = + jsonMapper.readValue(jsonMapper.writeValueAsString(choice), jacksonTypeRef()) + + assertThat(roundtrippedChoice).isEqualTo(choice) + } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/chat/UsageTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/chat/UsageTest.kt new file mode 100644 index 0000000..b66d66d --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/chat/UsageTest.kt @@ -0,0 +1,31 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.chat + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import dev.arcade.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class UsageTest { + + @Test + fun create() { + val usage = Usage.builder().completionTokens(0L).promptTokens(0L).totalTokens(0L).build() + + assertThat(usage.completionTokens()).contains(0L) + assertThat(usage.promptTokens()).contains(0L) + assertThat(usage.totalTokens()).contains(0L) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val usage = Usage.builder().completionTokens(0L).promptTokens(0L).totalTokens(0L).build() + + val roundtrippedUsage = + jsonMapper.readValue(jsonMapper.writeValueAsString(usage), jacksonTypeRef()) + + assertThat(roundtrippedUsage).isEqualTo(usage) + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/ChatCompletionCreateParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/chat/completions/CompletionCreateParamsTest.kt similarity index 95% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/ChatCompletionCreateParamsTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/chat/completions/CompletionCreateParamsTest.kt index 4b220d0..512d26d 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/ChatCompletionCreateParamsTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/chat/completions/CompletionCreateParamsTest.kt @@ -1,16 +1,18 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.chat.completions import dev.arcade.core.JsonValue +import dev.arcade.models.chat.ChatMessage +import dev.arcade.models.chat.ChatRequest import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ChatCompletionCreateParamsTest { +internal class CompletionCreateParamsTest { @Test fun create() { - ChatCompletionCreateParams.builder() + CompletionCreateParams.builder() .chatRequest( ChatRequest.builder() .frequencyPenalty(0.0) @@ -68,7 +70,7 @@ class ChatCompletionCreateParamsTest { @Test fun body() { val params = - ChatCompletionCreateParams.builder() + CompletionCreateParams.builder() .chatRequest( ChatRequest.builder() .frequencyPenalty(0.0) @@ -183,7 +185,7 @@ class ChatCompletionCreateParamsTest { @Test fun bodyWithoutOptionalFields() { val params = - ChatCompletionCreateParams.builder().chatRequest(ChatRequest.builder().build()).build() + CompletionCreateParams.builder().chatRequest(ChatRequest.builder().build()).build() val body = params._body() diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/HealthCheckParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/health/HealthCheckParamsTest.kt similarity index 70% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/HealthCheckParamsTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/health/HealthCheckParamsTest.kt index ecdb70c..f39e720 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/HealthCheckParamsTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/health/HealthCheckParamsTest.kt @@ -1,10 +1,10 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.health import org.junit.jupiter.api.Test -class HealthCheckParamsTest { +internal class HealthCheckParamsTest { @Test fun create() { diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/health/HealthSchemaTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/health/HealthSchemaTest.kt new file mode 100644 index 0000000..dac534f --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/health/HealthSchemaTest.kt @@ -0,0 +1,33 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.health + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import dev.arcade.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class HealthSchemaTest { + + @Test + fun create() { + val healthSchema = HealthSchema.builder().healthy(true).reason("reason").build() + + assertThat(healthSchema.healthy()).contains(true) + assertThat(healthSchema.reason()).contains("reason") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val healthSchema = HealthSchema.builder().healthy(true).reason("reason").build() + + val roundtrippedHealthSchema = + jsonMapper.readValue( + jsonMapper.writeValueAsString(healthSchema), + jacksonTypeRef(), + ) + + assertThat(roundtrippedHealthSchema).isEqualTo(healthSchema) + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/AuthorizeToolRequestTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/AuthorizeToolRequestTest.kt new file mode 100644 index 0000000..baf3b1b --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/AuthorizeToolRequestTest.kt @@ -0,0 +1,47 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.tools + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import dev.arcade.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class AuthorizeToolRequestTest { + + @Test + fun create() { + val authorizeToolRequest = + AuthorizeToolRequest.builder() + .toolName("tool_name") + .nextUri("next_uri") + .toolVersion("tool_version") + .userId("user_id") + .build() + + assertThat(authorizeToolRequest.toolName()).isEqualTo("tool_name") + assertThat(authorizeToolRequest.nextUri()).contains("next_uri") + assertThat(authorizeToolRequest.toolVersion()).contains("tool_version") + assertThat(authorizeToolRequest.userId()).contains("user_id") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val authorizeToolRequest = + AuthorizeToolRequest.builder() + .toolName("tool_name") + .nextUri("next_uri") + .toolVersion("tool_version") + .userId("user_id") + .build() + + val roundtrippedAuthorizeToolRequest = + jsonMapper.readValue( + jsonMapper.writeValueAsString(authorizeToolRequest), + jacksonTypeRef(), + ) + + assertThat(roundtrippedAuthorizeToolRequest).isEqualTo(authorizeToolRequest) + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/ExecuteToolRequestTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ExecuteToolRequestTest.kt similarity index 55% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/ExecuteToolRequestTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ExecuteToolRequestTest.kt index 5323408..0ea4139 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/ExecuteToolRequestTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ExecuteToolRequestTest.kt @@ -1,15 +1,17 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.tools +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import dev.arcade.core.JsonValue +import dev.arcade.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ExecuteToolRequestTest { +internal class ExecuteToolRequestTest { @Test - fun createExecuteToolRequest() { + fun create() { val executeToolRequest = ExecuteToolRequest.builder() .toolName("tool_name") @@ -23,7 +25,7 @@ class ExecuteToolRequestTest { .toolVersion("tool_version") .userId("user_id") .build() - assertThat(executeToolRequest).isNotNull + assertThat(executeToolRequest.toolName()).isEqualTo("tool_name") assertThat(executeToolRequest.includeErrorStacktrace()).contains(true) assertThat(executeToolRequest.input()) @@ -36,4 +38,30 @@ class ExecuteToolRequestTest { assertThat(executeToolRequest.toolVersion()).contains("tool_version") assertThat(executeToolRequest.userId()).contains("user_id") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val executeToolRequest = + ExecuteToolRequest.builder() + .toolName("tool_name") + .includeErrorStacktrace(true) + .input( + ExecuteToolRequest.Input.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .runAt("run_at") + .toolVersion("tool_version") + .userId("user_id") + .build() + + val roundtrippedExecuteToolRequest = + jsonMapper.readValue( + jsonMapper.writeValueAsString(executeToolRequest), + jacksonTypeRef(), + ) + + assertThat(roundtrippedExecuteToolRequest).isEqualTo(executeToolRequest) + } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/ExecuteToolResponseTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ExecuteToolResponseTest.kt similarity index 62% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/ExecuteToolResponseTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ExecuteToolResponseTest.kt index 9affb02..2756625 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/ExecuteToolResponseTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ExecuteToolResponseTest.kt @@ -1,15 +1,19 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.tools +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import dev.arcade.core.JsonValue +import dev.arcade.core.jsonMapper +import dev.arcade.models.AuthorizationContext +import dev.arcade.models.AuthorizationResponse import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ExecuteToolResponseTest { +internal class ExecuteToolResponseTest { @Test - fun createExecuteToolResponse() { + fun create() { val executeToolResponse = ExecuteToolResponse.builder() .id("id") @@ -70,7 +74,7 @@ class ExecuteToolResponseTest { .status("status") .success(true) .build() - assertThat(executeToolResponse).isNotNull + assertThat(executeToolResponse.id()).contains("id") assertThat(executeToolResponse.duration()).contains(0.0) assertThat(executeToolResponse.executionId()).contains("execution_id") @@ -130,4 +134,77 @@ class ExecuteToolResponseTest { assertThat(executeToolResponse.status()).contains("status") assertThat(executeToolResponse.success()).contains(true) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val executeToolResponse = + ExecuteToolResponse.builder() + .id("id") + .duration(0.0) + .executionId("execution_id") + .executionType("execution_type") + .finishedAt("finished_at") + .output( + ExecuteToolResponse.Output.builder() + .authorization( + AuthorizationResponse.builder() + .id("id") + .context( + AuthorizationContext.builder() + .token("token") + .userInfo( + AuthorizationContext.UserInfo.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .providerId("provider_id") + .addScope("string") + .status(AuthorizationResponse.Status.NOT_STARTED) + .url("url") + .userId("user_id") + .build() + ) + .error( + ExecuteToolResponse.Output.Error.builder() + .canRetry(true) + .kind(ExecuteToolResponse.Output.Error.Kind.TOOLKIT_LOAD_FAILED) + .message("message") + .additionalPromptContent("additional_prompt_content") + .developerMessage("developer_message") + .extra( + ExecuteToolResponse.Output.Error.Extra.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .retryAfterMs(0L) + .stacktrace("stacktrace") + .statusCode(0L) + .build() + ) + .addLog( + ExecuteToolResponse.Output.Log.builder() + .level("level") + .message("message") + .subtype("subtype") + .build() + ) + .value(JsonValue.from(mapOf())) + .build() + ) + .runAt("run_at") + .status("status") + .success(true) + .build() + + val roundtrippedExecuteToolResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(executeToolResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedExecuteToolResponse).isEqualTo(executeToolResponse) + } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolAuthorizeParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ToolAuthorizeParamsTest.kt similarity index 95% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/ToolAuthorizeParamsTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ToolAuthorizeParamsTest.kt index 30245c5..12d944e 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolAuthorizeParamsTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ToolAuthorizeParamsTest.kt @@ -1,11 +1,11 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.tools import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ToolAuthorizeParamsTest { +internal class ToolAuthorizeParamsTest { @Test fun create() { diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolDefinitionTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ToolDefinitionTest.kt similarity index 50% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/ToolDefinitionTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ToolDefinitionTest.kt index 21a93f1..7d7a237 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolDefinitionTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ToolDefinitionTest.kt @@ -1,15 +1,17 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.tools +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import dev.arcade.core.JsonValue +import dev.arcade.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ToolDefinitionTest { +internal class ToolDefinitionTest { @Test - fun createToolDefinition() { + fun create() { val toolDefinition = ToolDefinition.builder() .fullyQualifiedName("fully_qualified_name") @@ -47,6 +49,29 @@ class ToolDefinitionTest { .putAdditionalProperty("foo", JsonValue.from("bar")) .build() ) + .metadata( + ToolDefinition.Metadata.builder() + .behavior( + ToolDefinition.Metadata.Behavior.builder() + .destructive(true) + .idempotent(true) + .openWorld(true) + .addOperation("string") + .readOnly(true) + .build() + ) + .classification( + ToolDefinition.Metadata.Classification.builder() + .addServiceDomain("string") + .build() + ) + .extras( + ToolDefinition.Metadata.Extras.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) .output( ToolDefinition.Output.builder() .addAvailableMode("string") @@ -91,7 +116,7 @@ class ToolDefinitionTest { .build() ) .build() - assertThat(toolDefinition).isNotNull + assertThat(toolDefinition.fullyQualifiedName()).isEqualTo("fully_qualified_name") assertThat(toolDefinition.input()) .isEqualTo( @@ -130,6 +155,30 @@ class ToolDefinitionTest { .putAdditionalProperty("foo", JsonValue.from("bar")) .build() ) + assertThat(toolDefinition.metadata()) + .contains( + ToolDefinition.Metadata.builder() + .behavior( + ToolDefinition.Metadata.Behavior.builder() + .destructive(true) + .idempotent(true) + .openWorld(true) + .addOperation("string") + .readOnly(true) + .build() + ) + .classification( + ToolDefinition.Metadata.Classification.builder() + .addServiceDomain("string") + .build() + ) + .extras( + ToolDefinition.Metadata.Extras.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) assertThat(toolDefinition.output()) .contains( ToolDefinition.Output.builder() @@ -175,4 +224,121 @@ class ToolDefinitionTest { .build() ) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val toolDefinition = + ToolDefinition.builder() + .fullyQualifiedName("fully_qualified_name") + .input( + ToolDefinition.Input.builder() + .addParameter( + ToolDefinition.Input.Parameter.builder() + .name("name") + .valueSchema( + ValueSchema.builder() + .valType("val_type") + .addEnum("string") + .innerValType("inner_val_type") + .build() + ) + .description("description") + .inferrable(true) + .required(true) + .build() + ) + .build() + ) + .name("name") + .qualifiedName("qualified_name") + .toolkit( + ToolDefinition.Toolkit.builder() + .name("name") + .description("description") + .version("version") + .build() + ) + .description("description") + .formattedSchema( + ToolDefinition.FormattedSchema.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .metadata( + ToolDefinition.Metadata.builder() + .behavior( + ToolDefinition.Metadata.Behavior.builder() + .destructive(true) + .idempotent(true) + .openWorld(true) + .addOperation("string") + .readOnly(true) + .build() + ) + .classification( + ToolDefinition.Metadata.Classification.builder() + .addServiceDomain("string") + .build() + ) + .extras( + ToolDefinition.Metadata.Extras.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .output( + ToolDefinition.Output.builder() + .addAvailableMode("string") + .description("description") + .valueSchema( + ValueSchema.builder() + .valType("val_type") + .addEnum("string") + .innerValType("inner_val_type") + .build() + ) + .build() + ) + .requirements( + ToolDefinition.Requirements.builder() + .authorization( + ToolDefinition.Requirements.Authorization.builder() + .id("id") + .oauth2( + ToolDefinition.Requirements.Authorization.Oauth2.builder() + .addScope("string") + .build() + ) + .providerId("provider_id") + .providerType("provider_type") + .status(ToolDefinition.Requirements.Authorization.Status.ACTIVE) + .statusReason("status_reason") + .tokenStatus( + ToolDefinition.Requirements.Authorization.TokenStatus + .NOT_STARTED + ) + .build() + ) + .met(true) + .addSecret( + ToolDefinition.Requirements.Secret.builder() + .key("key") + .met(true) + .statusReason("status_reason") + .build() + ) + .build() + ) + .build() + + val roundtrippedToolDefinition = + jsonMapper.readValue( + jsonMapper.writeValueAsString(toolDefinition), + jacksonTypeRef(), + ) + + assertThat(roundtrippedToolDefinition).isEqualTo(toolDefinition) + } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolExecuteParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ToolExecuteParamsTest.kt similarity index 97% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/ToolExecuteParamsTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ToolExecuteParamsTest.kt index bb6a80e..6552558 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolExecuteParamsTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ToolExecuteParamsTest.kt @@ -1,12 +1,12 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.tools import dev.arcade.core.JsonValue import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ToolExecuteParamsTest { +internal class ToolExecuteParamsTest { @Test fun create() { diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolExecutionAttemptTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ToolExecutionAttemptTest.kt similarity index 62% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/ToolExecutionAttemptTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ToolExecutionAttemptTest.kt index f19e4f4..bb9d4c5 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolExecutionAttemptTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ToolExecutionAttemptTest.kt @@ -1,15 +1,19 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.tools +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import dev.arcade.core.JsonValue +import dev.arcade.core.jsonMapper +import dev.arcade.models.AuthorizationContext +import dev.arcade.models.AuthorizationResponse import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ToolExecutionAttemptTest { +internal class ToolExecutionAttemptTest { @Test - fun createToolExecutionAttempt() { + fun create() { val toolExecutionAttempt = ToolExecutionAttempt.builder() .id("id") @@ -67,7 +71,7 @@ class ToolExecutionAttemptTest { .success(true) .systemErrorMessage("system_error_message") .build() - assertThat(toolExecutionAttempt).isNotNull + assertThat(toolExecutionAttempt.id()).contains("id") assertThat(toolExecutionAttempt.finishedAt()).contains("finished_at") assertThat(toolExecutionAttempt.output()) @@ -124,4 +128,74 @@ class ToolExecutionAttemptTest { assertThat(toolExecutionAttempt.success()).contains(true) assertThat(toolExecutionAttempt.systemErrorMessage()).contains("system_error_message") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val toolExecutionAttempt = + ToolExecutionAttempt.builder() + .id("id") + .finishedAt("finished_at") + .output( + ToolExecutionAttempt.Output.builder() + .authorization( + AuthorizationResponse.builder() + .id("id") + .context( + AuthorizationContext.builder() + .token("token") + .userInfo( + AuthorizationContext.UserInfo.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .providerId("provider_id") + .addScope("string") + .status(AuthorizationResponse.Status.NOT_STARTED) + .url("url") + .userId("user_id") + .build() + ) + .error( + ToolExecutionAttempt.Output.Error.builder() + .canRetry(true) + .kind(ToolExecutionAttempt.Output.Error.Kind.TOOLKIT_LOAD_FAILED) + .message("message") + .additionalPromptContent("additional_prompt_content") + .developerMessage("developer_message") + .extra( + ToolExecutionAttempt.Output.Error.Extra.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .retryAfterMs(0L) + .stacktrace("stacktrace") + .statusCode(0L) + .build() + ) + .addLog( + ToolExecutionAttempt.Output.Log.builder() + .level("level") + .message("message") + .subtype("subtype") + .build() + ) + .value(JsonValue.from(mapOf())) + .build() + ) + .startedAt("started_at") + .success(true) + .systemErrorMessage("system_error_message") + .build() + + val roundtrippedToolExecutionAttempt = + jsonMapper.readValue( + jsonMapper.writeValueAsString(toolExecutionAttempt), + jacksonTypeRef(), + ) + + assertThat(roundtrippedToolExecutionAttempt).isEqualTo(toolExecutionAttempt) + } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolExecutionTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ToolExecutionTest.kt similarity index 58% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/ToolExecutionTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ToolExecutionTest.kt index e7e1d9c..3c0a587 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolExecutionTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ToolExecutionTest.kt @@ -1,14 +1,16 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.tools +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import dev.arcade.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ToolExecutionTest { +internal class ToolExecutionTest { @Test - fun createToolExecution() { + fun create() { val toolExecution = ToolExecution.builder() .id("id") @@ -24,7 +26,7 @@ class ToolExecutionTest { .updatedAt("updated_at") .userId("user_id") .build() - assertThat(toolExecution).isNotNull + assertThat(toolExecution.id()).contains("id") assertThat(toolExecution.createdAt()).contains("created_at") assertThat(toolExecution.executionStatus()).contains("execution_status") @@ -38,4 +40,32 @@ class ToolExecutionTest { assertThat(toolExecution.updatedAt()).contains("updated_at") assertThat(toolExecution.userId()).contains("user_id") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val toolExecution = + ToolExecution.builder() + .id("id") + .createdAt("created_at") + .executionStatus("execution_status") + .executionType("execution_type") + .finishedAt("finished_at") + .runAt("run_at") + .startedAt("started_at") + .toolName("tool_name") + .toolkitName("toolkit_name") + .toolkitVersion("toolkit_version") + .updatedAt("updated_at") + .userId("user_id") + .build() + + val roundtrippedToolExecution = + jsonMapper.readValue( + jsonMapper.writeValueAsString(toolExecution), + jacksonTypeRef(), + ) + + assertThat(roundtrippedToolExecution).isEqualTo(toolExecution) + } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolGetParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ToolGetParamsTest.kt similarity index 58% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/ToolGetParamsTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ToolGetParamsTest.kt index 04f7986..8d9cd30 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolGetParamsTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ToolGetParamsTest.kt @@ -1,12 +1,12 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.tools import dev.arcade.core.http.QueryParams import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ToolGetParamsTest { +internal class ToolGetParamsTest { @Test fun create() { @@ -17,6 +17,15 @@ class ToolGetParamsTest { .build() } + @Test + fun pathParams() { + val params = ToolGetParams.builder().name("name").build() + + assertThat(params._pathParam(0)).isEqualTo("name") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun queryParams() { val params = @@ -25,26 +34,24 @@ class ToolGetParamsTest { .addIncludeFormat(ToolGetParams.IncludeFormat.ARCADE) .userId("user_id") .build() - val expected = QueryParams.builder() - expected.put("include_format", ToolGetParams.IncludeFormat.ARCADE.toString()) - expected.put("user_id", "user_id") - assertThat(params._queryParams()).isEqualTo(expected.build()) + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("include_format", listOf("arcade").joinToString(",")) + .put("user_id", "user_id") + .build() + ) } @Test fun queryParamsWithoutOptionalFields() { val params = ToolGetParams.builder().name("name").build() - val expected = QueryParams.builder() - assertThat(params._queryParams()).isEqualTo(expected.build()) - } - @Test - fun getPathParam() { - val params = ToolGetParams.builder().name("name").build() - assertThat(params).isNotNull - // path param "name" - assertThat(params.getPathParam(0)).isEqualTo("name") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ToolListPageResponseTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ToolListPageResponseTest.kt new file mode 100644 index 0000000..426c0bd --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ToolListPageResponseTest.kt @@ -0,0 +1,371 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.tools + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import dev.arcade.core.JsonValue +import dev.arcade.core.jsonMapper +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ToolListPageResponseTest { + + @Test + fun create() { + val toolListPageResponse = + ToolListPageResponse.builder() + .addItem( + ToolDefinition.builder() + .fullyQualifiedName("fully_qualified_name") + .input( + ToolDefinition.Input.builder() + .addParameter( + ToolDefinition.Input.Parameter.builder() + .name("name") + .valueSchema( + ValueSchema.builder() + .valType("val_type") + .addEnum("string") + .innerValType("inner_val_type") + .build() + ) + .description("description") + .inferrable(true) + .required(true) + .build() + ) + .build() + ) + .name("name") + .qualifiedName("qualified_name") + .toolkit( + ToolDefinition.Toolkit.builder() + .name("name") + .description("description") + .version("version") + .build() + ) + .description("description") + .formattedSchema( + ToolDefinition.FormattedSchema.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .metadata( + ToolDefinition.Metadata.builder() + .behavior( + ToolDefinition.Metadata.Behavior.builder() + .destructive(true) + .idempotent(true) + .openWorld(true) + .addOperation("string") + .readOnly(true) + .build() + ) + .classification( + ToolDefinition.Metadata.Classification.builder() + .addServiceDomain("string") + .build() + ) + .extras( + ToolDefinition.Metadata.Extras.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .output( + ToolDefinition.Output.builder() + .addAvailableMode("string") + .description("description") + .valueSchema( + ValueSchema.builder() + .valType("val_type") + .addEnum("string") + .innerValType("inner_val_type") + .build() + ) + .build() + ) + .requirements( + ToolDefinition.Requirements.builder() + .authorization( + ToolDefinition.Requirements.Authorization.builder() + .id("id") + .oauth2( + ToolDefinition.Requirements.Authorization.Oauth2 + .builder() + .addScope("string") + .build() + ) + .providerId("provider_id") + .providerType("provider_type") + .status( + ToolDefinition.Requirements.Authorization.Status.ACTIVE + ) + .statusReason("status_reason") + .tokenStatus( + ToolDefinition.Requirements.Authorization.TokenStatus + .NOT_STARTED + ) + .build() + ) + .met(true) + .addSecret( + ToolDefinition.Requirements.Secret.builder() + .key("key") + .met(true) + .statusReason("status_reason") + .build() + ) + .build() + ) + .build() + ) + .limit(0L) + .offset(0L) + .pageCount(0L) + .totalCount(0L) + .build() + + assertThat(toolListPageResponse.items().getOrNull()) + .containsExactly( + ToolDefinition.builder() + .fullyQualifiedName("fully_qualified_name") + .input( + ToolDefinition.Input.builder() + .addParameter( + ToolDefinition.Input.Parameter.builder() + .name("name") + .valueSchema( + ValueSchema.builder() + .valType("val_type") + .addEnum("string") + .innerValType("inner_val_type") + .build() + ) + .description("description") + .inferrable(true) + .required(true) + .build() + ) + .build() + ) + .name("name") + .qualifiedName("qualified_name") + .toolkit( + ToolDefinition.Toolkit.builder() + .name("name") + .description("description") + .version("version") + .build() + ) + .description("description") + .formattedSchema( + ToolDefinition.FormattedSchema.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .metadata( + ToolDefinition.Metadata.builder() + .behavior( + ToolDefinition.Metadata.Behavior.builder() + .destructive(true) + .idempotent(true) + .openWorld(true) + .addOperation("string") + .readOnly(true) + .build() + ) + .classification( + ToolDefinition.Metadata.Classification.builder() + .addServiceDomain("string") + .build() + ) + .extras( + ToolDefinition.Metadata.Extras.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .output( + ToolDefinition.Output.builder() + .addAvailableMode("string") + .description("description") + .valueSchema( + ValueSchema.builder() + .valType("val_type") + .addEnum("string") + .innerValType("inner_val_type") + .build() + ) + .build() + ) + .requirements( + ToolDefinition.Requirements.builder() + .authorization( + ToolDefinition.Requirements.Authorization.builder() + .id("id") + .oauth2( + ToolDefinition.Requirements.Authorization.Oauth2.builder() + .addScope("string") + .build() + ) + .providerId("provider_id") + .providerType("provider_type") + .status(ToolDefinition.Requirements.Authorization.Status.ACTIVE) + .statusReason("status_reason") + .tokenStatus( + ToolDefinition.Requirements.Authorization.TokenStatus + .NOT_STARTED + ) + .build() + ) + .met(true) + .addSecret( + ToolDefinition.Requirements.Secret.builder() + .key("key") + .met(true) + .statusReason("status_reason") + .build() + ) + .build() + ) + .build() + ) + assertThat(toolListPageResponse.limit()).contains(0L) + assertThat(toolListPageResponse.offset()).contains(0L) + assertThat(toolListPageResponse.pageCount()).contains(0L) + assertThat(toolListPageResponse.totalCount()).contains(0L) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val toolListPageResponse = + ToolListPageResponse.builder() + .addItem( + ToolDefinition.builder() + .fullyQualifiedName("fully_qualified_name") + .input( + ToolDefinition.Input.builder() + .addParameter( + ToolDefinition.Input.Parameter.builder() + .name("name") + .valueSchema( + ValueSchema.builder() + .valType("val_type") + .addEnum("string") + .innerValType("inner_val_type") + .build() + ) + .description("description") + .inferrable(true) + .required(true) + .build() + ) + .build() + ) + .name("name") + .qualifiedName("qualified_name") + .toolkit( + ToolDefinition.Toolkit.builder() + .name("name") + .description("description") + .version("version") + .build() + ) + .description("description") + .formattedSchema( + ToolDefinition.FormattedSchema.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .metadata( + ToolDefinition.Metadata.builder() + .behavior( + ToolDefinition.Metadata.Behavior.builder() + .destructive(true) + .idempotent(true) + .openWorld(true) + .addOperation("string") + .readOnly(true) + .build() + ) + .classification( + ToolDefinition.Metadata.Classification.builder() + .addServiceDomain("string") + .build() + ) + .extras( + ToolDefinition.Metadata.Extras.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .output( + ToolDefinition.Output.builder() + .addAvailableMode("string") + .description("description") + .valueSchema( + ValueSchema.builder() + .valType("val_type") + .addEnum("string") + .innerValType("inner_val_type") + .build() + ) + .build() + ) + .requirements( + ToolDefinition.Requirements.builder() + .authorization( + ToolDefinition.Requirements.Authorization.builder() + .id("id") + .oauth2( + ToolDefinition.Requirements.Authorization.Oauth2 + .builder() + .addScope("string") + .build() + ) + .providerId("provider_id") + .providerType("provider_type") + .status( + ToolDefinition.Requirements.Authorization.Status.ACTIVE + ) + .statusReason("status_reason") + .tokenStatus( + ToolDefinition.Requirements.Authorization.TokenStatus + .NOT_STARTED + ) + .build() + ) + .met(true) + .addSecret( + ToolDefinition.Requirements.Secret.builder() + .key("key") + .met(true) + .statusReason("status_reason") + .build() + ) + .build() + ) + .build() + ) + .limit(0L) + .offset(0L) + .pageCount(0L) + .totalCount(0L) + .build() + + val roundtrippedToolListPageResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(toolListPageResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedToolListPageResponse).isEqualTo(toolListPageResponse) + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolListParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ToolListParamsTest.kt similarity index 58% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/ToolListParamsTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ToolListParamsTest.kt index 122a1c9..2c07652 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolListParamsTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ToolListParamsTest.kt @@ -1,12 +1,12 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.tools import dev.arcade.core.http.QueryParams import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ToolListParamsTest { +internal class ToolListParamsTest { @Test fun create() { @@ -31,20 +31,28 @@ class ToolListParamsTest { .toolkit("toolkit") .userId("user_id") .build() - val expected = QueryParams.builder() - expected.put("include_all_versions", "true") - expected.put("include_format", ToolListParams.IncludeFormat.ARCADE.toString()) - expected.put("limit", "0") - expected.put("offset", "0") - expected.put("toolkit", "toolkit") - expected.put("user_id", "user_id") - assertThat(params._queryParams()).isEqualTo(expected.build()) + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("include_all_versions", "true") + .put("include_format", listOf("arcade").joinToString(",")) + .put("limit", "0") + .put("offset", "0") + .put("toolkit", "toolkit") + .put("user_id", "user_id") + .build() + ) } @Test fun queryParamsWithoutOptionalFields() { val params = ToolListParams.builder().build() - val expected = QueryParams.builder() - assertThat(params._queryParams()).isEqualTo(expected.build()) + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ValueSchemaTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ValueSchemaTest.kt new file mode 100644 index 0000000..4d28e8a --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/ValueSchemaTest.kt @@ -0,0 +1,45 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.tools + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import dev.arcade.core.jsonMapper +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ValueSchemaTest { + + @Test + fun create() { + val valueSchema = + ValueSchema.builder() + .valType("val_type") + .addEnum("string") + .innerValType("inner_val_type") + .build() + + assertThat(valueSchema.valType()).isEqualTo("val_type") + assertThat(valueSchema.enum_().getOrNull()).containsExactly("string") + assertThat(valueSchema.innerValType()).contains("inner_val_type") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val valueSchema = + ValueSchema.builder() + .valType("val_type") + .addEnum("string") + .innerValType("inner_val_type") + .build() + + val roundtrippedValueSchema = + jsonMapper.readValue( + jsonMapper.writeValueAsString(valueSchema), + jacksonTypeRef(), + ) + + assertThat(roundtrippedValueSchema).isEqualTo(valueSchema) + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/formatted/FormattedGetParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/formatted/FormattedGetParamsTest.kt new file mode 100644 index 0000000..70c28ba --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/formatted/FormattedGetParamsTest.kt @@ -0,0 +1,46 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.tools.formatted + +import dev.arcade.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FormattedGetParamsTest { + + @Test + fun create() { + FormattedGetParams.builder().name("name").format("format").userId("user_id").build() + } + + @Test + fun pathParams() { + val params = FormattedGetParams.builder().name("name").build() + + assertThat(params._pathParam(0)).isEqualTo("name") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + + @Test + fun queryParams() { + val params = + FormattedGetParams.builder().name("name").format("format").userId("user_id").build() + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder().put("format", "format").put("user_id", "user_id").build() + ) + } + + @Test + fun queryParamsWithoutOptionalFields() { + val params = FormattedGetParams.builder().name("name").build() + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/formatted/FormattedGetResponseTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/formatted/FormattedGetResponseTest.kt new file mode 100644 index 0000000..d5d77d8 --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/formatted/FormattedGetResponseTest.kt @@ -0,0 +1,37 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.tools.formatted + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import dev.arcade.core.JsonValue +import dev.arcade.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FormattedGetResponseTest { + + @Test + fun create() { + val formattedGetResponse = + FormattedGetResponse.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val formattedGetResponse = + FormattedGetResponse.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + + val roundtrippedFormattedGetResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(formattedGetResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedFormattedGetResponse).isEqualTo(formattedGetResponse) + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/formatted/FormattedListPageResponseTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/formatted/FormattedListPageResponseTest.kt new file mode 100644 index 0000000..5b0505c --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/formatted/FormattedListPageResponseTest.kt @@ -0,0 +1,65 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.tools.formatted + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import dev.arcade.core.JsonValue +import dev.arcade.core.jsonMapper +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FormattedListPageResponseTest { + + @Test + fun create() { + val formattedListPageResponse = + FormattedListPageResponse.builder() + .addItem( + FormattedListResponse.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .limit(0L) + .offset(0L) + .pageCount(0L) + .totalCount(0L) + .build() + + assertThat(formattedListPageResponse.items().getOrNull()) + .containsExactly( + FormattedListResponse.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + assertThat(formattedListPageResponse.limit()).contains(0L) + assertThat(formattedListPageResponse.offset()).contains(0L) + assertThat(formattedListPageResponse.pageCount()).contains(0L) + assertThat(formattedListPageResponse.totalCount()).contains(0L) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val formattedListPageResponse = + FormattedListPageResponse.builder() + .addItem( + FormattedListResponse.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .limit(0L) + .offset(0L) + .pageCount(0L) + .totalCount(0L) + .build() + + val roundtrippedFormattedListPageResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(formattedListPageResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedFormattedListPageResponse).isEqualTo(formattedListPageResponse) + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/formatted/FormattedListParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/formatted/FormattedListParamsTest.kt new file mode 100644 index 0000000..48d2dad --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/formatted/FormattedListParamsTest.kt @@ -0,0 +1,58 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.tools.formatted + +import dev.arcade.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FormattedListParamsTest { + + @Test + fun create() { + FormattedListParams.builder() + .format("format") + .includeAllVersions(true) + .limit(0L) + .offset(0L) + .toolkit("toolkit") + .userId("user_id") + .build() + } + + @Test + fun queryParams() { + val params = + FormattedListParams.builder() + .format("format") + .includeAllVersions(true) + .limit(0L) + .offset(0L) + .toolkit("toolkit") + .userId("user_id") + .build() + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("format", "format") + .put("include_all_versions", "true") + .put("limit", "0") + .put("offset", "0") + .put("toolkit", "toolkit") + .put("user_id", "user_id") + .build() + ) + } + + @Test + fun queryParamsWithoutOptionalFields() { + val params = FormattedListParams.builder().build() + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/formatted/FormattedListResponseTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/formatted/FormattedListResponseTest.kt new file mode 100644 index 0000000..0d8e2f2 --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/formatted/FormattedListResponseTest.kt @@ -0,0 +1,37 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.tools.formatted + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import dev.arcade.core.JsonValue +import dev.arcade.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FormattedListResponseTest { + + @Test + fun create() { + val formattedListResponse = + FormattedListResponse.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val formattedListResponse = + FormattedListResponse.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + + val roundtrippedFormattedListResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(formattedListResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedFormattedListResponse).isEqualTo(formattedListResponse) + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/scheduled/ScheduledGetParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/scheduled/ScheduledGetParamsTest.kt new file mode 100644 index 0000000..de5bbd6 --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/scheduled/ScheduledGetParamsTest.kt @@ -0,0 +1,23 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.tools.scheduled + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ScheduledGetParamsTest { + + @Test + fun create() { + ScheduledGetParams.builder().id("id").build() + } + + @Test + fun pathParams() { + val params = ScheduledGetParams.builder().id("id").build() + + assertThat(params._pathParam(0)).isEqualTo("id") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolScheduledGetResponseTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/scheduled/ScheduledGetResponseTest.kt similarity index 55% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/ToolScheduledGetResponseTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/tools/scheduled/ScheduledGetResponseTest.kt index a5235e9..02abac8 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/ToolScheduledGetResponseTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/scheduled/ScheduledGetResponseTest.kt @@ -1,17 +1,23 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.tools.scheduled +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import dev.arcade.core.JsonValue +import dev.arcade.core.jsonMapper +import dev.arcade.models.AuthorizationContext +import dev.arcade.models.AuthorizationResponse +import dev.arcade.models.tools.ToolExecutionAttempt +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ToolScheduledGetResponseTest { +internal class ScheduledGetResponseTest { @Test - fun createToolScheduledGetResponse() { - val toolScheduledGetResponse = - ToolScheduledGetResponse.builder() + fun create() { + val scheduledGetResponse = + ScheduledGetResponse.builder() .id("id") .addAttempt( ToolExecutionAttempt.builder() @@ -82,7 +88,7 @@ class ToolScheduledGetResponseTest { .executionType("execution_type") .finishedAt("finished_at") .input( - ToolScheduledGetResponse.Input.builder() + ScheduledGetResponse.Input.builder() .putAdditionalProperty("foo", JsonValue.from("bar")) .build() ) @@ -94,9 +100,9 @@ class ToolScheduledGetResponseTest { .updatedAt("updated_at") .userId("user_id") .build() - assertThat(toolScheduledGetResponse).isNotNull - assertThat(toolScheduledGetResponse.id()).contains("id") - assertThat(toolScheduledGetResponse.attempts().get()) + + assertThat(scheduledGetResponse.id()).contains("id") + assertThat(scheduledGetResponse.attempts().getOrNull()) .containsExactly( ToolExecutionAttempt.builder() .id("id") @@ -160,22 +166,119 @@ class ToolScheduledGetResponseTest { .systemErrorMessage("system_error_message") .build() ) - assertThat(toolScheduledGetResponse.createdAt()).contains("created_at") - assertThat(toolScheduledGetResponse.executionStatus()).contains("execution_status") - assertThat(toolScheduledGetResponse.executionType()).contains("execution_type") - assertThat(toolScheduledGetResponse.finishedAt()).contains("finished_at") - assertThat(toolScheduledGetResponse.input()) + assertThat(scheduledGetResponse.createdAt()).contains("created_at") + assertThat(scheduledGetResponse.executionStatus()).contains("execution_status") + assertThat(scheduledGetResponse.executionType()).contains("execution_type") + assertThat(scheduledGetResponse.finishedAt()).contains("finished_at") + assertThat(scheduledGetResponse.input()) .contains( - ToolScheduledGetResponse.Input.builder() + ScheduledGetResponse.Input.builder() .putAdditionalProperty("foo", JsonValue.from("bar")) .build() ) - assertThat(toolScheduledGetResponse.runAt()).contains("run_at") - assertThat(toolScheduledGetResponse.startedAt()).contains("started_at") - assertThat(toolScheduledGetResponse.toolName()).contains("tool_name") - assertThat(toolScheduledGetResponse.toolkitName()).contains("toolkit_name") - assertThat(toolScheduledGetResponse.toolkitVersion()).contains("toolkit_version") - assertThat(toolScheduledGetResponse.updatedAt()).contains("updated_at") - assertThat(toolScheduledGetResponse.userId()).contains("user_id") + assertThat(scheduledGetResponse.runAt()).contains("run_at") + assertThat(scheduledGetResponse.startedAt()).contains("started_at") + assertThat(scheduledGetResponse.toolName()).contains("tool_name") + assertThat(scheduledGetResponse.toolkitName()).contains("toolkit_name") + assertThat(scheduledGetResponse.toolkitVersion()).contains("toolkit_version") + assertThat(scheduledGetResponse.updatedAt()).contains("updated_at") + assertThat(scheduledGetResponse.userId()).contains("user_id") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val scheduledGetResponse = + ScheduledGetResponse.builder() + .id("id") + .addAttempt( + ToolExecutionAttempt.builder() + .id("id") + .finishedAt("finished_at") + .output( + ToolExecutionAttempt.Output.builder() + .authorization( + AuthorizationResponse.builder() + .id("id") + .context( + AuthorizationContext.builder() + .token("token") + .userInfo( + AuthorizationContext.UserInfo.builder() + .putAdditionalProperty( + "foo", + JsonValue.from("bar"), + ) + .build() + ) + .build() + ) + .providerId("provider_id") + .addScope("string") + .status(AuthorizationResponse.Status.NOT_STARTED) + .url("url") + .userId("user_id") + .build() + ) + .error( + ToolExecutionAttempt.Output.Error.builder() + .canRetry(true) + .kind( + ToolExecutionAttempt.Output.Error.Kind + .TOOLKIT_LOAD_FAILED + ) + .message("message") + .additionalPromptContent("additional_prompt_content") + .developerMessage("developer_message") + .extra( + ToolExecutionAttempt.Output.Error.Extra.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .retryAfterMs(0L) + .stacktrace("stacktrace") + .statusCode(0L) + .build() + ) + .addLog( + ToolExecutionAttempt.Output.Log.builder() + .level("level") + .message("message") + .subtype("subtype") + .build() + ) + .value(JsonValue.from(mapOf())) + .build() + ) + .startedAt("started_at") + .success(true) + .systemErrorMessage("system_error_message") + .build() + ) + .createdAt("created_at") + .executionStatus("execution_status") + .executionType("execution_type") + .finishedAt("finished_at") + .input( + ScheduledGetResponse.Input.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .runAt("run_at") + .startedAt("started_at") + .toolName("tool_name") + .toolkitName("toolkit_name") + .toolkitVersion("toolkit_version") + .updatedAt("updated_at") + .userId("user_id") + .build() + + val roundtrippedScheduledGetResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(scheduledGetResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedScheduledGetResponse).isEqualTo(scheduledGetResponse) } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/scheduled/ScheduledListPageResponseTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/scheduled/ScheduledListPageResponseTest.kt new file mode 100644 index 0000000..3dfddf5 --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/scheduled/ScheduledListPageResponseTest.kt @@ -0,0 +1,98 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.tools.scheduled + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import dev.arcade.core.jsonMapper +import dev.arcade.models.tools.ToolExecution +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ScheduledListPageResponseTest { + + @Test + fun create() { + val scheduledListPageResponse = + ScheduledListPageResponse.builder() + .addItem( + ToolExecution.builder() + .id("id") + .createdAt("created_at") + .executionStatus("execution_status") + .executionType("execution_type") + .finishedAt("finished_at") + .runAt("run_at") + .startedAt("started_at") + .toolName("tool_name") + .toolkitName("toolkit_name") + .toolkitVersion("toolkit_version") + .updatedAt("updated_at") + .userId("user_id") + .build() + ) + .limit(0L) + .offset(0L) + .pageCount(0L) + .totalCount(0L) + .build() + + assertThat(scheduledListPageResponse.items().getOrNull()) + .containsExactly( + ToolExecution.builder() + .id("id") + .createdAt("created_at") + .executionStatus("execution_status") + .executionType("execution_type") + .finishedAt("finished_at") + .runAt("run_at") + .startedAt("started_at") + .toolName("tool_name") + .toolkitName("toolkit_name") + .toolkitVersion("toolkit_version") + .updatedAt("updated_at") + .userId("user_id") + .build() + ) + assertThat(scheduledListPageResponse.limit()).contains(0L) + assertThat(scheduledListPageResponse.offset()).contains(0L) + assertThat(scheduledListPageResponse.pageCount()).contains(0L) + assertThat(scheduledListPageResponse.totalCount()).contains(0L) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val scheduledListPageResponse = + ScheduledListPageResponse.builder() + .addItem( + ToolExecution.builder() + .id("id") + .createdAt("created_at") + .executionStatus("execution_status") + .executionType("execution_type") + .finishedAt("finished_at") + .runAt("run_at") + .startedAt("started_at") + .toolName("tool_name") + .toolkitName("toolkit_name") + .toolkitVersion("toolkit_version") + .updatedAt("updated_at") + .userId("user_id") + .build() + ) + .limit(0L) + .offset(0L) + .pageCount(0L) + .totalCount(0L) + .build() + + val roundtrippedScheduledListPageResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(scheduledListPageResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedScheduledListPageResponse).isEqualTo(scheduledListPageResponse) + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/scheduled/ScheduledListParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/scheduled/ScheduledListParamsTest.kt new file mode 100644 index 0000000..babe532 --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/tools/scheduled/ScheduledListParamsTest.kt @@ -0,0 +1,34 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.tools.scheduled + +import dev.arcade.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ScheduledListParamsTest { + + @Test + fun create() { + ScheduledListParams.builder().limit(0L).offset(0L).build() + } + + @Test + fun queryParams() { + val params = ScheduledListParams.builder().limit(0L).offset(0L).build() + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo(QueryParams.builder().put("limit", "0").put("offset", "0").build()) + } + + @Test + fun queryParamsWithoutOptionalFields() { + val params = ScheduledListParams.builder().build() + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/CreateWorkerRequestTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/CreateWorkerRequestTest.kt similarity index 60% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/CreateWorkerRequestTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/workers/CreateWorkerRequestTest.kt index 7199721..6e044d4 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/CreateWorkerRequestTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/CreateWorkerRequestTest.kt @@ -1,15 +1,17 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.workers +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import dev.arcade.core.JsonValue +import dev.arcade.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class CreateWorkerRequestTest { +internal class CreateWorkerRequestTest { @Test - fun createCreateWorkerRequest() { + fun create() { val createWorkerRequest = CreateWorkerRequest.builder() .id("id") @@ -49,7 +51,7 @@ class CreateWorkerRequestTest { ) .type("type") .build() - assertThat(createWorkerRequest).isNotNull + assertThat(createWorkerRequest.id()).isEqualTo("id") assertThat(createWorkerRequest.enabled()).contains(true) assertThat(createWorkerRequest.http()) @@ -89,4 +91,56 @@ class CreateWorkerRequestTest { ) assertThat(createWorkerRequest.type()).contains("type") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val createWorkerRequest = + CreateWorkerRequest.builder() + .id("id") + .enabled(true) + .http( + CreateWorkerRequest.Http.builder() + .retry(0L) + .secret("secret") + .timeout(1L) + .uri("uri") + .build() + ) + .mcp( + CreateWorkerRequest.Mcp.builder() + .retry(0L) + .timeout(1L) + .uri("uri") + .headers( + CreateWorkerRequest.Mcp.Headers.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .oauth2( + CreateWorkerRequest.Mcp.Oauth2.builder() + .authorizationUrl("authorization_url") + .clientId("client_id") + .clientSecret("client_secret") + .externalId("external_id") + .build() + ) + .secrets( + CreateWorkerRequest.Mcp.Secrets.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .build() + ) + .type("type") + .build() + + val roundtrippedCreateWorkerRequest = + jsonMapper.readValue( + jsonMapper.writeValueAsString(createWorkerRequest), + jacksonTypeRef(), + ) + + assertThat(roundtrippedCreateWorkerRequest).isEqualTo(createWorkerRequest) + } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/UpdateWorkerRequestTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/UpdateWorkerRequestTest.kt similarity index 60% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/UpdateWorkerRequestTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/workers/UpdateWorkerRequestTest.kt index 26fbd74..bc82aeb 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/UpdateWorkerRequestTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/UpdateWorkerRequestTest.kt @@ -1,15 +1,17 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.workers +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import dev.arcade.core.JsonValue +import dev.arcade.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class UpdateWorkerRequestTest { +internal class UpdateWorkerRequestTest { @Test - fun createUpdateWorkerRequest() { + fun create() { val updateWorkerRequest = UpdateWorkerRequest.builder() .enabled(true) @@ -46,7 +48,7 @@ class UpdateWorkerRequestTest { .build() ) .build() - assertThat(updateWorkerRequest).isNotNull + assertThat(updateWorkerRequest.enabled()).contains(true) assertThat(updateWorkerRequest.http()) .contains( @@ -83,4 +85,53 @@ class UpdateWorkerRequestTest { .build() ) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val updateWorkerRequest = + UpdateWorkerRequest.builder() + .enabled(true) + .http( + UpdateWorkerRequest.Http.builder() + .retry(0L) + .secret("secret") + .timeout(1L) + .uri("uri") + .build() + ) + .mcp( + UpdateWorkerRequest.Mcp.builder() + .headers( + UpdateWorkerRequest.Mcp.Headers.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .oauth2( + UpdateWorkerRequest.Mcp.Oauth2.builder() + .authorizationUrl("authorization_url") + .clientId("client_id") + .clientSecret("client_secret") + .build() + ) + .retry(0L) + .secrets( + UpdateWorkerRequest.Mcp.Secrets.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .timeout(1L) + .uri("uri") + .build() + ) + .build() + + val roundtrippedUpdateWorkerRequest = + jsonMapper.readValue( + jsonMapper.writeValueAsString(updateWorkerRequest), + jacksonTypeRef(), + ) + + assertThat(roundtrippedUpdateWorkerRequest).isEqualTo(updateWorkerRequest) + } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/WorkerCreateParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerCreateParamsTest.kt similarity index 98% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/WorkerCreateParamsTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerCreateParamsTest.kt index caf4d39..adf0677 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/WorkerCreateParamsTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerCreateParamsTest.kt @@ -1,12 +1,12 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.workers import dev.arcade.core.JsonValue import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class WorkerCreateParamsTest { +internal class WorkerCreateParamsTest { @Test fun create() { diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/WorkerDeleteParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerDeleteParamsTest.kt similarity index 57% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/WorkerDeleteParamsTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerDeleteParamsTest.kt index 73a2282..c38a2d2 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/WorkerDeleteParamsTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerDeleteParamsTest.kt @@ -1,11 +1,11 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.workers import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class WorkerDeleteParamsTest { +internal class WorkerDeleteParamsTest { @Test fun create() { @@ -13,12 +13,11 @@ class WorkerDeleteParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = WorkerDeleteParams.builder().id("id").build() - assertThat(params).isNotNull - // path param "id" - assertThat(params.getPathParam(0)).isEqualTo("id") + + assertThat(params._pathParam(0)).isEqualTo("id") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/WorkerGetParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerGetParamsTest.kt similarity index 57% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/WorkerGetParamsTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerGetParamsTest.kt index 3ad4415..a415ad3 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/WorkerGetParamsTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerGetParamsTest.kt @@ -1,11 +1,11 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.workers import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class WorkerGetParamsTest { +internal class WorkerGetParamsTest { @Test fun create() { @@ -13,12 +13,11 @@ class WorkerGetParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = WorkerGetParams.builder().id("id").build() - assertThat(params).isNotNull - // path param "id" - assertThat(params.getPathParam(0)).isEqualTo("id") + + assertThat(params._pathParam(0)).isEqualTo("id") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/WorkerHealthParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerHealthParamsTest.kt similarity index 57% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/WorkerHealthParamsTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerHealthParamsTest.kt index 3428467..2767f07 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/WorkerHealthParamsTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerHealthParamsTest.kt @@ -1,11 +1,11 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.workers import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class WorkerHealthParamsTest { +internal class WorkerHealthParamsTest { @Test fun create() { @@ -13,12 +13,11 @@ class WorkerHealthParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = WorkerHealthParams.builder().id("id").build() - assertThat(params).isNotNull - // path param "id" - assertThat(params.getPathParam(0)).isEqualTo("id") + + assertThat(params._pathParam(0)).isEqualTo("id") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerHealthResponseTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerHealthResponseTest.kt new file mode 100644 index 0000000..921ae2f --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerHealthResponseTest.kt @@ -0,0 +1,47 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.workers + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import dev.arcade.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class WorkerHealthResponseTest { + + @Test + fun create() { + val workerHealthResponse = + WorkerHealthResponse.builder() + .id("id") + .enabled(true) + .healthy(true) + .message("message") + .build() + + assertThat(workerHealthResponse.id()).contains("id") + assertThat(workerHealthResponse.enabled()).contains(true) + assertThat(workerHealthResponse.healthy()).contains(true) + assertThat(workerHealthResponse.message()).contains("message") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val workerHealthResponse = + WorkerHealthResponse.builder() + .id("id") + .enabled(true) + .healthy(true) + .message("message") + .build() + + val roundtrippedWorkerHealthResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(workerHealthResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedWorkerHealthResponse).isEqualTo(workerHealthResponse) + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerListPageResponseTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerListPageResponseTest.kt new file mode 100644 index 0000000..bfe4dee --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerListPageResponseTest.kt @@ -0,0 +1,325 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.workers + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import dev.arcade.core.JsonValue +import dev.arcade.core.jsonMapper +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class WorkerListPageResponseTest { + + @Test + fun create() { + val workerListPageResponse = + WorkerListPageResponse.builder() + .addItem( + WorkerResponse.builder() + .id("id") + .binding( + WorkerResponse.Binding.builder() + .id("id") + .type(WorkerResponse.Binding.Type.STATIC) + .build() + ) + .enabled(true) + .http( + WorkerResponse.Http.builder() + .retry(0L) + .secret( + WorkerResponse.Http.Secret.builder() + .binding(WorkerResponse.Http.Secret.Binding.STATIC) + .editable(true) + .exists(true) + .value("value") + .build() + ) + .timeout(0L) + .uri("uri") + .build() + ) + .managed(true) + .mcp( + WorkerResponse.Mcp.builder() + .headers( + WorkerResponse.Mcp.Headers.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .oauth2( + WorkerResponse.Mcp.Oauth2.builder() + .authorizationUrl("authorization_url") + .clientId("client_id") + .clientSecret( + WorkerResponse.Mcp.Oauth2.ClientSecret.builder() + .binding( + WorkerResponse.Mcp.Oauth2.ClientSecret.Binding + .STATIC + ) + .editable(true) + .exists(true) + .value("value") + .build() + ) + .externalId("external_id") + .redirectUri("redirect_uri") + .addSupportedScope("string") + .build() + ) + .retry(0L) + .secrets( + WorkerResponse.Mcp.Secrets.builder() + .putAdditionalProperty( + "foo", + JsonValue.from( + mapOf( + "binding" to "static", + "editable" to true, + "exists" to true, + "value" to "value", + ) + ), + ) + .build() + ) + .timeout(0L) + .uri("uri") + .build() + ) + .requirements( + WorkerResponse.Requirements.builder() + .authorization( + WorkerResponse.Requirements.Authorization.builder() + .met(true) + .oauth2( + WorkerResponse.Requirements.Authorization.Oauth2 + .builder() + .met(true) + .build() + ) + .build() + ) + .met(true) + .build() + ) + .type(WorkerResponse.Type.HTTP) + .build() + ) + .limit(0L) + .offset(0L) + .pageCount(0L) + .totalCount(0L) + .build() + + assertThat(workerListPageResponse.items().getOrNull()) + .containsExactly( + WorkerResponse.builder() + .id("id") + .binding( + WorkerResponse.Binding.builder() + .id("id") + .type(WorkerResponse.Binding.Type.STATIC) + .build() + ) + .enabled(true) + .http( + WorkerResponse.Http.builder() + .retry(0L) + .secret( + WorkerResponse.Http.Secret.builder() + .binding(WorkerResponse.Http.Secret.Binding.STATIC) + .editable(true) + .exists(true) + .value("value") + .build() + ) + .timeout(0L) + .uri("uri") + .build() + ) + .managed(true) + .mcp( + WorkerResponse.Mcp.builder() + .headers( + WorkerResponse.Mcp.Headers.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .oauth2( + WorkerResponse.Mcp.Oauth2.builder() + .authorizationUrl("authorization_url") + .clientId("client_id") + .clientSecret( + WorkerResponse.Mcp.Oauth2.ClientSecret.builder() + .binding( + WorkerResponse.Mcp.Oauth2.ClientSecret.Binding + .STATIC + ) + .editable(true) + .exists(true) + .value("value") + .build() + ) + .externalId("external_id") + .redirectUri("redirect_uri") + .addSupportedScope("string") + .build() + ) + .retry(0L) + .secrets( + WorkerResponse.Mcp.Secrets.builder() + .putAdditionalProperty( + "foo", + JsonValue.from( + mapOf( + "binding" to "static", + "editable" to true, + "exists" to true, + "value" to "value", + ) + ), + ) + .build() + ) + .timeout(0L) + .uri("uri") + .build() + ) + .requirements( + WorkerResponse.Requirements.builder() + .authorization( + WorkerResponse.Requirements.Authorization.builder() + .met(true) + .oauth2( + WorkerResponse.Requirements.Authorization.Oauth2.builder() + .met(true) + .build() + ) + .build() + ) + .met(true) + .build() + ) + .type(WorkerResponse.Type.HTTP) + .build() + ) + assertThat(workerListPageResponse.limit()).contains(0L) + assertThat(workerListPageResponse.offset()).contains(0L) + assertThat(workerListPageResponse.pageCount()).contains(0L) + assertThat(workerListPageResponse.totalCount()).contains(0L) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val workerListPageResponse = + WorkerListPageResponse.builder() + .addItem( + WorkerResponse.builder() + .id("id") + .binding( + WorkerResponse.Binding.builder() + .id("id") + .type(WorkerResponse.Binding.Type.STATIC) + .build() + ) + .enabled(true) + .http( + WorkerResponse.Http.builder() + .retry(0L) + .secret( + WorkerResponse.Http.Secret.builder() + .binding(WorkerResponse.Http.Secret.Binding.STATIC) + .editable(true) + .exists(true) + .value("value") + .build() + ) + .timeout(0L) + .uri("uri") + .build() + ) + .managed(true) + .mcp( + WorkerResponse.Mcp.builder() + .headers( + WorkerResponse.Mcp.Headers.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .oauth2( + WorkerResponse.Mcp.Oauth2.builder() + .authorizationUrl("authorization_url") + .clientId("client_id") + .clientSecret( + WorkerResponse.Mcp.Oauth2.ClientSecret.builder() + .binding( + WorkerResponse.Mcp.Oauth2.ClientSecret.Binding + .STATIC + ) + .editable(true) + .exists(true) + .value("value") + .build() + ) + .externalId("external_id") + .redirectUri("redirect_uri") + .addSupportedScope("string") + .build() + ) + .retry(0L) + .secrets( + WorkerResponse.Mcp.Secrets.builder() + .putAdditionalProperty( + "foo", + JsonValue.from( + mapOf( + "binding" to "static", + "editable" to true, + "exists" to true, + "value" to "value", + ) + ), + ) + .build() + ) + .timeout(0L) + .uri("uri") + .build() + ) + .requirements( + WorkerResponse.Requirements.builder() + .authorization( + WorkerResponse.Requirements.Authorization.builder() + .met(true) + .oauth2( + WorkerResponse.Requirements.Authorization.Oauth2 + .builder() + .met(true) + .build() + ) + .build() + ) + .met(true) + .build() + ) + .type(WorkerResponse.Type.HTTP) + .build() + ) + .limit(0L) + .offset(0L) + .pageCount(0L) + .totalCount(0L) + .build() + + val roundtrippedWorkerListPageResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(workerListPageResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedWorkerListPageResponse).isEqualTo(workerListPageResponse) + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/WorkerListParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerListParamsTest.kt similarity index 58% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/WorkerListParamsTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerListParamsTest.kt index e7f4967..5f81e75 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/WorkerListParamsTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerListParamsTest.kt @@ -1,12 +1,12 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.workers import dev.arcade.core.http.QueryParams import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class WorkerListParamsTest { +internal class WorkerListParamsTest { @Test fun create() { @@ -16,16 +16,19 @@ class WorkerListParamsTest { @Test fun queryParams() { val params = WorkerListParams.builder().limit(0L).offset(0L).build() - val expected = QueryParams.builder() - expected.put("limit", "0") - expected.put("offset", "0") - assertThat(params._queryParams()).isEqualTo(expected.build()) + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo(QueryParams.builder().put("limit", "0").put("offset", "0").build()) } @Test fun queryParamsWithoutOptionalFields() { val params = WorkerListParams.builder().build() - val expected = QueryParams.builder() - assertThat(params._queryParams()).isEqualTo(expected.build()) + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/WorkerResponseTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerResponseTest.kt similarity index 61% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/WorkerResponseTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerResponseTest.kt index 7499d1d..c280d01 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/WorkerResponseTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerResponseTest.kt @@ -1,15 +1,17 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.workers +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import dev.arcade.core.JsonValue +import dev.arcade.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class WorkerResponseTest { +internal class WorkerResponseTest { @Test - fun createWorkerResponse() { + fun create() { val workerResponse = WorkerResponse.builder() .id("id") @@ -28,7 +30,6 @@ class WorkerResponseTest { .binding(WorkerResponse.Http.Secret.Binding.STATIC) .editable(true) .exists(true) - .hint("hint") .value("value") .build() ) @@ -55,11 +56,12 @@ class WorkerResponseTest { ) .editable(true) .exists(true) - .hint("hint") .value("value") .build() ) + .externalId("external_id") .redirectUri("redirect_uri") + .addSupportedScope("string") .build() ) .retry(0L) @@ -72,7 +74,6 @@ class WorkerResponseTest { "binding" to "static", "editable" to true, "exists" to true, - "hint" to "hint", "value" to "value", ) ), @@ -100,7 +101,7 @@ class WorkerResponseTest { ) .type(WorkerResponse.Type.HTTP) .build() - assertThat(workerResponse).isNotNull + assertThat(workerResponse.id()).contains("id") assertThat(workerResponse.binding()) .contains( @@ -119,7 +120,6 @@ class WorkerResponseTest { .binding(WorkerResponse.Http.Secret.Binding.STATIC) .editable(true) .exists(true) - .hint("hint") .value("value") .build() ) @@ -145,11 +145,12 @@ class WorkerResponseTest { .binding(WorkerResponse.Mcp.Oauth2.ClientSecret.Binding.STATIC) .editable(true) .exists(true) - .hint("hint") .value("value") .build() ) + .externalId("external_id") .redirectUri("redirect_uri") + .addSupportedScope("string") .build() ) .retry(0L) @@ -162,7 +163,6 @@ class WorkerResponseTest { "binding" to "static", "editable" to true, "exists" to true, - "hint" to "hint", "value" to "value", ) ), @@ -191,4 +191,106 @@ class WorkerResponseTest { ) assertThat(workerResponse.type()).contains(WorkerResponse.Type.HTTP) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val workerResponse = + WorkerResponse.builder() + .id("id") + .binding( + WorkerResponse.Binding.builder() + .id("id") + .type(WorkerResponse.Binding.Type.STATIC) + .build() + ) + .enabled(true) + .http( + WorkerResponse.Http.builder() + .retry(0L) + .secret( + WorkerResponse.Http.Secret.builder() + .binding(WorkerResponse.Http.Secret.Binding.STATIC) + .editable(true) + .exists(true) + .value("value") + .build() + ) + .timeout(0L) + .uri("uri") + .build() + ) + .managed(true) + .mcp( + WorkerResponse.Mcp.builder() + .headers( + WorkerResponse.Mcp.Headers.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .oauth2( + WorkerResponse.Mcp.Oauth2.builder() + .authorizationUrl("authorization_url") + .clientId("client_id") + .clientSecret( + WorkerResponse.Mcp.Oauth2.ClientSecret.builder() + .binding( + WorkerResponse.Mcp.Oauth2.ClientSecret.Binding.STATIC + ) + .editable(true) + .exists(true) + .value("value") + .build() + ) + .externalId("external_id") + .redirectUri("redirect_uri") + .addSupportedScope("string") + .build() + ) + .retry(0L) + .secrets( + WorkerResponse.Mcp.Secrets.builder() + .putAdditionalProperty( + "foo", + JsonValue.from( + mapOf( + "binding" to "static", + "editable" to true, + "exists" to true, + "value" to "value", + ) + ), + ) + .build() + ) + .timeout(0L) + .uri("uri") + .build() + ) + .requirements( + WorkerResponse.Requirements.builder() + .authorization( + WorkerResponse.Requirements.Authorization.builder() + .met(true) + .oauth2( + WorkerResponse.Requirements.Authorization.Oauth2.builder() + .met(true) + .build() + ) + .build() + ) + .met(true) + .build() + ) + .type(WorkerResponse.Type.HTTP) + .build() + + val roundtrippedWorkerResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(workerResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedWorkerResponse).isEqualTo(workerResponse) + } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerToolsPageResponseTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerToolsPageResponseTest.kt new file mode 100644 index 0000000..975e7ba --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerToolsPageResponseTest.kt @@ -0,0 +1,373 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.models.workers + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import dev.arcade.core.JsonValue +import dev.arcade.core.jsonMapper +import dev.arcade.models.tools.ToolDefinition +import dev.arcade.models.tools.ValueSchema +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class WorkerToolsPageResponseTest { + + @Test + fun create() { + val workerToolsPageResponse = + WorkerToolsPageResponse.builder() + .addItem( + ToolDefinition.builder() + .fullyQualifiedName("fully_qualified_name") + .input( + ToolDefinition.Input.builder() + .addParameter( + ToolDefinition.Input.Parameter.builder() + .name("name") + .valueSchema( + ValueSchema.builder() + .valType("val_type") + .addEnum("string") + .innerValType("inner_val_type") + .build() + ) + .description("description") + .inferrable(true) + .required(true) + .build() + ) + .build() + ) + .name("name") + .qualifiedName("qualified_name") + .toolkit( + ToolDefinition.Toolkit.builder() + .name("name") + .description("description") + .version("version") + .build() + ) + .description("description") + .formattedSchema( + ToolDefinition.FormattedSchema.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .metadata( + ToolDefinition.Metadata.builder() + .behavior( + ToolDefinition.Metadata.Behavior.builder() + .destructive(true) + .idempotent(true) + .openWorld(true) + .addOperation("string") + .readOnly(true) + .build() + ) + .classification( + ToolDefinition.Metadata.Classification.builder() + .addServiceDomain("string") + .build() + ) + .extras( + ToolDefinition.Metadata.Extras.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .output( + ToolDefinition.Output.builder() + .addAvailableMode("string") + .description("description") + .valueSchema( + ValueSchema.builder() + .valType("val_type") + .addEnum("string") + .innerValType("inner_val_type") + .build() + ) + .build() + ) + .requirements( + ToolDefinition.Requirements.builder() + .authorization( + ToolDefinition.Requirements.Authorization.builder() + .id("id") + .oauth2( + ToolDefinition.Requirements.Authorization.Oauth2 + .builder() + .addScope("string") + .build() + ) + .providerId("provider_id") + .providerType("provider_type") + .status( + ToolDefinition.Requirements.Authorization.Status.ACTIVE + ) + .statusReason("status_reason") + .tokenStatus( + ToolDefinition.Requirements.Authorization.TokenStatus + .NOT_STARTED + ) + .build() + ) + .met(true) + .addSecret( + ToolDefinition.Requirements.Secret.builder() + .key("key") + .met(true) + .statusReason("status_reason") + .build() + ) + .build() + ) + .build() + ) + .limit(0L) + .offset(0L) + .pageCount(0L) + .totalCount(0L) + .build() + + assertThat(workerToolsPageResponse.items().getOrNull()) + .containsExactly( + ToolDefinition.builder() + .fullyQualifiedName("fully_qualified_name") + .input( + ToolDefinition.Input.builder() + .addParameter( + ToolDefinition.Input.Parameter.builder() + .name("name") + .valueSchema( + ValueSchema.builder() + .valType("val_type") + .addEnum("string") + .innerValType("inner_val_type") + .build() + ) + .description("description") + .inferrable(true) + .required(true) + .build() + ) + .build() + ) + .name("name") + .qualifiedName("qualified_name") + .toolkit( + ToolDefinition.Toolkit.builder() + .name("name") + .description("description") + .version("version") + .build() + ) + .description("description") + .formattedSchema( + ToolDefinition.FormattedSchema.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .metadata( + ToolDefinition.Metadata.builder() + .behavior( + ToolDefinition.Metadata.Behavior.builder() + .destructive(true) + .idempotent(true) + .openWorld(true) + .addOperation("string") + .readOnly(true) + .build() + ) + .classification( + ToolDefinition.Metadata.Classification.builder() + .addServiceDomain("string") + .build() + ) + .extras( + ToolDefinition.Metadata.Extras.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .output( + ToolDefinition.Output.builder() + .addAvailableMode("string") + .description("description") + .valueSchema( + ValueSchema.builder() + .valType("val_type") + .addEnum("string") + .innerValType("inner_val_type") + .build() + ) + .build() + ) + .requirements( + ToolDefinition.Requirements.builder() + .authorization( + ToolDefinition.Requirements.Authorization.builder() + .id("id") + .oauth2( + ToolDefinition.Requirements.Authorization.Oauth2.builder() + .addScope("string") + .build() + ) + .providerId("provider_id") + .providerType("provider_type") + .status(ToolDefinition.Requirements.Authorization.Status.ACTIVE) + .statusReason("status_reason") + .tokenStatus( + ToolDefinition.Requirements.Authorization.TokenStatus + .NOT_STARTED + ) + .build() + ) + .met(true) + .addSecret( + ToolDefinition.Requirements.Secret.builder() + .key("key") + .met(true) + .statusReason("status_reason") + .build() + ) + .build() + ) + .build() + ) + assertThat(workerToolsPageResponse.limit()).contains(0L) + assertThat(workerToolsPageResponse.offset()).contains(0L) + assertThat(workerToolsPageResponse.pageCount()).contains(0L) + assertThat(workerToolsPageResponse.totalCount()).contains(0L) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val workerToolsPageResponse = + WorkerToolsPageResponse.builder() + .addItem( + ToolDefinition.builder() + .fullyQualifiedName("fully_qualified_name") + .input( + ToolDefinition.Input.builder() + .addParameter( + ToolDefinition.Input.Parameter.builder() + .name("name") + .valueSchema( + ValueSchema.builder() + .valType("val_type") + .addEnum("string") + .innerValType("inner_val_type") + .build() + ) + .description("description") + .inferrable(true) + .required(true) + .build() + ) + .build() + ) + .name("name") + .qualifiedName("qualified_name") + .toolkit( + ToolDefinition.Toolkit.builder() + .name("name") + .description("description") + .version("version") + .build() + ) + .description("description") + .formattedSchema( + ToolDefinition.FormattedSchema.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .metadata( + ToolDefinition.Metadata.builder() + .behavior( + ToolDefinition.Metadata.Behavior.builder() + .destructive(true) + .idempotent(true) + .openWorld(true) + .addOperation("string") + .readOnly(true) + .build() + ) + .classification( + ToolDefinition.Metadata.Classification.builder() + .addServiceDomain("string") + .build() + ) + .extras( + ToolDefinition.Metadata.Extras.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .output( + ToolDefinition.Output.builder() + .addAvailableMode("string") + .description("description") + .valueSchema( + ValueSchema.builder() + .valType("val_type") + .addEnum("string") + .innerValType("inner_val_type") + .build() + ) + .build() + ) + .requirements( + ToolDefinition.Requirements.builder() + .authorization( + ToolDefinition.Requirements.Authorization.builder() + .id("id") + .oauth2( + ToolDefinition.Requirements.Authorization.Oauth2 + .builder() + .addScope("string") + .build() + ) + .providerId("provider_id") + .providerType("provider_type") + .status( + ToolDefinition.Requirements.Authorization.Status.ACTIVE + ) + .statusReason("status_reason") + .tokenStatus( + ToolDefinition.Requirements.Authorization.TokenStatus + .NOT_STARTED + ) + .build() + ) + .met(true) + .addSecret( + ToolDefinition.Requirements.Secret.builder() + .key("key") + .met(true) + .statusReason("status_reason") + .build() + ) + .build() + ) + .build() + ) + .limit(0L) + .offset(0L) + .pageCount(0L) + .totalCount(0L) + .build() + + val roundtrippedWorkerToolsPageResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(workerToolsPageResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedWorkerToolsPageResponse).isEqualTo(workerToolsPageResponse) + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/WorkerToolsParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerToolsParamsTest.kt similarity index 54% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/WorkerToolsParamsTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerToolsParamsTest.kt index 8fb9ea8..71f16a2 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/WorkerToolsParamsTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerToolsParamsTest.kt @@ -1,41 +1,43 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.workers import dev.arcade.core.http.QueryParams import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class WorkerToolsParamsTest { +internal class WorkerToolsParamsTest { @Test fun create() { WorkerToolsParams.builder().id("id").limit(0L).offset(0L).build() } + @Test + fun pathParams() { + val params = WorkerToolsParams.builder().id("id").build() + + assertThat(params._pathParam(0)).isEqualTo("id") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun queryParams() { val params = WorkerToolsParams.builder().id("id").limit(0L).offset(0L).build() - val expected = QueryParams.builder() - expected.put("limit", "0") - expected.put("offset", "0") - assertThat(params._queryParams()).isEqualTo(expected.build()) + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo(QueryParams.builder().put("limit", "0").put("offset", "0").build()) } @Test fun queryParamsWithoutOptionalFields() { val params = WorkerToolsParams.builder().id("id").build() - val expected = QueryParams.builder() - assertThat(params._queryParams()).isEqualTo(expected.build()) - } - @Test - fun getPathParam() { - val params = WorkerToolsParams.builder().id("id").build() - assertThat(params).isNotNull - // path param "id" - assertThat(params.getPathParam(0)).isEqualTo("id") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/models/WorkerUpdateParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerUpdateParamsTest.kt similarity index 95% rename from arcade-java-core/src/test/kotlin/dev/arcade/models/WorkerUpdateParamsTest.kt rename to arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerUpdateParamsTest.kt index 1fadd4f..85f9e6b 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/models/WorkerUpdateParamsTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/models/workers/WorkerUpdateParamsTest.kt @@ -1,12 +1,12 @@ // File generated from our OpenAPI spec by Stainless. -package dev.arcade.models +package dev.arcade.models.workers import dev.arcade.core.JsonValue import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class WorkerUpdateParamsTest { +internal class WorkerUpdateParamsTest { @Test fun create() { @@ -52,6 +52,19 @@ class WorkerUpdateParamsTest { .build() } + @Test + fun pathParams() { + val params = + WorkerUpdateParams.builder() + .id("id") + .updateWorkerRequest(UpdateWorkerRequest.builder().build()) + .build() + + assertThat(params._pathParam(0)).isEqualTo("id") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -150,18 +163,4 @@ class WorkerUpdateParamsTest { assertThat(body).isEqualTo(UpdateWorkerRequest.builder().build()) } - - @Test - fun getPathParam() { - val params = - WorkerUpdateParams.builder() - .id("id") - .updateWorkerRequest(UpdateWorkerRequest.builder().build()) - .build() - assertThat(params).isNotNull - // path param "id" - assertThat(params.getPathParam(0)).isEqualTo("id") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") - } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/services/ErrorHandlingTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/services/ErrorHandlingTest.kt index 99f3039..77356bd 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/services/ErrorHandlingTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/services/ErrorHandlingTest.kt @@ -2,9 +2,7 @@ package dev.arcade.services -import com.fasterxml.jackson.databind.json.JsonMapper import com.github.tomakehurst.wiremock.client.WireMock.anyUrl -import com.github.tomakehurst.wiremock.client.WireMock.ok import com.github.tomakehurst.wiremock.client.WireMock.post import com.github.tomakehurst.wiremock.client.WireMock.status import com.github.tomakehurst.wiremock.client.WireMock.stubFor @@ -15,7 +13,6 @@ import dev.arcade.client.okhttp.ArcadeOkHttpClient import dev.arcade.core.JsonValue import dev.arcade.core.http.Headers import dev.arcade.core.jsonMapper -import dev.arcade.errors.ArcadeError import dev.arcade.errors.ArcadeException import dev.arcade.errors.BadRequestException import dev.arcade.errors.InternalServerException @@ -25,27 +22,31 @@ import dev.arcade.errors.RateLimitException import dev.arcade.errors.UnauthorizedException import dev.arcade.errors.UnexpectedStatusCodeException import dev.arcade.errors.UnprocessableEntityException -import dev.arcade.models.AuthorizationContext -import dev.arcade.models.AuthorizationResponse -import dev.arcade.models.ChatCompletionCreateParams -import dev.arcade.models.ChatMessage -import dev.arcade.models.ChatRequest -import dev.arcade.models.ChatResponse -import dev.arcade.models.Choice -import dev.arcade.models.Usage +import dev.arcade.models.chat.ChatMessage +import dev.arcade.models.chat.ChatRequest import org.assertj.core.api.Assertions.assertThat -import org.assertj.core.api.Assertions.assertThatThrownBy -import org.assertj.core.api.InstanceOfAssertFactories +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 -class ErrorHandlingTest { +@ResourceLock("https://github.com/wiremock/wiremock/issues/169") +internal class ErrorHandlingTest { - private val JSON_MAPPER: JsonMapper = jsonMapper() + companion object { - private val ARCADE_ERROR: ArcadeError = - ArcadeError.builder().putAdditionalProperty("key", JsonValue.from("value")).build() + 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: ArcadeClient @@ -53,16 +54,24 @@ class ErrorHandlingTest { fun beforeEach(wmRuntimeInfo: WireMockRuntimeInfo) { client = ArcadeOkHttpClient.builder() - .baseUrl(wmRuntimeInfo.getHttpBaseUrl()) + .baseUrl(wmRuntimeInfo.httpBaseUrl) .apiKey("My API Key") .build() } @Test - fun completionsCreate200() { - val params = - ChatCompletionCreateParams.builder() - .chatRequest( + fun completionsCreate400() { + val completionService = client.chat().completions() + stubFor( + post(anyUrl()) + .willReturn( + status(400).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) + + val e = + assertThrows { + completionService.create( ChatRequest.builder() .frequencyPenalty(0.0) .logitBias( @@ -115,17 +124,36 @@ class ErrorHandlingTest { .user("user") .build() ) - .build() + } + + assertThat(e.statusCode()).isEqualTo(400) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) + } - val expected = - ChatResponse.builder() - .id("id") - .addChoice( - Choice.builder() - .finishReason("finish_reason") - .index(0L) - .logprobs(JsonValue.from(mapOf())) - .message( + @Test + fun completionsCreate400WithRawResponse() { + val completionService = client.chat().completions().withRawResponse() + stubFor( + post(anyUrl()) + .willReturn( + status(400).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) + + val e = + assertThrows { + completionService.create( + ChatRequest.builder() + .frequencyPenalty(0.0) + .logitBias( + ChatRequest.LogitBias.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .logprobs(true) + .maxTokens(0L) + .addMessage( ChatMessage.builder() .content("content") .role("role") @@ -145,27 +173,59 @@ class ErrorHandlingTest { ) .build() ) - .addToolAuthorization( - AuthorizationResponse.builder() - .id("id") - .context( - AuthorizationContext.builder() - .token("token") - .userInfo( - AuthorizationContext.UserInfo.builder() - .putAdditionalProperty("foo", JsonValue.from("bar")) - .build() - ) - .build() - ) - .providerId("provider_id") - .addScope("string") - .status(AuthorizationResponse.Status.NOT_STARTED) - .url("url") - .userId("user_id") + .model("model") + .n(0L) + .parallelToolCalls(true) + .presencePenalty(0.0) + .responseFormat( + ChatRequest.ResponseFormat.builder() + .type(ChatRequest.ResponseFormat.Type.JSON_OBJECT) .build() ) - .addToolMessage( + .seed(0L) + .addStop("string") + .stream(true) + .streamOptions( + ChatRequest.StreamOptions.builder().includeUsage(true).build() + ) + .temperature(0.0) + .toolChoice(JsonValue.from(mapOf())) + .tools(JsonValue.from(mapOf())) + .topLogprobs(0L) + .topP(0.0) + .user("user") + .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 completionsCreate401() { + val completionService = client.chat().completions() + stubFor( + post(anyUrl()) + .willReturn( + status(401).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) + + val e = + assertThrows { + completionService.create( + ChatRequest.builder() + .frequencyPenalty(0.0) + .logitBias( + ChatRequest.LogitBias.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .logprobs(true) + .maxTokens(0L) + .addMessage( ChatMessage.builder() .content("content") .role("role") @@ -185,27 +245,49 @@ class ErrorHandlingTest { ) .build() ) + .model("model") + .n(0L) + .parallelToolCalls(true) + .presencePenalty(0.0) + .responseFormat( + ChatRequest.ResponseFormat.builder() + .type(ChatRequest.ResponseFormat.Type.JSON_OBJECT) + .build() + ) + .seed(0L) + .addStop("string") + .stream(true) + .streamOptions( + ChatRequest.StreamOptions.builder().includeUsage(true).build() + ) + .temperature(0.0) + .toolChoice(JsonValue.from(mapOf())) + .tools(JsonValue.from(mapOf())) + .topLogprobs(0L) + .topP(0.0) + .user("user") .build() ) - .created(0L) - .model("model") - .object_("object") - .systemFingerprint("system_fingerprint") - .usage( - Usage.builder().completionTokens(0L).promptTokens(0L).totalTokens(0L).build() - ) - .build() - - stubFor(post(anyUrl()).willReturn(ok().withBody(toJson(expected)))) + } - assertThat(client.chat().completions().create(params)).isEqualTo(expected) + assertThat(e.statusCode()).isEqualTo(401) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test - fun completionsCreate400() { - val params = - ChatCompletionCreateParams.builder() - .chatRequest( + fun completionsCreate401WithRawResponse() { + val completionService = client.chat().completions().withRawResponse() + stubFor( + post(anyUrl()) + .willReturn( + status(401).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) + + val e = + assertThrows { + completionService.create( ChatRequest.builder() .frequencyPenalty(0.0) .logitBias( @@ -258,24 +340,26 @@ class ErrorHandlingTest { .user("user") .build() ) - .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 completionsCreate403() { + val completionService = client.chat().completions() stubFor( post(anyUrl()) - .willReturn(status(400).withHeader("Foo", "Bar").withBody(toJson(ARCADE_ERROR))) + .willReturn( + status(403).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) - assertThatThrownBy({ client.chat().completions().create(params) }) - .satisfies({ e -> - assertBadRequest(e, Headers.builder().put("Foo", "Bar").build(), ARCADE_ERROR) - }) - } - - @Test - fun completionsCreate401() { - val params = - ChatCompletionCreateParams.builder() - .chatRequest( + val e = + assertThrows { + completionService.create( ChatRequest.builder() .frequencyPenalty(0.0) .logitBias( @@ -328,24 +412,26 @@ class ErrorHandlingTest { .user("user") .build() ) - .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 completionsCreate403WithRawResponse() { + val completionService = client.chat().completions().withRawResponse() stubFor( post(anyUrl()) - .willReturn(status(401).withHeader("Foo", "Bar").withBody(toJson(ARCADE_ERROR))) + .willReturn( + status(403).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) - assertThatThrownBy({ client.chat().completions().create(params) }) - .satisfies({ e -> - assertUnauthorized(e, Headers.builder().put("Foo", "Bar").build(), ARCADE_ERROR) - }) - } - - @Test - fun completionsCreate403() { - val params = - ChatCompletionCreateParams.builder() - .chatRequest( + val e = + assertThrows { + completionService.create( ChatRequest.builder() .frequencyPenalty(0.0) .logitBias( @@ -398,24 +484,26 @@ class ErrorHandlingTest { .user("user") .build() ) - .build() + } - stubFor( - post(anyUrl()) - .willReturn(status(403).withHeader("Foo", "Bar").withBody(toJson(ARCADE_ERROR))) - ) - - assertThatThrownBy({ client.chat().completions().create(params) }) - .satisfies({ e -> - assertPermissionDenied(e, Headers.builder().put("Foo", "Bar").build(), ARCADE_ERROR) - }) + assertThat(e.statusCode()).isEqualTo(403) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test fun completionsCreate404() { - val params = - ChatCompletionCreateParams.builder() - .chatRequest( + val completionService = client.chat().completions() + stubFor( + post(anyUrl()) + .willReturn( + status(404).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) + + val e = + assertThrows { + completionService.create( ChatRequest.builder() .frequencyPenalty(0.0) .logitBias( @@ -468,24 +556,98 @@ class ErrorHandlingTest { .user("user") .build() ) - .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 completionsCreate404WithRawResponse() { + val completionService = client.chat().completions().withRawResponse() stubFor( post(anyUrl()) - .willReturn(status(404).withHeader("Foo", "Bar").withBody(toJson(ARCADE_ERROR))) + .willReturn( + status(404).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) - assertThatThrownBy({ client.chat().completions().create(params) }) - .satisfies({ e -> - assertNotFound(e, Headers.builder().put("Foo", "Bar").build(), ARCADE_ERROR) - }) + val e = + assertThrows { + completionService.create( + ChatRequest.builder() + .frequencyPenalty(0.0) + .logitBias( + ChatRequest.LogitBias.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .logprobs(true) + .maxTokens(0L) + .addMessage( + ChatMessage.builder() + .content("content") + .role("role") + .name("name") + .toolCallId("tool_call_id") + .addToolCall( + ChatMessage.ToolCall.builder() + .id("id") + .function( + ChatMessage.ToolCall.Function.builder() + .arguments("arguments") + .name("name") + .build() + ) + .type(ChatMessage.ToolCall.Type.FUNCTION) + .build() + ) + .build() + ) + .model("model") + .n(0L) + .parallelToolCalls(true) + .presencePenalty(0.0) + .responseFormat( + ChatRequest.ResponseFormat.builder() + .type(ChatRequest.ResponseFormat.Type.JSON_OBJECT) + .build() + ) + .seed(0L) + .addStop("string") + .stream(true) + .streamOptions( + ChatRequest.StreamOptions.builder().includeUsage(true).build() + ) + .temperature(0.0) + .toolChoice(JsonValue.from(mapOf())) + .tools(JsonValue.from(mapOf())) + .topLogprobs(0L) + .topP(0.0) + .user("user") + .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 completionsCreate422() { - val params = - ChatCompletionCreateParams.builder() - .chatRequest( + val completionService = client.chat().completions() + stubFor( + post(anyUrl()) + .willReturn( + status(422).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) + + val e = + assertThrows { + completionService.create( ChatRequest.builder() .frequencyPenalty(0.0) .logitBias( @@ -538,28 +700,98 @@ class ErrorHandlingTest { .user("user") .build() ) - .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 completionsCreate422WithRawResponse() { + val completionService = client.chat().completions().withRawResponse() stubFor( post(anyUrl()) - .willReturn(status(422).withHeader("Foo", "Bar").withBody(toJson(ARCADE_ERROR))) + .willReturn( + status(422).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) - assertThatThrownBy({ client.chat().completions().create(params) }) - .satisfies({ e -> - assertUnprocessableEntity( - e, - Headers.builder().put("Foo", "Bar").build(), - ARCADE_ERROR, + val e = + assertThrows { + completionService.create( + ChatRequest.builder() + .frequencyPenalty(0.0) + .logitBias( + ChatRequest.LogitBias.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .logprobs(true) + .maxTokens(0L) + .addMessage( + ChatMessage.builder() + .content("content") + .role("role") + .name("name") + .toolCallId("tool_call_id") + .addToolCall( + ChatMessage.ToolCall.builder() + .id("id") + .function( + ChatMessage.ToolCall.Function.builder() + .arguments("arguments") + .name("name") + .build() + ) + .type(ChatMessage.ToolCall.Type.FUNCTION) + .build() + ) + .build() + ) + .model("model") + .n(0L) + .parallelToolCalls(true) + .presencePenalty(0.0) + .responseFormat( + ChatRequest.ResponseFormat.builder() + .type(ChatRequest.ResponseFormat.Type.JSON_OBJECT) + .build() + ) + .seed(0L) + .addStop("string") + .stream(true) + .streamOptions( + ChatRequest.StreamOptions.builder().includeUsage(true).build() + ) + .temperature(0.0) + .toolChoice(JsonValue.from(mapOf())) + .tools(JsonValue.from(mapOf())) + .topLogprobs(0L) + .topP(0.0) + .user("user") + .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 completionsCreate429() { - val params = - ChatCompletionCreateParams.builder() - .chatRequest( + val completionService = client.chat().completions() + stubFor( + post(anyUrl()) + .willReturn( + status(429).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) + + val e = + assertThrows { + completionService.create( ChatRequest.builder() .frequencyPenalty(0.0) .logitBias( @@ -612,24 +844,26 @@ class ErrorHandlingTest { .user("user") .build() ) - .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 completionsCreate429WithRawResponse() { + val completionService = client.chat().completions().withRawResponse() stubFor( post(anyUrl()) - .willReturn(status(429).withHeader("Foo", "Bar").withBody(toJson(ARCADE_ERROR))) + .willReturn( + status(429).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) - assertThatThrownBy({ client.chat().completions().create(params) }) - .satisfies({ e -> - assertRateLimit(e, Headers.builder().put("Foo", "Bar").build(), ARCADE_ERROR) - }) - } - - @Test - fun completionsCreate500() { - val params = - ChatCompletionCreateParams.builder() - .chatRequest( + val e = + assertThrows { + completionService.create( ChatRequest.builder() .frequencyPenalty(0.0) .logitBias( @@ -682,24 +916,26 @@ class ErrorHandlingTest { .user("user") .build() ) - .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 completionsCreate500() { + val completionService = client.chat().completions() stubFor( post(anyUrl()) - .willReturn(status(500).withHeader("Foo", "Bar").withBody(toJson(ARCADE_ERROR))) + .willReturn( + status(500).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) - assertThatThrownBy({ client.chat().completions().create(params) }) - .satisfies({ e -> - assertInternalServer(e, Headers.builder().put("Foo", "Bar").build(), ARCADE_ERROR) - }) - } - - @Test - fun unexpectedStatusCode() { - val params = - ChatCompletionCreateParams.builder() - .chatRequest( + val e = + assertThrows { + completionService.create( ChatRequest.builder() .frequencyPenalty(0.0) .logitBias( @@ -752,29 +988,26 @@ class ErrorHandlingTest { .user("user") .build() ) - .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 completionsCreate500WithRawResponse() { + val completionService = client.chat().completions().withRawResponse() stubFor( post(anyUrl()) - .willReturn(status(999).withHeader("Foo", "Bar").withBody(toJson(ARCADE_ERROR))) - ) - - assertThatThrownBy({ client.chat().completions().create(params) }) - .satisfies({ e -> - assertUnexpectedStatusCodeException( - e, - 999, - Headers.builder().put("Foo", "Bar").build(), - toJson(ARCADE_ERROR), + .willReturn( + status(500).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) ) - }) - } + ) - @Test - fun invalidBody() { - val params = - ChatCompletionCreateParams.builder() - .chatRequest( + val e = + assertThrows { + completionService.create( ChatRequest.builder() .frequencyPenalty(0.0) .logitBias( @@ -827,23 +1060,26 @@ class ErrorHandlingTest { .user("user") .build() ) - .build() - - stubFor(post(anyUrl()).willReturn(status(200).withBody("Not JSON"))) + } - assertThatThrownBy({ client.chat().completions().create(params) }) - .satisfies({ e -> - assertThat(e) - .isInstanceOf(ArcadeException::class.java) - .hasMessage("Error reading response") - }) + assertThat(e.statusCode()).isEqualTo(500) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test - fun invalidErrorBody() { - val params = - ChatCompletionCreateParams.builder() - .chatRequest( + fun completionsCreate999() { + val completionService = client.chat().completions() + stubFor( + post(anyUrl()) + .willReturn( + status(999).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) + + val e = + assertThrows { + completionService.create( ChatRequest.builder() .frequencyPenalty(0.0) .logitBias( @@ -896,113 +1132,151 @@ class ErrorHandlingTest { .user("user") .build() ) - .build() - - stubFor(post(anyUrl()).willReturn(status(400).withBody("Not JSON"))) - - assertThatThrownBy({ client.chat().completions().create(params) }) - .satisfies({ e -> - assertBadRequest(e, Headers.builder().build(), ArcadeError.builder().build()) - }) - } - - private fun toJson(body: T): ByteArray { - return JSON_MAPPER.writeValueAsBytes(body) - } - - private fun assertUnexpectedStatusCodeException( - throwable: Throwable, - statusCode: Int, - headers: Headers, - responseBody: ByteArray, - ) { - assertThat(throwable) - .asInstanceOf( - InstanceOfAssertFactories.throwable(UnexpectedStatusCodeException::class.java) - ) - .satisfies({ e -> - assertThat(e.statusCode()).isEqualTo(statusCode) - assertThat(e.body()).isEqualTo(String(responseBody)) - assertThat(e.headers().toMap()).containsAllEntriesOf(headers.toMap()) - }) - } + } - private fun assertBadRequest(throwable: Throwable, headers: Headers, error: ArcadeError) { - assertThat(throwable) - .asInstanceOf(InstanceOfAssertFactories.throwable(BadRequestException::class.java)) - .satisfies({ e -> - assertThat(e.statusCode()).isEqualTo(400) - assertThat(e.error()).isEqualTo(error) - assertThat(e.headers().toMap()).containsAllEntriesOf(headers.toMap()) - }) + assertThat(e.statusCode()).isEqualTo(999) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } - private fun assertUnauthorized(throwable: Throwable, headers: Headers, error: ArcadeError) { - assertThat(throwable) - .asInstanceOf(InstanceOfAssertFactories.throwable(UnauthorizedException::class.java)) - .satisfies({ e -> - assertThat(e.statusCode()).isEqualTo(401) - assertThat(e.error()).isEqualTo(error) - assertThat(e.headers().toMap()).containsAllEntriesOf(headers.toMap()) - }) - } + @Test + fun completionsCreate999WithRawResponse() { + val completionService = client.chat().completions().withRawResponse() + stubFor( + post(anyUrl()) + .willReturn( + status(999).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) - private fun assertPermissionDenied(throwable: Throwable, headers: Headers, error: ArcadeError) { - assertThat(throwable) - .asInstanceOf( - InstanceOfAssertFactories.throwable(PermissionDeniedException::class.java) - ) - .satisfies({ e -> - assertThat(e.statusCode()).isEqualTo(403) - assertThat(e.error()).isEqualTo(error) - assertThat(e.headers().toMap()).containsAllEntriesOf(headers.toMap()) - }) - } + val e = + assertThrows { + completionService.create( + ChatRequest.builder() + .frequencyPenalty(0.0) + .logitBias( + ChatRequest.LogitBias.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .logprobs(true) + .maxTokens(0L) + .addMessage( + ChatMessage.builder() + .content("content") + .role("role") + .name("name") + .toolCallId("tool_call_id") + .addToolCall( + ChatMessage.ToolCall.builder() + .id("id") + .function( + ChatMessage.ToolCall.Function.builder() + .arguments("arguments") + .name("name") + .build() + ) + .type(ChatMessage.ToolCall.Type.FUNCTION) + .build() + ) + .build() + ) + .model("model") + .n(0L) + .parallelToolCalls(true) + .presencePenalty(0.0) + .responseFormat( + ChatRequest.ResponseFormat.builder() + .type(ChatRequest.ResponseFormat.Type.JSON_OBJECT) + .build() + ) + .seed(0L) + .addStop("string") + .stream(true) + .streamOptions( + ChatRequest.StreamOptions.builder().includeUsage(true).build() + ) + .temperature(0.0) + .toolChoice(JsonValue.from(mapOf())) + .tools(JsonValue.from(mapOf())) + .topLogprobs(0L) + .topP(0.0) + .user("user") + .build() + ) + } - private fun assertNotFound(throwable: Throwable, headers: Headers, error: ArcadeError) { - assertThat(throwable) - .asInstanceOf(InstanceOfAssertFactories.throwable(NotFoundException::class.java)) - .satisfies({ e -> - assertThat(e.statusCode()).isEqualTo(404) - assertThat(e.error()).isEqualTo(error) - assertThat(e.headers().toMap()).containsAllEntriesOf(headers.toMap()) - }) + assertThat(e.statusCode()).isEqualTo(999) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } - private fun assertUnprocessableEntity( - throwable: Throwable, - headers: Headers, - error: ArcadeError, - ) { - assertThat(throwable) - .asInstanceOf( - InstanceOfAssertFactories.throwable(UnprocessableEntityException::class.java) - ) - .satisfies({ e -> - assertThat(e.statusCode()).isEqualTo(422) - assertThat(e.error()).isEqualTo(error) - assertThat(e.headers().toMap()).containsAllEntriesOf(headers.toMap()) - }) - } + @Test + fun completionsCreateInvalidJsonBody() { + val completionService = client.chat().completions() + stubFor( + post(anyUrl()) + .willReturn(status(200).withHeader(HEADER_NAME, HEADER_VALUE).withBody(NOT_JSON)) + ) - private fun assertRateLimit(throwable: Throwable, headers: Headers, error: ArcadeError) { - assertThat(throwable) - .asInstanceOf(InstanceOfAssertFactories.throwable(RateLimitException::class.java)) - .satisfies({ e -> - assertThat(e.statusCode()).isEqualTo(429) - assertThat(e.error()).isEqualTo(error) - assertThat(e.headers().toMap()).containsAllEntriesOf(headers.toMap()) - }) - } + val e = + assertThrows { + completionService.create( + ChatRequest.builder() + .frequencyPenalty(0.0) + .logitBias( + ChatRequest.LogitBias.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .logprobs(true) + .maxTokens(0L) + .addMessage( + ChatMessage.builder() + .content("content") + .role("role") + .name("name") + .toolCallId("tool_call_id") + .addToolCall( + ChatMessage.ToolCall.builder() + .id("id") + .function( + ChatMessage.ToolCall.Function.builder() + .arguments("arguments") + .name("name") + .build() + ) + .type(ChatMessage.ToolCall.Type.FUNCTION) + .build() + ) + .build() + ) + .model("model") + .n(0L) + .parallelToolCalls(true) + .presencePenalty(0.0) + .responseFormat( + ChatRequest.ResponseFormat.builder() + .type(ChatRequest.ResponseFormat.Type.JSON_OBJECT) + .build() + ) + .seed(0L) + .addStop("string") + .stream(true) + .streamOptions( + ChatRequest.StreamOptions.builder().includeUsage(true).build() + ) + .temperature(0.0) + .toolChoice(JsonValue.from(mapOf())) + .tools(JsonValue.from(mapOf())) + .topLogprobs(0L) + .topP(0.0) + .user("user") + .build() + ) + } - private fun assertInternalServer(throwable: Throwable, headers: Headers, error: ArcadeError) { - assertThat(throwable) - .asInstanceOf(InstanceOfAssertFactories.throwable(InternalServerException::class.java)) - .satisfies({ e -> - assertThat(e.statusCode()).isEqualTo(500) - assertThat(e.error()).isEqualTo(error) - assertThat(e.headers().toMap()).containsAllEntriesOf(headers.toMap()) - }) + assertThat(e).hasMessage("Error reading response") } private fun Headers.toMap(): Map> = diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/services/ServiceParamsTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/services/ServiceParamsTest.kt index 03dfd6f..d2d8a75 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/services/ServiceParamsTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/services/ServiceParamsTest.kt @@ -2,7 +2,6 @@ package dev.arcade.services -import com.fasterxml.jackson.databind.json.JsonMapper import com.github.tomakehurst.wiremock.client.WireMock.anyUrl import com.github.tomakehurst.wiremock.client.WireMock.equalTo import com.github.tomakehurst.wiremock.client.WireMock.ok @@ -15,25 +14,18 @@ import com.github.tomakehurst.wiremock.junit5.WireMockTest import dev.arcade.client.ArcadeClient import dev.arcade.client.okhttp.ArcadeOkHttpClient import dev.arcade.core.JsonValue -import dev.arcade.core.jsonMapper -import dev.arcade.models.AuthorizationContext -import dev.arcade.models.AuthorizationResponse -import dev.arcade.models.ChatCompletionCreateParams -import dev.arcade.models.ChatMessage -import dev.arcade.models.ChatRequest -import dev.arcade.models.ChatResponse -import dev.arcade.models.Choice -import dev.arcade.models.ExecuteToolRequest -import dev.arcade.models.ExecuteToolResponse -import dev.arcade.models.ToolExecuteParams -import dev.arcade.models.Usage +import dev.arcade.models.chat.ChatMessage +import dev.arcade.models.chat.ChatRequest +import dev.arcade.models.chat.completions.CompletionCreateParams +import dev.arcade.models.tools.ExecuteToolRequest +import dev.arcade.models.tools.ToolExecuteParams import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test +import org.junit.jupiter.api.parallel.ResourceLock @WireMockTest -class ServiceParamsTest { - - private val JSON_MAPPER: JsonMapper = jsonMapper() +@ResourceLock("https://github.com/wiremock/wiremock/issues/169") +internal class ServiceParamsTest { private lateinit var client: ArcadeClient @@ -41,23 +33,18 @@ class ServiceParamsTest { fun beforeEach(wmRuntimeInfo: WireMockRuntimeInfo) { client = ArcadeOkHttpClient.builder() + .baseUrl(wmRuntimeInfo.httpBaseUrl) .apiKey("My API Key") - .baseUrl(wmRuntimeInfo.getHttpBaseUrl()) .build() } @Test - fun completionsCreateWithAdditionalParams() { - val additionalHeaders = mutableMapOf>() - - additionalHeaders.put("x-test-header", listOf("abc1234")) - - val additionalQueryParams = mutableMapOf>() + fun create() { + val completionService = client.chat().completions() + stubFor(post(anyUrl()).willReturn(ok("{}"))) - additionalQueryParams.put("test_query_param", listOf("def567")) - - val params = - ChatCompletionCreateParams.builder() + completionService.create( + CompletionCreateParams.builder() .chatRequest( ChatRequest.builder() .frequencyPenalty(0.0) @@ -111,112 +98,24 @@ class ServiceParamsTest { .user("user") .build() ) - .additionalHeaders(additionalHeaders) - .additionalQueryParams(additionalQueryParams) - .build() - - val apiResponse = - ChatResponse.builder() - .id("id") - .addChoice( - Choice.builder() - .finishReason("finish_reason") - .index(0L) - .logprobs(JsonValue.from(mapOf())) - .message( - ChatMessage.builder() - .content("content") - .role("role") - .name("name") - .toolCallId("tool_call_id") - .addToolCall( - ChatMessage.ToolCall.builder() - .id("id") - .function( - ChatMessage.ToolCall.Function.builder() - .arguments("arguments") - .name("name") - .build() - ) - .type(ChatMessage.ToolCall.Type.FUNCTION) - .build() - ) - .build() - ) - .addToolAuthorization( - AuthorizationResponse.builder() - .id("id") - .context( - AuthorizationContext.builder() - .token("token") - .userInfo( - AuthorizationContext.UserInfo.builder() - .putAdditionalProperty("foo", JsonValue.from("bar")) - .build() - ) - .build() - ) - .providerId("provider_id") - .addScope("string") - .status(AuthorizationResponse.Status.NOT_STARTED) - .url("url") - .userId("user_id") - .build() - ) - .addToolMessage( - ChatMessage.builder() - .content("content") - .role("role") - .name("name") - .toolCallId("tool_call_id") - .addToolCall( - ChatMessage.ToolCall.builder() - .id("id") - .function( - ChatMessage.ToolCall.Function.builder() - .arguments("arguments") - .name("name") - .build() - ) - .type(ChatMessage.ToolCall.Type.FUNCTION) - .build() - ) - .build() - ) - .build() - ) - .created(0L) - .model("model") - .object_("object") - .systemFingerprint("system_fingerprint") - .usage( - Usage.builder().completionTokens(0L).promptTokens(0L).totalTokens(0L).build() - ) + .putAdditionalHeader("Secret-Header", "42") + .putAdditionalQueryParam("secret_query_param", "42") .build() - - stubFor( - post(anyUrl()) - .withHeader("x-test-header", equalTo("abc1234")) - .withQueryParam("test_query_param", equalTo("def567")) - .willReturn(ok(JSON_MAPPER.writeValueAsString(apiResponse))) ) - client.chat().completions().create(params) - - verify(postRequestedFor(anyUrl())) + verify( + postRequestedFor(anyUrl()) + .withHeader("Secret-Header", equalTo("42")) + .withQueryParam("secret_query_param", equalTo("42")) + ) } @Test - fun toolsExecuteWithAdditionalParams() { - val additionalHeaders = mutableMapOf>() - - additionalHeaders.put("x-test-header", listOf("abc1234")) - - val additionalQueryParams = mutableMapOf>() - - additionalQueryParams.put("test_query_param", listOf("def567")) + fun execute() { + val toolService = client.tools() + stubFor(post(anyUrl()).willReturn(ok("{}"))) - val params = + toolService.execute( ToolExecuteParams.builder() .executeToolRequest( ExecuteToolRequest.builder() @@ -232,80 +131,15 @@ class ServiceParamsTest { .userId("user_id") .build() ) - .additionalHeaders(additionalHeaders) - .additionalQueryParams(additionalQueryParams) + .putAdditionalHeader("Secret-Header", "42") + .putAdditionalQueryParam("secret_query_param", "42") .build() - - val apiResponse = - ExecuteToolResponse.builder() - .id("id") - .duration(0.0) - .executionId("execution_id") - .executionType("execution_type") - .finishedAt("finished_at") - .output( - ExecuteToolResponse.Output.builder() - .authorization( - AuthorizationResponse.builder() - .id("id") - .context( - AuthorizationContext.builder() - .token("token") - .userInfo( - AuthorizationContext.UserInfo.builder() - .putAdditionalProperty("foo", JsonValue.from("bar")) - .build() - ) - .build() - ) - .providerId("provider_id") - .addScope("string") - .status(AuthorizationResponse.Status.NOT_STARTED) - .url("url") - .userId("user_id") - .build() - ) - .error( - ExecuteToolResponse.Output.Error.builder() - .canRetry(true) - .kind(ExecuteToolResponse.Output.Error.Kind.TOOLKIT_LOAD_FAILED) - .message("message") - .additionalPromptContent("additional_prompt_content") - .developerMessage("developer_message") - .extra( - ExecuteToolResponse.Output.Error.Extra.builder() - .putAdditionalProperty("foo", JsonValue.from("bar")) - .build() - ) - .retryAfterMs(0L) - .stacktrace("stacktrace") - .statusCode(0L) - .build() - ) - .addLog( - ExecuteToolResponse.Output.Log.builder() - .level("level") - .message("message") - .subtype("subtype") - .build() - ) - .value(JsonValue.from(mapOf())) - .build() - ) - .runAt("run_at") - .status("status") - .success(true) - .build() - - stubFor( - post(anyUrl()) - .withHeader("x-test-header", equalTo("abc1234")) - .withQueryParam("test_query_param", equalTo("def567")) - .willReturn(ok(JSON_MAPPER.writeValueAsString(apiResponse))) ) - client.tools().execute(params) - - verify(postRequestedFor(anyUrl())) + verify( + postRequestedFor(anyUrl()) + .withHeader("Secret-Header", equalTo("42")) + .withQueryParam("secret_query_param", equalTo("42")) + ) } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/services/async/AuthServiceAsyncTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/services/async/AuthServiceAsyncTest.kt new file mode 100644 index 0000000..d41b7a6 --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/services/async/AuthServiceAsyncTest.kt @@ -0,0 +1,186 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.services.async + +import dev.arcade.TestServerExtension +import dev.arcade.client.okhttp.ArcadeOkHttpClient +import dev.arcade.client.okhttp.ArcadeOkHttpClientAsync +import dev.arcade.models.auth.AuthAuthorizeParams +import dev.arcade.models.auth.AuthRequest +import dev.arcade.models.auth.AuthStatusParams +import dev.arcade.models.auth.ConfirmUserRequest +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.mockito.kotlin.spy +import org.mockito.kotlin.verify + +@ExtendWith(TestServerExtension::class) +internal class AuthServiceAsyncTest { + + @Test + fun authorize() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val authServiceAsync = client.auth() + + val authorizationResponseFuture = + authServiceAsync.authorize( + AuthRequest.builder() + .authRequirement( + AuthRequest.AuthRequirement.builder() + .id("id") + .oauth2( + AuthRequest.AuthRequirement.Oauth2.builder() + .addScope("string") + .build() + ) + .providerId("provider_id") + .providerType("provider_type") + .build() + ) + .userId("user_id") + .nextUri("next_uri") + .build() + ) + + val authorizationResponse = authorizationResponseFuture.get() + authorizationResponse.validate() + } + + @Test + fun confirmUser() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val authServiceAsync = client.auth() + + val confirmUserResponseFuture = + authServiceAsync.confirmUser( + ConfirmUserRequest.builder().flowId("flow_id").userId("user_id").build() + ) + + val confirmUserResponse = confirmUserResponseFuture.get() + confirmUserResponse.validate() + } + + @Test + fun status() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val authServiceAsync = client.auth() + + val authorizationResponseFuture = + authServiceAsync.status(AuthStatusParams.builder().id("id").wait(0L).build()) + + val authorizationResponse = authorizationResponseFuture.get() + authorizationResponse.validate() + } + + // ------------------------------------------------------------------------- + // Start of manually added code + // ------------------------------------------------------------------------- + + @Test + fun start() { + val expected = + AuthAuthorizeParams.builder() + .authRequest( + AuthRequest.builder() + .userId("user_id") + .authRequirement( + AuthRequest.AuthRequirement.builder() + .providerId("provider_id") + .providerType("provider_type") + .oauth2( + AuthRequest.AuthRequirement.Oauth2.builder() + .scopes(listOf("scope_one", "scope_two")) + .build() + ) + .build() + ) + .build() + ) + .build() + + verifyAuthorize(expected) { auth -> + auth.start("user_id", "provider_id", "provider_type", listOf("scope_one", "scope_two")) + } + } + + @Test + fun start_noScopes() { + val expected = + AuthAuthorizeParams.builder() + .authRequest( + AuthRequest.builder() + .userId("user_id") + .authRequirement( + AuthRequest.AuthRequirement.builder() + .providerId("provider_id") + .providerType("provider_type") + .oauth2( + AuthRequest.AuthRequirement.Oauth2.builder() + .scopes(emptyList()) + .build() + ) + .build() + ) + .build() + ) + .build() + + verifyAuthorize(expected) { auth -> auth.start("user_id", "provider_id", "provider_type") } + } + + @Test + fun start_noProviderType() { + val expected = + AuthAuthorizeParams.builder() + .authRequest( + AuthRequest.builder() + .userId("user_id") + .authRequirement( + AuthRequest.AuthRequirement.builder() + .providerId("provider_id") + .providerType("oauth2") + .oauth2( + AuthRequest.AuthRequirement.Oauth2.builder() + .scopes(emptyList()) + .build() + ) + .build() + ) + .build() + ) + .build() + + verifyAuthorize(expected) { auth -> auth.start("user_id", "provider_id") } + } + + private fun verifyAuthorize( + expected: AuthAuthorizeParams, + testCode: (AuthServiceAsync) -> Unit, + ) { + // given + val client = + ArcadeOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val auth = spy(client.async().auth()) + + // when + testCode.invoke(auth) + + // then + verify(auth).authorize(expected) + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/services/async/HealthServiceAsyncTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/services/async/HealthServiceAsyncTest.kt new file mode 100644 index 0000000..45f2d8d --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/services/async/HealthServiceAsyncTest.kt @@ -0,0 +1,27 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.services.async + +import dev.arcade.TestServerExtension +import dev.arcade.client.okhttp.ArcadeOkHttpClientAsync +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class HealthServiceAsyncTest { + + @Test + fun check() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val healthServiceAsync = client.health() + + val healthSchemaFuture = healthServiceAsync.check() + + val healthSchema = healthSchemaFuture.get() + healthSchema.validate() + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/services/async/ToolServiceAsyncTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/services/async/ToolServiceAsyncTest.kt new file mode 100644 index 0000000..7c229d7 --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/services/async/ToolServiceAsyncTest.kt @@ -0,0 +1,105 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.services.async + +import dev.arcade.TestServerExtension +import dev.arcade.client.okhttp.ArcadeOkHttpClientAsync +import dev.arcade.core.JsonValue +import dev.arcade.models.tools.AuthorizeToolRequest +import dev.arcade.models.tools.ExecuteToolRequest +import dev.arcade.models.tools.ToolGetParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class ToolServiceAsyncTest { + + @Test + fun list() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val toolServiceAsync = client.tools() + + val pageFuture = toolServiceAsync.list() + + val page = pageFuture.get() + page.response().validate() + } + + @Test + fun authorize() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val toolServiceAsync = client.tools() + + val authorizationResponseFuture = + toolServiceAsync.authorize( + AuthorizeToolRequest.builder() + .toolName("tool_name") + .nextUri("next_uri") + .toolVersion("tool_version") + .userId("user_id") + .build() + ) + + val authorizationResponse = authorizationResponseFuture.get() + authorizationResponse.validate() + } + + @Test + fun execute() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val toolServiceAsync = client.tools() + + val executeToolResponseFuture = + toolServiceAsync.execute( + ExecuteToolRequest.builder() + .toolName("tool_name") + .includeErrorStacktrace(true) + .input( + ExecuteToolRequest.Input.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .runAt("run_at") + .toolVersion("tool_version") + .userId("user_id") + .build() + ) + + val executeToolResponse = executeToolResponseFuture.get() + executeToolResponse.validate() + } + + @Test + fun get() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val toolServiceAsync = client.tools() + + val toolDefinitionFuture = + toolServiceAsync.get( + ToolGetParams.builder() + .name("name") + .addIncludeFormat(ToolGetParams.IncludeFormat.ARCADE) + .userId("user_id") + .build() + ) + + val toolDefinition = toolDefinitionFuture.get() + toolDefinition.validate() + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/services/async/WorkerServiceAsyncTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/services/async/WorkerServiceAsyncTest.kt new file mode 100644 index 0000000..a82a179 --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/services/async/WorkerServiceAsyncTest.kt @@ -0,0 +1,202 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.services.async + +import dev.arcade.TestServerExtension +import dev.arcade.client.okhttp.ArcadeOkHttpClientAsync +import dev.arcade.core.JsonValue +import dev.arcade.models.workers.CreateWorkerRequest +import dev.arcade.models.workers.UpdateWorkerRequest +import dev.arcade.models.workers.WorkerUpdateParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class WorkerServiceAsyncTest { + + @Test + fun create() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val workerServiceAsync = client.workers() + + val workerResponseFuture = + workerServiceAsync.create( + CreateWorkerRequest.builder() + .id("id") + .enabled(true) + .http( + CreateWorkerRequest.Http.builder() + .retry(0L) + .secret("secret") + .timeout(1L) + .uri("uri") + .build() + ) + .mcp( + CreateWorkerRequest.Mcp.builder() + .retry(0L) + .timeout(1L) + .uri("uri") + .headers( + CreateWorkerRequest.Mcp.Headers.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .oauth2( + CreateWorkerRequest.Mcp.Oauth2.builder() + .authorizationUrl("authorization_url") + .clientId("client_id") + .clientSecret("client_secret") + .externalId("external_id") + .build() + ) + .secrets( + CreateWorkerRequest.Mcp.Secrets.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .build() + ) + .type("type") + .build() + ) + + val workerResponse = workerResponseFuture.get() + workerResponse.validate() + } + + @Test + fun update() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val workerServiceAsync = client.workers() + + val workerResponseFuture = + workerServiceAsync.update( + WorkerUpdateParams.builder() + .id("id") + .updateWorkerRequest( + UpdateWorkerRequest.builder() + .enabled(true) + .http( + UpdateWorkerRequest.Http.builder() + .retry(0L) + .secret("secret") + .timeout(1L) + .uri("uri") + .build() + ) + .mcp( + UpdateWorkerRequest.Mcp.builder() + .headers( + UpdateWorkerRequest.Mcp.Headers.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .oauth2( + UpdateWorkerRequest.Mcp.Oauth2.builder() + .authorizationUrl("authorization_url") + .clientId("client_id") + .clientSecret("client_secret") + .build() + ) + .retry(0L) + .secrets( + UpdateWorkerRequest.Mcp.Secrets.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .timeout(1L) + .uri("uri") + .build() + ) + .build() + ) + .build() + ) + + val workerResponse = workerResponseFuture.get() + workerResponse.validate() + } + + @Test + fun list() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val workerServiceAsync = client.workers() + + val pageFuture = workerServiceAsync.list() + + val page = pageFuture.get() + page.response().validate() + } + + @Test + fun delete() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val workerServiceAsync = client.workers() + + val future = workerServiceAsync.delete("id") + + val response = future.get() + } + + @Test + fun get() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val workerServiceAsync = client.workers() + + val workerResponseFuture = workerServiceAsync.get("id") + + val workerResponse = workerResponseFuture.get() + workerResponse.validate() + } + + @Test + fun health() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val workerServiceAsync = client.workers() + + val workerHealthResponseFuture = workerServiceAsync.health("id") + + val workerHealthResponse = workerHealthResponseFuture.get() + workerHealthResponse.validate() + } + + @Test + fun tools() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val workerServiceAsync = client.workers() + + val pageFuture = workerServiceAsync.tools("id") + + val page = pageFuture.get() + page.response().validate() + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/services/async/admin/AuthProviderServiceAsyncTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/services/async/admin/AuthProviderServiceAsyncTest.kt new file mode 100644 index 0000000..04a3bb6 --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/services/async/admin/AuthProviderServiceAsyncTest.kt @@ -0,0 +1,472 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.services.async.admin + +import dev.arcade.TestServerExtension +import dev.arcade.client.okhttp.ArcadeOkHttpClientAsync +import dev.arcade.core.JsonValue +import dev.arcade.models.admin.authproviders.AuthProviderCreateRequest +import dev.arcade.models.admin.authproviders.AuthProviderPatchParams +import dev.arcade.models.admin.authproviders.AuthProviderUpdateRequest +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class AuthProviderServiceAsyncTest { + + @Test + fun create() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val authProviderServiceAsync = client.admin().authProviders() + + val authProviderResponseFuture = + authProviderServiceAsync.create( + AuthProviderCreateRequest.builder() + .id("id") + .description("description") + .externalId("external_id") + .oauth2( + AuthProviderCreateRequest.Oauth2.builder() + .clientId("client_id") + .authorizeRequest( + AuthProviderCreateRequest.Oauth2.AuthorizeRequest.builder() + .endpoint("endpoint") + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .method("method") + .params( + AuthProviderCreateRequest.Oauth2.AuthorizeRequest.Params + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .requestContentType( + AuthProviderCreateRequest.Oauth2.AuthorizeRequest + .RequestContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseContentType( + AuthProviderCreateRequest.Oauth2.AuthorizeRequest + .ResponseContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseMap( + AuthProviderCreateRequest.Oauth2.AuthorizeRequest + .ResponseMap + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .build() + ) + .clientSecret("client_secret") + .pkce( + AuthProviderCreateRequest.Oauth2.Pkce.builder() + .codeChallengeMethod("code_challenge_method") + .enabled(true) + .build() + ) + .refreshRequest( + AuthProviderCreateRequest.Oauth2.RefreshRequest.builder() + .endpoint("endpoint") + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .method("method") + .params( + AuthProviderCreateRequest.Oauth2.RefreshRequest.Params + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .requestContentType( + AuthProviderCreateRequest.Oauth2.RefreshRequest + .RequestContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseContentType( + AuthProviderCreateRequest.Oauth2.RefreshRequest + .ResponseContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseMap( + AuthProviderCreateRequest.Oauth2.RefreshRequest.ResponseMap + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .build() + ) + .scopeDelimiter( + AuthProviderCreateRequest.Oauth2.ScopeDelimiter.Unknown0 + ) + .tokenIntrospectionRequest( + AuthProviderCreateRequest.Oauth2.TokenIntrospectionRequest.builder() + .endpoint("endpoint") + .triggers( + AuthProviderCreateRequest.Oauth2.TokenIntrospectionRequest + .Triggers + .builder() + .onTokenGrant(true) + .onTokenRefresh(true) + .build() + ) + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .method("method") + .params( + AuthProviderCreateRequest.Oauth2.TokenIntrospectionRequest + .Params + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .requestContentType( + AuthProviderCreateRequest.Oauth2.TokenIntrospectionRequest + .RequestContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseContentType( + AuthProviderCreateRequest.Oauth2.TokenIntrospectionRequest + .ResponseContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseMap( + AuthProviderCreateRequest.Oauth2.TokenIntrospectionRequest + .ResponseMap + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .build() + ) + .tokenRequest( + AuthProviderCreateRequest.Oauth2.TokenRequest.builder() + .endpoint("endpoint") + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .method("method") + .params( + AuthProviderCreateRequest.Oauth2.TokenRequest.Params + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .requestContentType( + AuthProviderCreateRequest.Oauth2.TokenRequest + .RequestContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseContentType( + AuthProviderCreateRequest.Oauth2.TokenRequest + .ResponseContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseMap( + AuthProviderCreateRequest.Oauth2.TokenRequest.ResponseMap + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .build() + ) + .userInfoRequest( + AuthProviderCreateRequest.Oauth2.UserInfoRequest.builder() + .endpoint("endpoint") + .triggers( + AuthProviderCreateRequest.Oauth2.UserInfoRequest.Triggers + .builder() + .onTokenGrant(true) + .onTokenRefresh(true) + .build() + ) + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .method("method") + .params( + AuthProviderCreateRequest.Oauth2.UserInfoRequest.Params + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .requestContentType( + AuthProviderCreateRequest.Oauth2.UserInfoRequest + .RequestContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseContentType( + AuthProviderCreateRequest.Oauth2.UserInfoRequest + .ResponseContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseMap( + AuthProviderCreateRequest.Oauth2.UserInfoRequest.ResponseMap + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .build() + ) + .build() + ) + .providerId("provider_id") + .status("status") + .type("type") + .build() + ) + + val authProviderResponse = authProviderResponseFuture.get() + authProviderResponse.validate() + } + + @Test + fun list() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val authProviderServiceAsync = client.admin().authProviders() + + val authProvidersFuture = authProviderServiceAsync.list() + + val authProviders = authProvidersFuture.get() + authProviders.validate() + } + + @Test + fun delete() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val authProviderServiceAsync = client.admin().authProviders() + + val authProviderResponseFuture = authProviderServiceAsync.delete("id") + + val authProviderResponse = authProviderResponseFuture.get() + authProviderResponse.validate() + } + + @Test + fun get() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val authProviderServiceAsync = client.admin().authProviders() + + val authProviderResponseFuture = authProviderServiceAsync.get("id") + + val authProviderResponse = authProviderResponseFuture.get() + authProviderResponse.validate() + } + + @Test + fun patch() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val authProviderServiceAsync = client.admin().authProviders() + + val authProviderResponseFuture = + authProviderServiceAsync.patch( + AuthProviderPatchParams.builder() + .pathId("id") + .authProviderUpdateRequest( + AuthProviderUpdateRequest.builder() + .id("id") + .description("description") + .oauth2( + AuthProviderUpdateRequest.Oauth2.builder() + .authorizeRequest( + AuthProviderUpdateRequest.Oauth2.AuthorizeRequest.builder() + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .endpoint("endpoint") + .method("method") + .params( + AuthProviderUpdateRequest.Oauth2.AuthorizeRequest + .Params + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("string"), + ) + .build() + ) + .requestContentType( + AuthProviderUpdateRequest.Oauth2.AuthorizeRequest + .RequestContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseContentType( + AuthProviderUpdateRequest.Oauth2.AuthorizeRequest + .ResponseContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseMap( + AuthProviderUpdateRequest.Oauth2.AuthorizeRequest + .ResponseMap + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("string"), + ) + .build() + ) + .build() + ) + .clientId("client_id") + .clientSecret("client_secret") + .pkce( + AuthProviderUpdateRequest.Oauth2.Pkce.builder() + .codeChallengeMethod("code_challenge_method") + .enabled(true) + .build() + ) + .refreshRequest( + AuthProviderUpdateRequest.Oauth2.RefreshRequest.builder() + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .endpoint("endpoint") + .method("method") + .params( + AuthProviderUpdateRequest.Oauth2.RefreshRequest + .Params + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("string"), + ) + .build() + ) + .requestContentType( + AuthProviderUpdateRequest.Oauth2.RefreshRequest + .RequestContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseContentType( + AuthProviderUpdateRequest.Oauth2.RefreshRequest + .ResponseContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseMap( + AuthProviderUpdateRequest.Oauth2.RefreshRequest + .ResponseMap + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("string"), + ) + .build() + ) + .build() + ) + .scopeDelimiter( + AuthProviderUpdateRequest.Oauth2.ScopeDelimiter.Unknown2 + ) + .tokenRequest( + AuthProviderUpdateRequest.Oauth2.TokenRequest.builder() + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .endpoint("endpoint") + .method("method") + .params( + AuthProviderUpdateRequest.Oauth2.TokenRequest.Params + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("string"), + ) + .build() + ) + .requestContentType( + AuthProviderUpdateRequest.Oauth2.TokenRequest + .RequestContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseContentType( + AuthProviderUpdateRequest.Oauth2.TokenRequest + .ResponseContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseMap( + AuthProviderUpdateRequest.Oauth2.TokenRequest + .ResponseMap + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("string"), + ) + .build() + ) + .build() + ) + .userInfoRequest( + AuthProviderUpdateRequest.Oauth2.UserInfoRequest.builder() + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .endpoint("endpoint") + .method("method") + .params( + AuthProviderUpdateRequest.Oauth2.UserInfoRequest + .Params + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("string"), + ) + .build() + ) + .requestContentType( + AuthProviderUpdateRequest.Oauth2.UserInfoRequest + .RequestContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseContentType( + AuthProviderUpdateRequest.Oauth2.UserInfoRequest + .ResponseContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseMap( + AuthProviderUpdateRequest.Oauth2.UserInfoRequest + .ResponseMap + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("string"), + ) + .build() + ) + .triggers( + AuthProviderUpdateRequest.Oauth2.UserInfoRequest + .Triggers + .builder() + .onTokenGrant(true) + .onTokenRefresh(true) + .build() + ) + .build() + ) + .build() + ) + .providerId("provider_id") + .status("status") + .type("type") + .build() + ) + .build() + ) + + val authProviderResponse = authProviderResponseFuture.get() + authProviderResponse.validate() + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/services/async/admin/SecretServiceAsyncTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/services/async/admin/SecretServiceAsyncTest.kt new file mode 100644 index 0000000..91e94c8 --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/services/async/admin/SecretServiceAsyncTest.kt @@ -0,0 +1,64 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.services.async.admin + +import dev.arcade.TestServerExtension +import dev.arcade.client.okhttp.ArcadeOkHttpClientAsync +import dev.arcade.models.admin.secrets.SecretCreateParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class SecretServiceAsyncTest { + + @Test + fun create() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val secretServiceAsync = client.admin().secrets() + + val secretResponseFuture = + secretServiceAsync.create( + SecretCreateParams.builder() + .secretKey("secret_key") + .value("value") + .description("description") + .build() + ) + + val secretResponse = secretResponseFuture.get() + secretResponse.validate() + } + + @Test + fun list() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val secretServiceAsync = client.admin().secrets() + + val secretsFuture = secretServiceAsync.list() + + val secrets = secretsFuture.get() + secrets.validate() + } + + @Test + fun delete() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val secretServiceAsync = client.admin().secrets() + + val future = secretServiceAsync.delete("secret_id") + + val response = future.get() + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/services/async/admin/UserConnectionServiceAsyncTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/services/async/admin/UserConnectionServiceAsyncTest.kt new file mode 100644 index 0000000..b009507 --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/services/async/admin/UserConnectionServiceAsyncTest.kt @@ -0,0 +1,41 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.services.async.admin + +import dev.arcade.TestServerExtension +import dev.arcade.client.okhttp.ArcadeOkHttpClientAsync +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class UserConnectionServiceAsyncTest { + + @Test + fun list() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val userConnectionServiceAsync = client.admin().userConnections() + + val pageFuture = userConnectionServiceAsync.list() + + val page = pageFuture.get() + page.response().validate() + } + + @Test + fun delete() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val userConnectionServiceAsync = client.admin().userConnections() + + val future = userConnectionServiceAsync.delete("id") + + val response = future.get() + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/services/async/chat/CompletionServiceAsyncTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/services/async/chat/CompletionServiceAsyncTest.kt new file mode 100644 index 0000000..3cb39b0 --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/services/async/chat/CompletionServiceAsyncTest.kt @@ -0,0 +1,81 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.services.async.chat + +import dev.arcade.TestServerExtension +import dev.arcade.client.okhttp.ArcadeOkHttpClientAsync +import dev.arcade.core.JsonValue +import dev.arcade.models.chat.ChatMessage +import dev.arcade.models.chat.ChatRequest +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class CompletionServiceAsyncTest { + + @Test + fun create() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val completionServiceAsync = client.chat().completions() + + val chatResponseFuture = + completionServiceAsync.create( + ChatRequest.builder() + .frequencyPenalty(0.0) + .logitBias( + ChatRequest.LogitBias.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .logprobs(true) + .maxTokens(0L) + .addMessage( + ChatMessage.builder() + .content("content") + .role("role") + .name("name") + .toolCallId("tool_call_id") + .addToolCall( + ChatMessage.ToolCall.builder() + .id("id") + .function( + ChatMessage.ToolCall.Function.builder() + .arguments("arguments") + .name("name") + .build() + ) + .type(ChatMessage.ToolCall.Type.FUNCTION) + .build() + ) + .build() + ) + .model("model") + .n(0L) + .parallelToolCalls(true) + .presencePenalty(0.0) + .responseFormat( + ChatRequest.ResponseFormat.builder() + .type(ChatRequest.ResponseFormat.Type.JSON_OBJECT) + .build() + ) + .seed(0L) + .addStop("string") + .stream(true) + .streamOptions(ChatRequest.StreamOptions.builder().includeUsage(true).build()) + .temperature(0.0) + .toolChoice(JsonValue.from(mapOf())) + .tools(JsonValue.from(mapOf())) + .topLogprobs(0L) + .topP(0.0) + .user("user") + .build() + ) + + val chatResponse = chatResponseFuture.get() + chatResponse.validate() + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/services/async/tools/FormattedServiceAsyncTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/services/async/tools/FormattedServiceAsyncTest.kt new file mode 100644 index 0000000..3ca4c18 --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/services/async/tools/FormattedServiceAsyncTest.kt @@ -0,0 +1,46 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.services.async.tools + +import dev.arcade.TestServerExtension +import dev.arcade.client.okhttp.ArcadeOkHttpClientAsync +import dev.arcade.models.tools.formatted.FormattedGetParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class FormattedServiceAsyncTest { + + @Test + fun list() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val formattedServiceAsync = client.tools().formatted() + + val pageFuture = formattedServiceAsync.list() + + val page = pageFuture.get() + page.response().validate() + } + + @Test + fun get() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val formattedServiceAsync = client.tools().formatted() + + val formattedFuture = + formattedServiceAsync.get( + FormattedGetParams.builder().name("name").format("format").userId("user_id").build() + ) + + val formatted = formattedFuture.get() + formatted.validate() + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/services/async/tools/ScheduledServiceAsyncTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/services/async/tools/ScheduledServiceAsyncTest.kt new file mode 100644 index 0000000..3d039da --- /dev/null +++ b/arcade-java-core/src/test/kotlin/dev/arcade/services/async/tools/ScheduledServiceAsyncTest.kt @@ -0,0 +1,42 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.services.async.tools + +import dev.arcade.TestServerExtension +import dev.arcade.client.okhttp.ArcadeOkHttpClientAsync +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class ScheduledServiceAsyncTest { + + @Test + fun list() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val scheduledServiceAsync = client.tools().scheduled() + + val pageFuture = scheduledServiceAsync.list() + + val page = pageFuture.get() + page.response().validate() + } + + @Test + fun get() { + val client = + ArcadeOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val scheduledServiceAsync = client.tools().scheduled() + + val scheduledFuture = scheduledServiceAsync.get("id") + + val scheduled = scheduledFuture.get() + scheduled.validate() + } +} diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/AuthServiceTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/AuthServiceTest.kt index cedf979..6d493ca 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/AuthServiceTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/AuthServiceTest.kt @@ -4,83 +4,283 @@ package dev.arcade.services.blocking import dev.arcade.TestServerExtension import dev.arcade.client.okhttp.ArcadeOkHttpClient -import dev.arcade.models.AuthAuthorizeParams -import dev.arcade.models.AuthConfirmUserParams -import dev.arcade.models.AuthRequest -import dev.arcade.models.AuthStatusParams -import dev.arcade.models.ConfirmUserRequest +import dev.arcade.core.RequestOptions +import dev.arcade.models.AuthorizationResponse +import dev.arcade.models.auth.AuthAuthorizeParams +import dev.arcade.models.auth.AuthRequest +import dev.arcade.models.auth.AuthStatusParams +import dev.arcade.models.auth.ConfirmUserRequest +import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith +import org.mockito.kotlin.argThat +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.eq +import org.mockito.kotlin.spy +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever @ExtendWith(TestServerExtension::class) -class AuthServiceTest { +internal class AuthServiceTest { @Test - fun callAuthorize() { + fun authorize() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val authService = client.auth() + val authorizationResponse = authService.authorize( - AuthAuthorizeParams.builder() - .authRequest( - AuthRequest.builder() - .authRequirement( - AuthRequest.AuthRequirement.builder() - .id("id") - .oauth2( - AuthRequest.AuthRequirement.Oauth2.builder() - .addScope("string") - .build() - ) - .providerId("provider_id") - .providerType("provider_type") + AuthRequest.builder() + .authRequirement( + AuthRequest.AuthRequirement.builder() + .id("id") + .oauth2( + AuthRequest.AuthRequirement.Oauth2.builder() + .addScope("string") .build() ) - .userId("user_id") - .nextUri("next_uri") + .providerId("provider_id") + .providerType("provider_type") .build() ) + .userId("user_id") + .nextUri("next_uri") .build() ) - println(authorizationResponse) + authorizationResponse.validate() } @Test - fun callConfirmUser() { + fun confirmUser() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val authService = client.auth() + val confirmUserResponse = authService.confirmUser( - AuthConfirmUserParams.builder() - .confirmUserRequest( - ConfirmUserRequest.builder().flowId("flow_id").userId("user_id").build() - ) - .build() + ConfirmUserRequest.builder().flowId("flow_id").userId("user_id").build() ) - println(confirmUserResponse) + confirmUserResponse.validate() } @Test - fun callStatus() { + fun status() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val authService = client.auth() + val authorizationResponse = authService.status(AuthStatusParams.builder().id("id").wait(0L).build()) - println(authorizationResponse) + authorizationResponse.validate() } + + // ------------------------------------------------------------------------- + // Start of manually added code + // ------------------------------------------------------------------------- + + @Test + fun start() { + val expected = + AuthAuthorizeParams.builder() + .authRequest( + AuthRequest.builder() + .userId("user_id") + .authRequirement( + AuthRequest.AuthRequirement.builder() + .providerId("provider_id") + .providerType("provider_type") + .oauth2( + AuthRequest.AuthRequirement.Oauth2.builder() + .scopes(listOf("scope_one", "scope_two")) + .build() + ) + .build() + ) + .build() + ) + .build() + + verifyAuthorize(expected) { auth -> + auth.start("user_id", "provider_id", "provider_type", listOf("scope_one", "scope_two")) + } + } + + @Test + fun start_noScopes() { + val expected = + AuthAuthorizeParams.builder() + .authRequest( + AuthRequest.builder() + .userId("user_id") + .authRequirement( + AuthRequest.AuthRequirement.builder() + .providerId("provider_id") + .providerType("provider_type") + .oauth2( + AuthRequest.AuthRequirement.Oauth2.builder() + .scopes(emptyList()) + .build() + ) + .build() + ) + .build() + ) + .build() + + verifyAuthorize(expected) { auth -> auth.start("user_id", "provider_id", "provider_type") } + } + + @Test + fun start_noProviderType() { + val expected = + AuthAuthorizeParams.builder() + .authRequest( + AuthRequest.builder() + .userId("user_id") + .authRequirement( + AuthRequest.AuthRequirement.builder() + .providerId("provider_id") + .providerType("oauth2") + .oauth2( + AuthRequest.AuthRequirement.Oauth2.builder() + .scopes(emptyList()) + .build() + ) + .build() + ) + .build() + ) + .build() + + verifyAuthorize(expected) { auth -> auth.start("user_id", "provider_id") } + } + + @Test + fun waitForCompletion() { + // given + val client = + ArcadeOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val auth = spy(client.auth()) + + val authResponse = + AuthorizationResponse.builder() + .id("start_id") + .status(AuthorizationResponse.Status.NOT_STARTED) + .build() + + val secondAuthResponse = + AuthorizationResponse.builder() + .id("second_request_id") + .status(AuthorizationResponse.Status.PENDING) + .build() + + val completedAuthResponse = + AuthorizationResponse.builder() + .id("completed_id") + .status(AuthorizationResponse.Status.COMPLETED) + .build() + + val expectedAuthStatusParams = + AuthStatusParams.builder() + .id("start_id") + .wait(AuthServiceImpl.Companion.DEFAULT_LONGPOLL_WAIT_TIME) + .build() + + doReturn(secondAuthResponse) + .whenever(auth) + .status(argThat { id() == "start_id" }, eq(RequestOptions.none())) + + doReturn(completedAuthResponse) + .whenever(auth) + .status( + argThat { id() == "second_request_id" }, + eq(RequestOptions.none()), + ) + + // when + val result = auth.waitForCompletion(authResponse) + + // then + assertThat(result).isEqualTo(completedAuthResponse) + verify(auth).status(expectedAuthStatusParams) + } + + @Test + fun waitForCompletion_withId() { + // given + val client = + ArcadeOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val auth = spy(client.auth()) + + val completedAuthResponse = + AuthorizationResponse.builder() + .id("completed_id") + .status(AuthorizationResponse.Status.COMPLETED) + .build() + + val secondAuthResponse = + AuthorizationResponse.builder() + .id("second_request_id") + .status(AuthorizationResponse.Status.PENDING) + .build() + + val expectedAuthStatusParams = + AuthStatusParams.builder() + .id("start_id") + .wait(AuthServiceImpl.Companion.DEFAULT_LONGPOLL_WAIT_TIME) + .build() + + doReturn(secondAuthResponse) + .whenever(auth) + .status(argThat { id() == "start_id" }, eq(RequestOptions.none())) + + doReturn(completedAuthResponse) + .whenever(auth) + .status( + argThat { id() == "second_request_id" }, + eq(RequestOptions.none()), + ) + + // when + val result = auth.waitForCompletion("start_id") + + // then + assertThat(result).isEqualTo(completedAuthResponse) + verify(auth).status(expectedAuthStatusParams) + } + + private fun verifyAuthorize(expected: AuthAuthorizeParams, testCode: (AuthService) -> Unit) { + // given + val client = + ArcadeOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val auth = spy(client.auth()) + + // when + testCode.invoke(auth) + + // then + verify(auth).authorize(expected) + } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/HealthServiceTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/HealthServiceTest.kt index 0f4d628..8cc0712 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/HealthServiceTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/HealthServiceTest.kt @@ -4,23 +4,23 @@ package dev.arcade.services.blocking import dev.arcade.TestServerExtension import dev.arcade.client.okhttp.ArcadeOkHttpClient -import dev.arcade.models.HealthCheckParams import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class HealthServiceTest { +internal class HealthServiceTest { @Test - fun callCheck() { + fun check() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val healthService = client.health() - val healthSchema = healthService.check(HealthCheckParams.builder().build()) - println(healthSchema) + + val healthSchema = healthService.check() + healthSchema.validate() } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/ToolServiceTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/ToolServiceTest.kt index 4290742..2738abc 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/ToolServiceTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/ToolServiceTest.kt @@ -5,96 +5,88 @@ package dev.arcade.services.blocking import dev.arcade.TestServerExtension import dev.arcade.client.okhttp.ArcadeOkHttpClient import dev.arcade.core.JsonValue -import dev.arcade.models.AuthorizeToolRequest -import dev.arcade.models.ExecuteToolRequest -import dev.arcade.models.ToolAuthorizeParams -import dev.arcade.models.ToolExecuteParams -import dev.arcade.models.ToolGetParams -import dev.arcade.models.ToolListParams +import dev.arcade.models.tools.AuthorizeToolRequest +import dev.arcade.models.tools.ExecuteToolRequest +import dev.arcade.models.tools.ToolGetParams import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class ToolServiceTest { +internal class ToolServiceTest { @Test - fun callList() { + fun list() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val toolService = client.tools() - val schemasOffsetPageSchemasToolResponse = - toolService.list(ToolListParams.builder().build()) - println(schemasOffsetPageSchemasToolResponse) - schemasOffsetPageSchemasToolResponse.items().forEach { it.validate() } + + val page = toolService.list() + + page.response().validate() } @Test - fun callAuthorize() { + fun authorize() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val toolService = client.tools() + val authorizationResponse = toolService.authorize( - ToolAuthorizeParams.builder() - .authorizeToolRequest( - AuthorizeToolRequest.builder() - .toolName("tool_name") - .nextUri("next_uri") - .toolVersion("tool_version") - .userId("user_id") - .build() - ) + AuthorizeToolRequest.builder() + .toolName("tool_name") + .nextUri("next_uri") + .toolVersion("tool_version") + .userId("user_id") .build() ) - println(authorizationResponse) + authorizationResponse.validate() } @Test - fun callExecute() { + fun execute() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val toolService = client.tools() + val executeToolResponse = toolService.execute( - ToolExecuteParams.builder() - .executeToolRequest( - ExecuteToolRequest.builder() - .toolName("tool_name") - .includeErrorStacktrace(true) - .input( - ExecuteToolRequest.Input.builder() - .putAdditionalProperty("foo", JsonValue.from("bar")) - .build() - ) - .runAt("run_at") - .toolVersion("tool_version") - .userId("user_id") + ExecuteToolRequest.builder() + .toolName("tool_name") + .includeErrorStacktrace(true) + .input( + ExecuteToolRequest.Input.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) .build() ) + .runAt("run_at") + .toolVersion("tool_version") + .userId("user_id") .build() ) - println(executeToolResponse) + executeToolResponse.validate() } @Test - fun callGet() { + fun get() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val toolService = client.tools() + val toolDefinition = toolService.get( ToolGetParams.builder() @@ -103,7 +95,7 @@ class ToolServiceTest { .userId("user_id") .build() ) - println(toolDefinition) + toolDefinition.validate() } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/WorkerServiceTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/WorkerServiceTest.kt index 7f6551d..8bc7948 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/WorkerServiceTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/WorkerServiceTest.kt @@ -5,86 +5,78 @@ package dev.arcade.services.blocking import dev.arcade.TestServerExtension import dev.arcade.client.okhttp.ArcadeOkHttpClient import dev.arcade.core.JsonValue -import dev.arcade.models.CreateWorkerRequest -import dev.arcade.models.UpdateWorkerRequest -import dev.arcade.models.WorkerCreateParams -import dev.arcade.models.WorkerDeleteParams -import dev.arcade.models.WorkerGetParams -import dev.arcade.models.WorkerHealthParams -import dev.arcade.models.WorkerListParams -import dev.arcade.models.WorkerToolsParams -import dev.arcade.models.WorkerUpdateParams +import dev.arcade.models.workers.CreateWorkerRequest +import dev.arcade.models.workers.UpdateWorkerRequest +import dev.arcade.models.workers.WorkerUpdateParams import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class WorkerServiceTest { +internal class WorkerServiceTest { @Test - fun callCreate() { + fun create() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val workerService = client.workers() + val workerResponse = workerService.create( - WorkerCreateParams.builder() - .createWorkerRequest( - CreateWorkerRequest.builder() - .id("id") - .enabled(true) - .http( - CreateWorkerRequest.Http.builder() - .retry(0L) - .secret("secret") - .timeout(1L) - .uri("uri") + CreateWorkerRequest.builder() + .id("id") + .enabled(true) + .http( + CreateWorkerRequest.Http.builder() + .retry(0L) + .secret("secret") + .timeout(1L) + .uri("uri") + .build() + ) + .mcp( + CreateWorkerRequest.Mcp.builder() + .retry(0L) + .timeout(1L) + .uri("uri") + .headers( + CreateWorkerRequest.Mcp.Headers.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) .build() ) - .mcp( - CreateWorkerRequest.Mcp.builder() - .retry(0L) - .timeout(1L) - .uri("uri") - .headers( - CreateWorkerRequest.Mcp.Headers.builder() - .putAdditionalProperty("foo", JsonValue.from("string")) - .build() - ) - .oauth2( - CreateWorkerRequest.Mcp.Oauth2.builder() - .authorizationUrl("authorization_url") - .clientId("client_id") - .clientSecret("client_secret") - .externalId("external_id") - .build() - ) - .secrets( - CreateWorkerRequest.Mcp.Secrets.builder() - .putAdditionalProperty("foo", JsonValue.from("string")) - .build() - ) + .oauth2( + CreateWorkerRequest.Mcp.Oauth2.builder() + .authorizationUrl("authorization_url") + .clientId("client_id") + .clientSecret("client_secret") + .externalId("external_id") + .build() + ) + .secrets( + CreateWorkerRequest.Mcp.Secrets.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) .build() ) - .type("type") .build() ) + .type("type") .build() ) - println(workerResponse) + workerResponse.validate() } @Test - fun callUpdate() { + fun update() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val workerService = client.workers() + val workerResponse = workerService.update( WorkerUpdateParams.builder() @@ -128,73 +120,75 @@ class WorkerServiceTest { ) .build() ) - println(workerResponse) + workerResponse.validate() } @Test - fun callList() { + fun list() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val workerService = client.workers() - val schemasOffsetPageSchemasWorkerResponse = - workerService.list(WorkerListParams.builder().build()) - println(schemasOffsetPageSchemasWorkerResponse) - schemasOffsetPageSchemasWorkerResponse.items().forEach { it.validate() } + + val page = workerService.list() + + page.response().validate() } @Test - fun callDelete() { + fun delete() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val workerService = client.workers() - workerService.delete(WorkerDeleteParams.builder().id("id").build()) + + workerService.delete("id") } @Test - fun callGet() { + fun get() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val workerService = client.workers() - val workerResponse = workerService.get(WorkerGetParams.builder().id("id").build()) - println(workerResponse) + + val workerResponse = workerService.get("id") + workerResponse.validate() } @Test - fun callHealth() { + fun health() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val workerService = client.workers() - val workerHealthResponse = - workerService.health(WorkerHealthParams.builder().id("id").build()) - println(workerHealthResponse) + + val workerHealthResponse = workerService.health("id") + workerHealthResponse.validate() } @Test - fun callTools() { + fun tools() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val workerService = client.workers() - val schemasOffsetPageSchemasToolResponse = - workerService.tools(WorkerToolsParams.builder().id("id").build()) - println(schemasOffsetPageSchemasToolResponse) - schemasOffsetPageSchemasToolResponse.items().forEach { it.validate() } + + val page = workerService.tools("id") + + page.response().validate() } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/admin/AuthProviderServiceTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/admin/AuthProviderServiceTest.kt index 83ee407..dcfea65 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/admin/AuthProviderServiceTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/admin/AuthProviderServiceTest.kt @@ -5,326 +5,277 @@ package dev.arcade.services.blocking.admin import dev.arcade.TestServerExtension import dev.arcade.client.okhttp.ArcadeOkHttpClient import dev.arcade.core.JsonValue -import dev.arcade.models.AdminAuthProviderCreateParams -import dev.arcade.models.AdminAuthProviderDeleteParams -import dev.arcade.models.AdminAuthProviderGetParams -import dev.arcade.models.AdminAuthProviderListParams -import dev.arcade.models.AdminAuthProviderPatchParams -import dev.arcade.models.AuthProviderCreateRequest -import dev.arcade.models.AuthProviderUpdateRequest +import dev.arcade.models.admin.authproviders.AuthProviderCreateRequest +import dev.arcade.models.admin.authproviders.AuthProviderPatchParams +import dev.arcade.models.admin.authproviders.AuthProviderUpdateRequest import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class AuthProviderServiceTest { +internal class AuthProviderServiceTest { @Test - fun callCreate() { + fun create() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val authProviderService = client.admin().authProviders() + val authProviderResponse = authProviderService.create( - AdminAuthProviderCreateParams.builder() - .authProviderCreateRequest( - AuthProviderCreateRequest.builder() - .id("id") - .description("description") - .externalId("external_id") - .oauth2( - AuthProviderCreateRequest.Oauth2.builder() - .clientId("client_id") - .authorizeRequest( - AuthProviderCreateRequest.Oauth2.AuthorizeRequest.builder() - .endpoint("endpoint") - .authHeaderValueFormat("auth_header_value_format") - .authMethod("auth_method") - .method("method") - .params( - AuthProviderCreateRequest.Oauth2.AuthorizeRequest - .Params - .builder() - .putAdditionalProperty( - "foo", - JsonValue.from("string"), - ) - .build() - ) - .requestContentType( - AuthProviderCreateRequest.Oauth2.AuthorizeRequest - .RequestContentType - .APPLICATION_X_WWW_FORM_URLENCODED - ) - .responseContentType( - AuthProviderCreateRequest.Oauth2.AuthorizeRequest - .ResponseContentType - .APPLICATION_X_WWW_FORM_URLENCODED - ) - .responseMap( - AuthProviderCreateRequest.Oauth2.AuthorizeRequest - .ResponseMap - .builder() - .putAdditionalProperty( - "foo", - JsonValue.from("string"), - ) - .build() - ) + AuthProviderCreateRequest.builder() + .id("id") + .description("description") + .externalId("external_id") + .oauth2( + AuthProviderCreateRequest.Oauth2.builder() + .clientId("client_id") + .authorizeRequest( + AuthProviderCreateRequest.Oauth2.AuthorizeRequest.builder() + .endpoint("endpoint") + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .method("method") + .params( + AuthProviderCreateRequest.Oauth2.AuthorizeRequest.Params + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) .build() ) - .clientSecret("client_secret") - .pkce( - AuthProviderCreateRequest.Oauth2.Pkce.builder() - .codeChallengeMethod("code_challenge_method") - .enabled(true) + .requestContentType( + AuthProviderCreateRequest.Oauth2.AuthorizeRequest + .RequestContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseContentType( + AuthProviderCreateRequest.Oauth2.AuthorizeRequest + .ResponseContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseMap( + AuthProviderCreateRequest.Oauth2.AuthorizeRequest + .ResponseMap + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) .build() ) - .refreshRequest( - AuthProviderCreateRequest.Oauth2.RefreshRequest.builder() - .endpoint("endpoint") - .authHeaderValueFormat("auth_header_value_format") - .authMethod("auth_method") - .method("method") - .params( - AuthProviderCreateRequest.Oauth2.RefreshRequest - .Params - .builder() - .putAdditionalProperty( - "foo", - JsonValue.from("string"), - ) - .build() - ) - .requestContentType( - AuthProviderCreateRequest.Oauth2.RefreshRequest - .RequestContentType - .APPLICATION_X_WWW_FORM_URLENCODED - ) - .responseContentType( - AuthProviderCreateRequest.Oauth2.RefreshRequest - .ResponseContentType - .APPLICATION_X_WWW_FORM_URLENCODED - ) - .responseMap( - AuthProviderCreateRequest.Oauth2.RefreshRequest - .ResponseMap - .builder() - .putAdditionalProperty( - "foo", - JsonValue.from("string"), - ) - .build() - ) + .build() + ) + .clientSecret("client_secret") + .pkce( + AuthProviderCreateRequest.Oauth2.Pkce.builder() + .codeChallengeMethod("code_challenge_method") + .enabled(true) + .build() + ) + .refreshRequest( + AuthProviderCreateRequest.Oauth2.RefreshRequest.builder() + .endpoint("endpoint") + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .method("method") + .params( + AuthProviderCreateRequest.Oauth2.RefreshRequest.Params + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) .build() ) - .scopeDelimiter( - AuthProviderCreateRequest.Oauth2.ScopeDelimiter.Unknown0 + .requestContentType( + AuthProviderCreateRequest.Oauth2.RefreshRequest + .RequestContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseContentType( + AuthProviderCreateRequest.Oauth2.RefreshRequest + .ResponseContentType + .APPLICATION_X_WWW_FORM_URLENCODED ) - .tokenIntrospectionRequest( + .responseMap( + AuthProviderCreateRequest.Oauth2.RefreshRequest.ResponseMap + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .build() + ) + .scopeDelimiter( + AuthProviderCreateRequest.Oauth2.ScopeDelimiter.Unknown0 + ) + .tokenIntrospectionRequest( + AuthProviderCreateRequest.Oauth2.TokenIntrospectionRequest.builder() + .endpoint("endpoint") + .triggers( AuthProviderCreateRequest.Oauth2.TokenIntrospectionRequest + .Triggers .builder() - .endpoint("endpoint") - .triggers( - AuthProviderCreateRequest.Oauth2 - .TokenIntrospectionRequest - .Triggers - .builder() - .onTokenGrant(true) - .onTokenRefresh(true) - .build() - ) - .authHeaderValueFormat("auth_header_value_format") - .authMethod("auth_method") - .method("method") - .params( - AuthProviderCreateRequest.Oauth2 - .TokenIntrospectionRequest - .Params - .builder() - .putAdditionalProperty( - "foo", - JsonValue.from("string"), - ) - .build() - ) - .requestContentType( - AuthProviderCreateRequest.Oauth2 - .TokenIntrospectionRequest - .RequestContentType - .APPLICATION_X_WWW_FORM_URLENCODED - ) - .responseContentType( - AuthProviderCreateRequest.Oauth2 - .TokenIntrospectionRequest - .ResponseContentType - .APPLICATION_X_WWW_FORM_URLENCODED - ) - .responseMap( - AuthProviderCreateRequest.Oauth2 - .TokenIntrospectionRequest - .ResponseMap - .builder() - .putAdditionalProperty( - "foo", - JsonValue.from("string"), - ) - .build() - ) + .onTokenGrant(true) + .onTokenRefresh(true) .build() ) - .tokenRequest( - AuthProviderCreateRequest.Oauth2.TokenRequest.builder() - .endpoint("endpoint") - .authHeaderValueFormat("auth_header_value_format") - .authMethod("auth_method") - .method("method") - .params( - AuthProviderCreateRequest.Oauth2.TokenRequest.Params - .builder() - .putAdditionalProperty( - "foo", - JsonValue.from("string"), - ) - .build() - ) - .requestContentType( - AuthProviderCreateRequest.Oauth2.TokenRequest - .RequestContentType - .APPLICATION_X_WWW_FORM_URLENCODED - ) - .responseContentType( - AuthProviderCreateRequest.Oauth2.TokenRequest - .ResponseContentType - .APPLICATION_X_WWW_FORM_URLENCODED - ) - .responseMap( - AuthProviderCreateRequest.Oauth2.TokenRequest - .ResponseMap - .builder() - .putAdditionalProperty( - "foo", - JsonValue.from("string"), - ) - .build() - ) + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .method("method") + .params( + AuthProviderCreateRequest.Oauth2.TokenIntrospectionRequest + .Params + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) .build() ) - .userInfoRequest( - AuthProviderCreateRequest.Oauth2.UserInfoRequest.builder() - .endpoint("endpoint") - .triggers( - AuthProviderCreateRequest.Oauth2.UserInfoRequest - .Triggers - .builder() - .onTokenGrant(true) - .onTokenRefresh(true) - .build() - ) - .authHeaderValueFormat("auth_header_value_format") - .authMethod("auth_method") - .method("method") - .params( - AuthProviderCreateRequest.Oauth2.UserInfoRequest - .Params - .builder() - .putAdditionalProperty( - "foo", - JsonValue.from("string"), - ) - .build() - ) - .requestContentType( - AuthProviderCreateRequest.Oauth2.UserInfoRequest - .RequestContentType - .APPLICATION_X_WWW_FORM_URLENCODED - ) - .responseContentType( - AuthProviderCreateRequest.Oauth2.UserInfoRequest - .ResponseContentType - .APPLICATION_X_WWW_FORM_URLENCODED - ) - .responseMap( - AuthProviderCreateRequest.Oauth2.UserInfoRequest - .ResponseMap - .builder() - .putAdditionalProperty( - "foo", - JsonValue.from("string"), - ) - .build() - ) + .requestContentType( + AuthProviderCreateRequest.Oauth2.TokenIntrospectionRequest + .RequestContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseContentType( + AuthProviderCreateRequest.Oauth2.TokenIntrospectionRequest + .ResponseContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseMap( + AuthProviderCreateRequest.Oauth2.TokenIntrospectionRequest + .ResponseMap + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .build() + ) + .tokenRequest( + AuthProviderCreateRequest.Oauth2.TokenRequest.builder() + .endpoint("endpoint") + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .method("method") + .params( + AuthProviderCreateRequest.Oauth2.TokenRequest.Params + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .requestContentType( + AuthProviderCreateRequest.Oauth2.TokenRequest + .RequestContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseContentType( + AuthProviderCreateRequest.Oauth2.TokenRequest + .ResponseContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseMap( + AuthProviderCreateRequest.Oauth2.TokenRequest.ResponseMap + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .build() + ) + .userInfoRequest( + AuthProviderCreateRequest.Oauth2.UserInfoRequest.builder() + .endpoint("endpoint") + .triggers( + AuthProviderCreateRequest.Oauth2.UserInfoRequest.Triggers + .builder() + .onTokenGrant(true) + .onTokenRefresh(true) + .build() + ) + .authHeaderValueFormat("auth_header_value_format") + .authMethod("auth_method") + .method("method") + .params( + AuthProviderCreateRequest.Oauth2.UserInfoRequest.Params + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build() + ) + .requestContentType( + AuthProviderCreateRequest.Oauth2.UserInfoRequest + .RequestContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseContentType( + AuthProviderCreateRequest.Oauth2.UserInfoRequest + .ResponseContentType + .APPLICATION_X_WWW_FORM_URLENCODED + ) + .responseMap( + AuthProviderCreateRequest.Oauth2.UserInfoRequest.ResponseMap + .builder() + .putAdditionalProperty("foo", JsonValue.from("string")) .build() ) .build() ) - .providerId("provider_id") - .status("status") - .type("type") .build() ) + .providerId("provider_id") + .status("status") + .type("type") .build() ) - println(authProviderResponse) + authProviderResponse.validate() } @Test - fun callList() { + fun list() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val authProviderService = client.admin().authProviders() - val adminAuthProviderListResponse = - authProviderService.list(AdminAuthProviderListParams.builder().build()) - println(adminAuthProviderListResponse) - adminAuthProviderListResponse.validate() + + val authProviders = authProviderService.list() + + authProviders.validate() } @Test - fun callDelete() { + fun delete() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val authProviderService = client.admin().authProviders() - val authProviderResponse = - authProviderService.delete(AdminAuthProviderDeleteParams.builder().id("id").build()) - println(authProviderResponse) + + val authProviderResponse = authProviderService.delete("id") + authProviderResponse.validate() } @Test - fun callGet() { + fun get() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val authProviderService = client.admin().authProviders() - val authProviderResponse = - authProviderService.get(AdminAuthProviderGetParams.builder().id("id").build()) - println(authProviderResponse) + + val authProviderResponse = authProviderService.get("id") + authProviderResponse.validate() } @Test - fun callPatch() { + fun patch() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val authProviderService = client.admin().authProviders() + val authProviderResponse = authProviderService.patch( - AdminAuthProviderPatchParams.builder() - .id("id") + AuthProviderPatchParams.builder() + .pathId("id") .authProviderUpdateRequest( AuthProviderUpdateRequest.builder() .id("id") @@ -416,7 +367,7 @@ class AuthProviderServiceTest { .build() ) .scopeDelimiter( - AuthProviderUpdateRequest.Oauth2.ScopeDelimiter.Unknown1 + AuthProviderUpdateRequest.Oauth2.ScopeDelimiter.Unknown2 ) .tokenRequest( AuthProviderUpdateRequest.Oauth2.TokenRequest.builder() @@ -510,7 +461,7 @@ class AuthProviderServiceTest { ) .build() ) - println(authProviderResponse) + authProviderResponse.validate() } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/admin/SecretServiceTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/admin/SecretServiceTest.kt index d4f8edc..88a1519 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/admin/SecretServiceTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/admin/SecretServiceTest.kt @@ -4,56 +4,57 @@ package dev.arcade.services.blocking.admin import dev.arcade.TestServerExtension import dev.arcade.client.okhttp.ArcadeOkHttpClient -import dev.arcade.models.AdminSecretCreateParams -import dev.arcade.models.AdminSecretDeleteParams -import dev.arcade.models.AdminSecretListParams +import dev.arcade.models.admin.secrets.SecretCreateParams import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class SecretServiceTest { +internal class SecretServiceTest { @Test - fun callCreate() { + fun create() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val secretService = client.admin().secrets() + val secretResponse = secretService.create( - AdminSecretCreateParams.builder() + SecretCreateParams.builder() .secretKey("secret_key") .value("value") .description("description") .build() ) - println(secretResponse) + secretResponse.validate() } @Test - fun callList() { + fun list() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val secretService = client.admin().secrets() - val adminSecretListResponse = secretService.list(AdminSecretListParams.builder().build()) - println(adminSecretListResponse) - adminSecretListResponse.validate() + + val secrets = secretService.list() + + secrets.validate() } @Test - fun callDelete() { + fun delete() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val secretService = client.admin().secrets() - secretService.delete(AdminSecretDeleteParams.builder().secretId("secret_id").build()) + + secretService.delete("secret_id") } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/admin/UserConnectionServiceTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/admin/UserConnectionServiceTest.kt index 286ac44..462076c 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/admin/UserConnectionServiceTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/admin/UserConnectionServiceTest.kt @@ -4,36 +4,35 @@ package dev.arcade.services.blocking.admin import dev.arcade.TestServerExtension import dev.arcade.client.okhttp.ArcadeOkHttpClient -import dev.arcade.models.AdminUserConnectionDeleteParams -import dev.arcade.models.AdminUserConnectionListParams import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class UserConnectionServiceTest { +internal class UserConnectionServiceTest { @Test - fun callList() { + fun list() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val userConnectionService = client.admin().userConnections() - val schemasOffsetPageSchemasUserAuthProviderConnectionResponse = - userConnectionService.list(AdminUserConnectionListParams.builder().build()) - println(schemasOffsetPageSchemasUserAuthProviderConnectionResponse) - schemasOffsetPageSchemasUserAuthProviderConnectionResponse.items().forEach { it.validate() } + + val page = userConnectionService.list() + + page.response().validate() } @Test - fun callDelete() { + fun delete() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val userConnectionService = client.admin().userConnections() - userConnectionService.delete(AdminUserConnectionDeleteParams.builder().id("id").build()) + + userConnectionService.delete("id") } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/chat/CompletionServiceTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/chat/CompletionServiceTest.kt index 1bb2b7c..b0212b8 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/chat/CompletionServiceTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/chat/CompletionServiceTest.kt @@ -5,82 +5,76 @@ package dev.arcade.services.blocking.chat import dev.arcade.TestServerExtension import dev.arcade.client.okhttp.ArcadeOkHttpClient import dev.arcade.core.JsonValue -import dev.arcade.models.ChatCompletionCreateParams -import dev.arcade.models.ChatMessage -import dev.arcade.models.ChatRequest +import dev.arcade.models.chat.ChatMessage +import dev.arcade.models.chat.ChatRequest import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class CompletionServiceTest { +internal class CompletionServiceTest { @Test - fun callCreate() { + fun create() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val completionService = client.chat().completions() + val chatResponse = completionService.create( - ChatCompletionCreateParams.builder() - .chatRequest( - ChatRequest.builder() - .frequencyPenalty(0.0) - .logitBias( - ChatRequest.LogitBias.builder() - .putAdditionalProperty("foo", JsonValue.from(0)) - .build() - ) - .logprobs(true) - .maxTokens(0L) - .addMessage( - ChatMessage.builder() - .content("content") - .role("role") - .name("name") - .toolCallId("tool_call_id") - .addToolCall( - ChatMessage.ToolCall.builder() - .id("id") - .function( - ChatMessage.ToolCall.Function.builder() - .arguments("arguments") - .name("name") - .build() - ) - .type(ChatMessage.ToolCall.Type.FUNCTION) + ChatRequest.builder() + .frequencyPenalty(0.0) + .logitBias( + ChatRequest.LogitBias.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .logprobs(true) + .maxTokens(0L) + .addMessage( + ChatMessage.builder() + .content("content") + .role("role") + .name("name") + .toolCallId("tool_call_id") + .addToolCall( + ChatMessage.ToolCall.builder() + .id("id") + .function( + ChatMessage.ToolCall.Function.builder() + .arguments("arguments") + .name("name") .build() ) + .type(ChatMessage.ToolCall.Type.FUNCTION) .build() ) - .model("model") - .n(0L) - .parallelToolCalls(true) - .presencePenalty(0.0) - .responseFormat( - ChatRequest.ResponseFormat.builder() - .type(ChatRequest.ResponseFormat.Type.JSON_OBJECT) - .build() - ) - .seed(0L) - .addStop("string") - .stream(true) - .streamOptions( - ChatRequest.StreamOptions.builder().includeUsage(true).build() - ) - .temperature(0.0) - .toolChoice(JsonValue.from(mapOf())) - .tools(JsonValue.from(mapOf())) - .topLogprobs(0L) - .topP(0.0) - .user("user") .build() ) + .model("model") + .n(0L) + .parallelToolCalls(true) + .presencePenalty(0.0) + .responseFormat( + ChatRequest.ResponseFormat.builder() + .type(ChatRequest.ResponseFormat.Type.JSON_OBJECT) + .build() + ) + .seed(0L) + .addStop("string") + .stream(true) + .streamOptions(ChatRequest.StreamOptions.builder().includeUsage(true).build()) + .temperature(0.0) + .toolChoice(JsonValue.from(mapOf())) + .tools(JsonValue.from(mapOf())) + .topLogprobs(0L) + .topP(0.0) + .user("user") .build() ) - println(chatResponse) + chatResponse.validate() } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/tools/FormattedServiceTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/tools/FormattedServiceTest.kt index f1b9465..581bd41 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/tools/FormattedServiceTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/tools/FormattedServiceTest.kt @@ -4,43 +4,41 @@ package dev.arcade.services.blocking.tools import dev.arcade.TestServerExtension import dev.arcade.client.okhttp.ArcadeOkHttpClient -import dev.arcade.models.ToolFormattedGetParams -import dev.arcade.models.ToolFormattedListParams +import dev.arcade.models.tools.formatted.FormattedGetParams import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class FormattedServiceTest { +internal class FormattedServiceTest { @Test - fun callList() { + fun list() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val formattedService = client.tools().formatted() - val schemasOffsetPageAny = formattedService.list(ToolFormattedListParams.builder().build()) - println(schemasOffsetPageAny) - schemasOffsetPageAny.items().forEach { it.validate() } + + val page = formattedService.list() + + page.response().validate() } @Test - fun callGet() { + fun get() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val formattedService = client.tools().formatted() - val toolFormattedGetResponse = + + val formatted = formattedService.get( - ToolFormattedGetParams.builder() - .name("name") - .format("format") - .userId("user_id") - .build() + FormattedGetParams.builder().name("name").format("format").userId("user_id").build() ) - println(toolFormattedGetResponse) + + formatted.validate() } } diff --git a/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/tools/ScheduledServiceTest.kt b/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/tools/ScheduledServiceTest.kt index f2207e0..47ae212 100644 --- a/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/tools/ScheduledServiceTest.kt +++ b/arcade-java-core/src/test/kotlin/dev/arcade/services/blocking/tools/ScheduledServiceTest.kt @@ -4,39 +4,37 @@ package dev.arcade.services.blocking.tools import dev.arcade.TestServerExtension import dev.arcade.client.okhttp.ArcadeOkHttpClient -import dev.arcade.models.ToolScheduledGetParams -import dev.arcade.models.ToolScheduledListParams import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class ScheduledServiceTest { +internal class ScheduledServiceTest { @Test - fun callList() { + fun list() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val scheduledService = client.tools().scheduled() - val schemasOffsetPageSchemasToolExecutionListResponse = - scheduledService.list(ToolScheduledListParams.builder().build()) - println(schemasOffsetPageSchemasToolExecutionListResponse) - schemasOffsetPageSchemasToolExecutionListResponse.items().forEach { it.validate() } + + val page = scheduledService.list() + + page.response().validate() } @Test - fun callGet() { + fun get() { val client = ArcadeOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val scheduledService = client.tools().scheduled() - val toolScheduledGetResponse = - scheduledService.get(ToolScheduledGetParams.builder().id("id").build()) - println(toolScheduledGetResponse) - toolScheduledGetResponse.validate() + + val scheduled = scheduledService.get("id") + + scheduled.validate() } } diff --git a/arcade-java-example/build.gradle.kts b/arcade-java-example/build.gradle.kts index f7b2eaf..c5e56bc 100644 --- a/arcade-java-example/build.gradle.kts +++ b/arcade-java-example/build.gradle.kts @@ -1,18 +1,50 @@ plugins { - id("arcade.kotlin") - id("java") + id("arcade.java") + id("io.spring.dependency-management") version "1.1.7" // only needed for SpringBoot examples application } +repositories { + mavenCentral() +} + dependencies { implementation(project(":arcade-java")) + + // Only needed for SpringBootExample + implementation(project(":arcade-spring-boot-starter")) + implementation("org.springframework.boot:spring-boot-starter:3.5.10") + + // only needed for SpringAIExample + implementation("org.springframework.ai:spring-ai-starter-model-openai") + implementation("org.apache.httpcomponents.client5:httpclient5:5.6") + + // Only needed for GmailExample + implementation("com.google.api-client:google-api-client:2.9.0") + implementation("com.google.oauth-client:google-oauth-client-jetty:1.39.0") + implementation("com.google.apis:google-api-services-gmail:v1-rev20260112-2.0.0") + +} + +// only needed for SpringAIExample +dependencyManagement { + imports { + mavenBom("org.springframework.ai:spring-ai-bom:1.1.2") + } } tasks.withType().configureEach { // Allow using more modern APIs, like `List.of` and `Map.of`, in examples. - options.release.set(9) + options.release.set(17) } application { - mainClass = "dev.arcade.example.Main" + // Use `./gradlew :arcade-java-example:run` to run `Main` + // Use `./gradlew :arcade-java-example:run -Pexample=Something` to run `SomethingExample` + mainClass = "dev.arcade.example.${ + if (project.hasProperty("example")) + "${project.property("example")}Example" + else + "Main" + }" } diff --git a/arcade-java-example/src/main/java/dev/arcade/example/AuthExample.java b/arcade-java-example/src/main/java/dev/arcade/example/AuthExample.java new file mode 100644 index 0000000..acf0d59 --- /dev/null +++ b/arcade-java-example/src/main/java/dev/arcade/example/AuthExample.java @@ -0,0 +1,34 @@ +package dev.arcade.example; + +import dev.arcade.client.ArcadeClient; +import dev.arcade.client.okhttp.ArcadeOkHttpClient; +import dev.arcade.models.AuthorizationResponse; +import java.util.List; + +public class AuthExample { + + public static void main(String[] args) { + + // As the developer, you must identify the user you're authorizing + // and pass a unique identifier for them (e.g. an email or user ID) to Arcade: + String userId = System.getenv("ARCADE_USER_ID"); + if (userId == null) { + throw new IllegalArgumentException("Missing environment variable ARCADE_USER_ID"); + } + + ArcadeClient client = ArcadeOkHttpClient.builder().fromEnv().build(); + + // get the auth service, and call start + AuthorizationResponse authResponse = client.auth().start(userId, "github", "oauth2", List.of("repo")); + + // check the response status + authResponse + .status() + .filter(status -> status != AuthorizationResponse.Status.COMPLETED) + .flatMap(status -> authResponse.url()) + .ifPresent(url -> System.out.println("Click this link to authorize: " + url)); + + // if the authorization is NOT complete, you can wait using the following method (for CLI applications): + client.auth().waitForCompletion(authResponse); + } +} diff --git a/arcade-java-example/src/main/java/dev/arcade/example/GmailExample.java b/arcade-java-example/src/main/java/dev/arcade/example/GmailExample.java new file mode 100644 index 0000000..b4120ab --- /dev/null +++ b/arcade-java-example/src/main/java/dev/arcade/example/GmailExample.java @@ -0,0 +1,65 @@ +package dev.arcade.example; + +import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; +import com.google.api.client.http.HttpTransport; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.JsonFactory; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.gmail.Gmail; +import com.google.api.services.gmail.model.Message; +import dev.arcade.client.ArcadeClient; +import dev.arcade.client.okhttp.ArcadeOkHttpClient; +import dev.arcade.models.AuthorizationContext; +import dev.arcade.models.AuthorizationResponse; +import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class GmailExample { + + private static final Logger logger = LoggerFactory.getLogger(GmailExample.class); + + public static void main(String[] args) throws Exception { + + // As the developer, you must identify the user you're authorizing + // and pass a unique identifier for them (e.g. an email or user ID) to Arcade: + String userId = System.getenv("ARCADE_USER_ID"); + if (userId == null) { + throw new IllegalArgumentException("Missing environment variable ARCADE_USER_ID"); + } + + ArcadeClient client = ArcadeOkHttpClient.fromEnv(); + + // get the auth service and call start + AuthorizationResponse authResponse = client.auth() + .start(userId, "google", "oauth2", List.of("https://www.googleapis.com/auth/gmail.readonly")); + + // check the response status + authResponse + .status() + .filter(status -> status != AuthorizationResponse.Status.COMPLETED) + .flatMap(status -> authResponse.url()) + .ifPresent(url -> logger.info("Click this link to authorize: {}", url)); + + // if the authorization is NOT complete, you can wait using the following method (for CLI applications): + AuthorizationResponse completedAuthResponse = client.auth().waitForCompletion(authResponse); + + // Use the credential + String token = completedAuthResponse + .context() + .flatMap(AuthorizationContext::token) + .get(); + + JsonFactory jsonFactory = GsonFactory.getDefaultInstance(); + HttpTransport httpTransport = new NetHttpTransport(); + GoogleCredential credential = new GoogleCredential().setAccessToken(token); + + Gmail gmail = new Gmail.Builder(httpTransport, jsonFactory, credential) + .setApplicationName("Your Application Name") + .build(); + + // List email messages + List messages = gmail.users().messages().list("me").execute().getMessages(); + logger.info("Messages: {}", messages); + } +} diff --git a/arcade-java-example/src/main/java/dev/arcade/example/PlaySpotifyExample.java b/arcade-java-example/src/main/java/dev/arcade/example/PlaySpotifyExample.java new file mode 100644 index 0000000..8433ecb --- /dev/null +++ b/arcade-java-example/src/main/java/dev/arcade/example/PlaySpotifyExample.java @@ -0,0 +1,42 @@ +package dev.arcade.example; + +import dev.arcade.client.ArcadeClient; +import dev.arcade.client.okhttp.ArcadeOkHttpClient; +import dev.arcade.models.tools.ExecuteToolRequest; +import dev.arcade.models.tools.ExecuteToolResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Example of calling a tool using the Arcade Java SDK. + *

+ * Both the {@code ARCADE_USER_ID} and {@code ARCADE_API_KEY} environment variables must be set. + * See the Getting Your API Key guide to create an API Key. + * Your username can be found in the lower left corner of your Arcade console. + */ +public class PlaySpotifyExample { + + private static final Logger logger = LoggerFactory.getLogger(PlaySpotifyExample.class); + + public static void main(String[] args) { + + String userId = System.getenv("ARCADE_USER_ID"); // the Spotify tool requires a userId + if (userId == null) { + throw new IllegalArgumentException("ARCADE_USER_ID and ARCADE_API_KEY environment variables must be set"); + } + + // Configures using the `ARCADE_API_KEY` environment variable + ArcadeClient client = ArcadeOkHttpClient.fromEnv(); + + ExecuteToolResponse response = client.tools() + .execute(ExecuteToolRequest.builder() + .toolName("Spotify.ResumePlayback@1.0.2") + .userId(userId) + .build()); + + response.output() + .ifPresentOrElse( + output -> logger.info("Tool output: {}", output._value()), + () -> logger.info("No output for this tool")); + } +} diff --git a/arcade-java-example/src/main/java/dev/arcade/example/QuickStartExample.java b/arcade-java-example/src/main/java/dev/arcade/example/QuickStartExample.java new file mode 100644 index 0000000..4bad391 --- /dev/null +++ b/arcade-java-example/src/main/java/dev/arcade/example/QuickStartExample.java @@ -0,0 +1,126 @@ +package dev.arcade.example; + +import dev.arcade.client.ArcadeClient; +import dev.arcade.client.okhttp.ArcadeOkHttpClient; +import dev.arcade.core.JsonValue; +import dev.arcade.models.AuthorizationResponse; +import dev.arcade.models.tools.AuthorizeToolRequest; +import dev.arcade.models.tools.ExecuteToolRequest; +import dev.arcade.models.tools.ExecuteToolResponse.Output; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class QuickStartExample { + + private static final Logger logger = LoggerFactory.getLogger(QuickStartExample.class); + + public static void main(String[] args) { + + // You can also set the `ARCADE_API_KEY` environment variable instead of passing it as a + // parameter by using ArcadeOkHttpClient.fromEnv(). + ArcadeClient client = + ArcadeOkHttpClient.builder().apiKey("{arcade_api_key}").build(); + + // Arcade needs a unique identifier for your application user (this could be an email address, a UUID, etc). + // In this example, use the email you used to sign up for Arcade.dev: + String userId = "{arcade_user_id}"; + + Map searchResult = authorizeAndRunTool( + client, "GoogleNews.SearchNewsStories", Map.of("keywords", "MCP URL mode elicitation"), userId); + + // Extract the list of news results from the tool output + List news = searchResult + .getOrDefault("news_results", JsonValue.from(List.of())) + .toListOrEmpty(); + + String output = "latest news about MCP URL mode elicitation:\n" + + news.stream() + .map(item -> { + Map newsItem = item.toMapOrEmpty(); + return newsItem.get("source").asStringOrThrow() + " - " + + newsItem.get("title").asStringOrThrow() + "\n" + + newsItem.get("link").asStringOrThrow() + "\n\n"; + }) + .collect(Collectors.joining("\n")); + + // Create a Google Doc with the news results + // If the user has not previously authorized the Google Docs tool, they will be prompted to authorize the tool + // call. + Map createDocResult = authorizeAndRunTool( + client, + "GoogleDocs.CreateDocumentFromText", + Map.of("title", "News about MCP URL mode elicitation", "text_content", output), + userId); + + String googleDocUrl = createDocResult.get("documentUrl").asStringOrThrow(); + + String emailBody = + "You can find the news about MCP URL mode elicitation in the following Google Doc: " + googleDocUrl; + + Map sendEmailResult = authorizeAndRunTool( + client, + "Gmail.SendEmail", + Map.of("recipient", userId, "subject", "News about MCP URL mode elicitation", "body", emailBody), + userId); + + // Print the response from the tool call + logger.info( + """ + Success! Check your email at {} + + You just chained 3 tools together: + 1. Searched Google News for stories about MCP URL mode elicitation + 2. Created a Google Doc with the results + 3. Sent yourself an email with the document link + + Email metadata: {} + """, + userId, + sendEmailResult); + } + + /** + * Authorize (if needed) and execute a tool, returning the output as a Map. + */ + public static Map authorizeAndRunTool( + ArcadeClient client, String toolName, Map input, String userId) { + // Start the authorization process + AuthorizationResponse authResponse = client.tools() + .authorize(AuthorizeToolRequest.builder() + .toolName(toolName) + .userId(userId) + .build()); + + // If the authorization is not completed, print the authorization URL and wait for the user to authorize the + // app. + // Tools that do not require authorization will have the status "completed" already. + authResponse + .status() + .filter(status -> status != AuthorizationResponse.Status.COMPLETED) + .flatMap(status -> authResponse.url()) + .ifPresent(url -> logger.info( + """ + Click this link to authorize {}: + {}. + The process will continue once you have authorized the app. + """, + toolName, + url)); + client.auth().waitForCompletion(authResponse); + + // Execute the tool and extract the output as a Map + return client.tools() + .execute(ExecuteToolRequest.builder() + .toolName(toolName) + .input(input) + .userId(userId) + .includeErrorStacktrace(true) + .build()) + .output() + .flatMap(Output::valueAsObject) + .orElse(Map.of()); + } +} diff --git a/arcade-java-example/src/main/java/dev/arcade/example/springai/SpringAIExample.java b/arcade-java-example/src/main/java/dev/arcade/example/springai/SpringAIExample.java new file mode 100644 index 0000000..2b4a6b7 --- /dev/null +++ b/arcade-java-example/src/main/java/dev/arcade/example/springai/SpringAIExample.java @@ -0,0 +1,199 @@ +package dev.arcade.example.springai; + +import dev.arcade.client.ArcadeClient; +import dev.arcade.models.AuthorizationResponse; +import dev.arcade.models.tools.AuthorizeToolRequest; +import dev.arcade.models.tools.ExecuteToolRequest; +import dev.arcade.models.tools.ExecuteToolResponse; +import java.util.Map; +import java.util.Optional; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.ai.chat.client.ChatClient; +import org.springframework.ai.tool.annotation.Tool; +import org.springframework.ai.tool.annotation.ToolParam; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.stereotype.Service; + +@SpringBootApplication +public class SpringAIExample { + + private static final String SYSTEM_PROMPT = + """ + You are a specialized Music Assistant with access to two MCP tools: get_spotify_state and play_song. + Your goal is to provide a seamless, proactive audio experience. Follow these operational guidelines: + Context Awareness: Before playing any music, always use get_spotify_state to see if music is already playing. If it is, acknowledge what is currently playing before switching to the new track. + Proactive Assistance: If the user asks for a song and Spotify is currently paused, inform the user you are resuming playback or starting the session for them. + Error Handling: If a song fails to play or the tool returns an error, check the state again to see if the player is disconnected or if the track simply wasn't found. + Tone: Be concise, upbeat, and music-focused. + Chain of Thought: When a user asks for a song, your internal logic should be: Check State -> Inform User -> Execute Play. + """; + + public static void main(String[] args) { + SpringApplication.run(SpringAIExample.class, args); + } + + @Bean + ApplicationRunner runner(ChatClient.Builder chatClientBuilder, ArcadeToolProvider arcadeToolProvider) { + return args -> { + ChatClient chatClient = chatClientBuilder + .defaultSystem(SYSTEM_PROMPT) + .defaultTools(arcadeToolProvider) // see below, each tool is annotated with @Tool + .build(); + + String summary = chatClient + .prompt() + .user("If my music is not currently playing, play something to get me in the mood to write code.") + .call() + .content(); + + System.out.println(summary); + }; + } + + /** + * Exposes Arcade Tools to Spring AI. + */ + @Service + public static class ArcadeToolProvider { + private final Logger log = LoggerFactory.getLogger(ArcadeToolProvider.class); + private final ArcadeClient client; + private final String userId; + + ArcadeToolProvider(ArcadeClient client, @Value("${arcade.user-id}") String userId) { + this.client = client; + this.userId = userId; + } + + /** + * Exposes an Arcade Tool call to Spotify.GetPlaybackState, using Spring AI annotations. + * + * @return A string object of the playback state. + */ + @Tool( + name = "play_song", + description = "Plays a song by an artist and queues four more songs by the same artist") + String play(@ToolParam(description = "The name of the artist to play") String name) { + return executeTool("Spotify.PlayArtistByName", Map.of("name", name)); + } + + /** + * Exposes an Arcade Tool call to Spotify.GetPlaybackState, using Spring AI annotations. + * + * @return A string object of the playback state. + */ + @Tool( + name = "get_spotify_state", + description = + """ + Get information about the user's current playback state, + including track or episode, and active device. + This tool does not perform any actions. Use other tools to control playback. + """) + String playbackState() { + return executeTool("Spotify.GetPlaybackState", Map.of()); + } + + /** + * Executes the specified tool with the provided input. Handles authorization and errors. + * + * @param toolName the name of the tool to be executed + * @param input the input parameters required for tool execution + * @return the result of the tool execution as a string; the result may include + * the output of the tool, an error message, or an authorization requirement + */ + private String executeTool(String toolName, Map input) { + log.debug("Executing tool {}, with input: {}", toolName, input); + try { + ExecuteToolResponse response = client.tools() + .execute(ExecuteToolRequest.builder() + .toolName(toolName) + .userId(userId) + .input(input) + .build()); + + log.debug( + "Tool {} executed, with a status of '{}'", + toolName, + response.status().orElse(null)); + + // process the result + if (response.success().orElse(false)) { + String result = + response.output().map(o -> o._value().toString()).orElse("{}"); + log.debug("Tool {} returned: {}", toolName, result); + return result; + } + + Optional error = + response.output().flatMap(ExecuteToolResponse.Output::error); + + if (error.isPresent()) { + String errorMessage = error.get().message(); + + if (errorMessage.contains("authorization required")) { + AuthorizationResult auth = requestAuthorization(toolName); + if (auth.requiresAction()) { + log.debug("Tool {} requires authorization, open a browser to {}", toolName, auth.url()); + return String.format( + "The '%s' tool requires authorization, open a browser to %s to continue.", + toolName, auth.url()); + } + } + log.warn("Tool {} returned an error: {}", toolName, errorMessage); + return "Error: " + errorMessage; + } + + return "Error: Tool execution failed"; + } catch (Exception e) { + String message = e.getMessage(); + if (message != null && message.contains("authorization")) { + AuthorizationResult auth = requestAuthorization(toolName); + if (auth.requiresAction()) { + log.debug("Tool {} requires authorization, open a browser to {}", toolName, auth.url()); + return String.format( + "The '%s' tool requires authorization, open a browser to %s to continue.", + toolName, auth.url()); + } + } + log.error("Tool execution failed for {}: {}", toolName, message); + return "Error: " + message; + } + } + + /** + * Requests authorization for a tool and returns the OAuth URL. + */ + public AuthorizationResult requestAuthorization(String toolName) { + try { + AuthorizationResponse response = client.tools() + .authorize(AuthorizeToolRequest.builder() + .toolName(toolName) + .userId(userId) + .build()); + + Optional url = response.url(); + String statusValue = + response.status().map(s -> s.value().name()).orElse("unknown"); + + if ("PENDING".equalsIgnoreCase(statusValue) && url.isPresent()) { + return new AuthorizationResult(toolName, url.get(), statusValue); + } + return new AuthorizationResult(toolName, null, statusValue); + } catch (Exception e) { + log.error("Failed to request authorization for {}: {}", toolName, e.getMessage()); + return new AuthorizationResult(toolName, null, "error: " + e.getMessage()); + } + } + + public record AuthorizationResult(String toolName, String url, String status) { + public boolean requiresAction() { + return url != null && "PENDING".equalsIgnoreCase(status); + } + } + } +} diff --git a/arcade-java-example/src/main/java/dev/arcade/example/springboot/SpringBootExample.java b/arcade-java-example/src/main/java/dev/arcade/example/springboot/SpringBootExample.java new file mode 100644 index 0000000..61b7bd6 --- /dev/null +++ b/arcade-java-example/src/main/java/dev/arcade/example/springboot/SpringBootExample.java @@ -0,0 +1,57 @@ +package dev.arcade.example.springboot; + +import dev.arcade.client.ArcadeClient; +import dev.arcade.models.tools.ExecuteToolRequest; +import dev.arcade.models.tools.ExecuteToolResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.ApplicationRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; + +/** + * Example of calling a tool using the Arcade Java SDK with Spring Boot. + *

+ * The {@code ArcadeClient} bean is auto-configured when the {@code ARCADE_API_KEY} environment variable + * (or equivalent {@code application.properties} value) is set. + */ +@SpringBootApplication +public class SpringBootExample { + + private static final Logger logger = LoggerFactory.getLogger(SpringBootExample.class); + + /** + * Starts the Spring Boot application. + * @param args All args are passed into the SpringApplication + */ + public static void main(String[] args) { + SpringApplication.run(SpringBootExample.class, args); + } + + /** + * Injects an ArcadeClient, and returns an ApplicationRunner that makes a tool call. + * @param client Arcade Client is autoinjected if ARCADE_API_KEY, or equivalent application.properties var is set. + * @return Runs code on application start. + */ + @Bean + ApplicationRunner appRunner(ArcadeClient client) { + return args -> { + String userId = System.getenv("ARCADE_USER_ID"); // the Spotify tool requires a userId + if (userId == null) { + throw new IllegalArgumentException("Missing ARCADE_USER_ID environment variable"); + } + + ExecuteToolResponse response = client.tools() + .execute(ExecuteToolRequest.builder() + .toolName("Spotify.ResumePlayback") + .userId(userId) + .build()); + + response.output() + .ifPresentOrElse( + output -> logger.info("Tool output: {}", output._value()), + () -> logger.info("No output for this tool")); + }; + } +} diff --git a/arcade-java-example/src/main/resources/application-local.yml.template b/arcade-java-example/src/main/resources/application-local.yml.template new file mode 100644 index 0000000..16d01c1 --- /dev/null +++ b/arcade-java-example/src/main/resources/application-local.yml.template @@ -0,0 +1,15 @@ +# Local configuration - copy to application-local.yml and fill in values +# DO NOT commit application-local.yml to version control + +spring: + ai: + openai: + api-key: ${OPENAI_API_KEY:your-openai-api-key} + chat: + options: + model: gpt-4o + +arcade: + api-key: ${ARCADE_API_KEY:your-arcade-api-key} + user-id: ${ARCADE_USER_ID:your-email@example.com} + diff --git a/arcade-java-example/src/main/resources/application.yml b/arcade-java-example/src/main/resources/application.yml new file mode 100644 index 0000000..608bc63 --- /dev/null +++ b/arcade-java-example/src/main/resources/application.yml @@ -0,0 +1,8 @@ +spring: + main: + web-application-type: none + config: + import: optional:application-local.yml +logging: + level: + dev.arcade.example: DEBUG diff --git a/arcade-java-proguard-test/build.gradle.kts b/arcade-java-proguard-test/build.gradle.kts new file mode 100644 index 0000000..18783e5 --- /dev/null +++ b/arcade-java-proguard-test/build.gradle.kts @@ -0,0 +1,101 @@ +plugins { + id("arcade.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(":arcade-java")) + testImplementation(kotlin("test")) + testImplementation("org.junit.jupiter:junit-jupiter-api:5.9.3") + testImplementation("org.assertj:assertj-core:3.27.7") + testImplementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.14.0") +} + +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("../arcade-java-core/src/main/resources/META-INF/proguard/arcade-java-core.pro") +} + +val testProGuard by tasks.registering(JavaExec::class) { + group = "verification" + dependsOn(proguardJar) + notCompatibleWithConfigurationCache("ProGuard") + + mainClass.set("dev.arcade.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", "../arcade-java-core/src/main/resources/META-INF/proguard/arcade-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("dev.arcade.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/arcade-java-proguard-test/src/test/kotlin/dev/arcade/proguard/ProGuardCompatibilityTest.kt b/arcade-java-proguard-test/src/test/kotlin/dev/arcade/proguard/ProGuardCompatibilityTest.kt new file mode 100644 index 0000000..95ef6e2 --- /dev/null +++ b/arcade-java-proguard-test/src/test/kotlin/dev/arcade/proguard/ProGuardCompatibilityTest.kt @@ -0,0 +1,77 @@ +// File generated from our OpenAPI spec by Stainless. + +package dev.arcade.proguard + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import dev.arcade.client.okhttp.ArcadeOkHttpClient +import dev.arcade.core.jsonMapper +import dev.arcade.models.tools.AuthorizeToolRequest +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/arcade-java-core.pro") + + assertThat(rulesFile).isNotNull() + } + + @Test + fun client() { + val client = ArcadeOkHttpClient.builder().apiKey("My API Key").build() + + assertThat(client).isNotNull() + assertThat(client.admin()).isNotNull() + assertThat(client.auth()).isNotNull() + assertThat(client.health()).isNotNull() + assertThat(client.chat()).isNotNull() + assertThat(client.tools()).isNotNull() + assertThat(client.workers()).isNotNull() + } + + @Test + fun authorizeToolRequestRoundtrip() { + val jsonMapper = jsonMapper() + val authorizeToolRequest = + AuthorizeToolRequest.builder() + .toolName("tool_name") + .nextUri("next_uri") + .toolVersion("tool_version") + .userId("user_id") + .build() + + val roundtrippedAuthorizeToolRequest = + jsonMapper.readValue( + jsonMapper.writeValueAsString(authorizeToolRequest), + jacksonTypeRef(), + ) + + assertThat(roundtrippedAuthorizeToolRequest).isEqualTo(authorizeToolRequest) + } +} diff --git a/arcade-java-proguard-test/test.pro b/arcade-java-proguard-test/test.pro new file mode 100644 index 0000000..58d68c5 --- /dev/null +++ b/arcade-java-proguard-test/test.pro @@ -0,0 +1,9 @@ +# Specify the entrypoint where ProGuard starts to determine what's reachable. +-keep class dev.arcade.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/arcade-java/build.gradle.kts b/arcade-java/build.gradle.kts index dc7d5e0..9a4d64f 100644 --- a/arcade-java/build.gradle.kts +++ b/arcade-java/build.gradle.kts @@ -6,3 +6,24 @@ plugins { dependencies { api(project(":arcade-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/arcade-spring-boot-starter/build.gradle.kts b/arcade-spring-boot-starter/build.gradle.kts new file mode 100644 index 0000000..6212eba --- /dev/null +++ b/arcade-spring-boot-starter/build.gradle.kts @@ -0,0 +1,32 @@ +import org.jetbrains.kotlin.gradle.dsl.JvmTarget +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +plugins { + id("arcade.kotlin") + id("arcade.publish") +} + +dependencies { + api(project(":arcade-java")) + implementation("org.springframework.boot:spring-boot-starter:3.5.10") +} + +tasks.withType().configureEach { + // Allow using more modern APIs, like `List.of` and `Map.of`, in examples. + options.release.set(17) +} + +tasks.withType { + compilerOptions { + freeCompilerArgs = listOf( + "-Xjvm-default=all", + "-Xjdk-release=17", + // 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_17) + } +} + + diff --git a/arcade-spring-boot-starter/src/main/java/dev/arcade/springboot/ArcadeAutoConfiguration.kt b/arcade-spring-boot-starter/src/main/java/dev/arcade/springboot/ArcadeAutoConfiguration.kt new file mode 100644 index 0000000..3522df1 --- /dev/null +++ b/arcade-spring-boot-starter/src/main/java/dev/arcade/springboot/ArcadeAutoConfiguration.kt @@ -0,0 +1,41 @@ +package dev.arcade.springboot + +import dev.arcade.client.ArcadeClient +import dev.arcade.client.okhttp.ArcadeOkHttpClient +import dev.arcade.core.ClientOptions +import org.springframework.boot.autoconfigure.AutoConfiguration +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty +import org.springframework.boot.context.properties.ConfigurationProperties +import org.springframework.boot.context.properties.EnableConfigurationProperties +import org.springframework.context.annotation.Bean +import org.springframework.util.StringUtils + +@AutoConfiguration +@EnableConfigurationProperties(ArcadeAutoConfiguration.Config::class) +open class ArcadeAutoConfiguration { + + @Bean + @ConditionalOnMissingBean + @ConditionalOnProperty(prefix = "arcade", name = ["api-key"]) + open fun arcadeClient(config: Config): ArcadeClient { + val clientBuilder = ArcadeOkHttpClient.builder().fromEnv() + + if (config.apiKey != null && StringUtils.hasText(config.apiKey)) { + clientBuilder.apiKey(config.apiKey) + } + + if (config.baseUrl != null && StringUtils.hasText(config.baseUrl)) { + clientBuilder.baseUrl(config.baseUrl) + } + + return clientBuilder.build() + } + + @ConfigurationProperties(prefix = "arcade") + @JvmRecord + data class Config( + val apiKey: String? = System.getenv("ARCADE_API_KEY"), + val baseUrl: String? = ClientOptions.PRODUCTION_URL, + ) {} +} diff --git a/arcade-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/arcade-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 0000000..ce3da62 --- /dev/null +++ b/arcade-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1 @@ +dev.arcade.springboot.ArcadeAutoConfiguration \ No newline at end of file diff --git a/bin/check-release-environment b/bin/check-release-environment index d9fa0bc..3a6a7b4 100644 --- a/bin/check-release-environment +++ b/bin/check-release-environment @@ -3,19 +3,19 @@ errors=() if [ -z "${SONATYPE_USERNAME}" ]; then - errors+=("The ARCADE_SONATYPE_USERNAME secret has not been set. Please set it in either this repository's secrets or your organization secrets") + 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 ARCADE_SONATYPE_PASSWORD secret has not been set. Please set it in either this repository's secrets or your organization secrets") + 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 ARCADE_SONATYPE_GPG_SIGNING_KEY secret has not been set. Please set it in either this repository's secrets or your organization secrets") + 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 ARCADE_SONATYPE_GPG_SIGNING_PASSWORD secret has not been set. Please set it in either this repository's secrets or your organization secrets") + 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[@]} diff --git a/build.gradle.kts b/build.gradle.kts index 0b8935e..0571c9c 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,5 +1,10 @@ plugins { id("io.github.gradle-nexus.publish-plugin") version "1.1.0" + id("org.jetbrains.dokka") version "2.0.0" +} + +repositories { + mavenCentral() } allprojects { @@ -7,6 +12,30 @@ allprojects { version = "0.1.0-alpha.1" // 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 != "arcade-java" && it.name == "dokkaJavadocJar" } + .forEach { mustRunAfter(it) } +} + nexusPublishing { repositories { sonatype { diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts index 4ffbf94..0b14135 100644 --- a/buildSrc/build.gradle.kts +++ b/buildSrc/build.gradle.kts @@ -1,6 +1,6 @@ plugins { `kotlin-dsl` - kotlin("jvm") version "2.1.10" + kotlin("jvm") version "1.9.20" } repositories { @@ -8,6 +8,5 @@ repositories { } dependencies { - implementation("com.diffplug.spotless:spotless-plugin-gradle:7.0.2") - implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:2.1.10") + implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:1.9.20") } diff --git a/buildSrc/src/main/kotlin/arcade.java.gradle.kts b/buildSrc/src/main/kotlin/arcade.java.gradle.kts index a816ba7..81d5d32 100644 --- a/buildSrc/src/main/kotlin/arcade.java.gradle.kts +++ b/buildSrc/src/main/kotlin/arcade.java.gradle.kts @@ -1,9 +1,7 @@ -import com.diffplug.gradle.spotless.SpotlessExtension import org.gradle.api.tasks.testing.logging.TestExceptionFormat plugins { `java-library` - id("com.diffplug.spotless") } repositories { @@ -15,19 +13,13 @@ configure { withSourcesJar() } -configure { - java { - importOrder() - removeUnusedImports() - palantirJavaFormat() - toggleOffOn() - } -} - java { toolchain { - languageVersion.set(JavaLanguageVersion.of(17)) + languageVersion.set(JavaLanguageVersion.of(21)) } + + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 } tasks.withType().configureEach { @@ -59,3 +51,86 @@ tasks.withType().configureEach { 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/arcade.kotlin.gradle.kts b/buildSrc/src/main/kotlin/arcade.kotlin.gradle.kts index 7643a47..08c21f3 100644 --- a/buildSrc/src/main/kotlin/arcade.kotlin.gradle.kts +++ b/buildSrc/src/main/kotlin/arcade.kotlin.gradle.kts @@ -1,39 +1,109 @@ -import com.diffplug.gradle.spotless.SpotlessExtension import org.jetbrains.kotlin.gradle.dsl.JvmTarget -import org.jetbrains.kotlin.gradle.tasks.KotlinCompile +import org.jetbrains.kotlin.gradle.dsl.KotlinVersion plugins { id("arcade.java") kotlin("jvm") } -kotlin { - jvmToolchain { - languageVersion.set(JavaLanguageVersion.of(17)) - } +repositories { + mavenCentral() } -configure { - kotlin { - ktfmt().kotlinlangStyle() - toggleOffOn() +kotlin { + jvmToolchain { + languageVersion.set(JavaLanguageVersion.of(21)) } -} -tasks.withType().configureEach { compilerOptions { freeCompilerArgs = listOf( - "-Xjvm-default=all", - "-Xjdk-release=1.8", - // Suppress deprecation warnings because we may still reference and test deprecated members. - "-Xsuppress-warning=DEPRECATION" + "-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" } } -// Run tests in parallel to some degree. tasks.withType().configureEach { - maxParallelForks = (Runtime.getRuntime().availableProcessors() / 2).coerceAtLeast(1) - forkEvery = 100 + systemProperty("junit.jupiter.execution.parallel.enabled", true) + systemProperty("junit.jupiter.execution.parallel.mode.default", "concurrent") + + // `SKIP_MOCK_TESTS` affects which tests run so it must be added as input for proper cache invalidation. + inputs.property("skipMockTests", System.getenv("SKIP_MOCK_TESTS")).optional(true) } + +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/arcade.publish.gradle.kts b/buildSrc/src/main/kotlin/arcade.publish.gradle.kts index d2bd07d..39290bc 100644 --- a/buildSrc/src/main/kotlin/arcade.publish.gradle.kts +++ b/buildSrc/src/main/kotlin/arcade.publish.gradle.kts @@ -40,6 +40,14 @@ configure { } } } + repositories { + if (project.hasProperty("publishLocal")) { + maven { + name = "LocalFileSystem" + url = uri("${rootProject.layout.buildDirectory.get()}/local-maven-repo") + } + } + } } signing { diff --git a/gradle.properties b/gradle.properties index 0c8d4de..6680f9c 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,5 +1,18 @@ org.gradle.caching=true +org.gradle.configuration-cache=true org.gradle.parallel=true org.gradle.daemon=false -org.gradle.jvmargs=-Xmx4g -kotlin.daemon.jvmargs=-Xmx4g +# 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/scripts/build b/scripts/build new file mode 100755 index 0000000..16a2b00 --- /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/fast-format b/scripts/fast-format new file mode 100755 index 0000000..1b3bc47 --- /dev/null +++ b/scripts/fast-format @@ -0,0 +1,46 @@ +#!/usr/bin/env bash + +set -euo pipefail + +echo "Script started with $# arguments" +echo "Arguments: $*" +echo "Script location: $(dirname "$0")" + +cd "$(dirname "$0")/.." +echo "Changed to directory: $(pwd)" + +if [ $# -eq 0 ]; then + echo "Usage: $0 [additional-formatter-args...]" + echo "The file should contain one file path per line" + exit 1 +fi + +FILE_LIST="$1" + +echo "Looking for file: $FILE_LIST" + +if [ ! -f "$FILE_LIST" ]; then + echo "Error: File '$FILE_LIST' not found" + exit 1 +fi + +if ! command -v ktfmt-fast-format &> /dev/null; then + echo "Error: ktfmt-fast-format not found" + exit 1 +fi + +# Process Kotlin files +echo "==> Looking for Kotlin files" +kt_files=$(grep -E '\.kt$' "$FILE_LIST" | grep -v './buildSrc/build/' || true) +echo "==> Done looking for Kotlin files" + +if [[ -n "$kt_files" ]]; then + echo "==> will format Kotlin files" + echo "$kt_files" | tr '\n' '\0' | xargs -0 ktfmt-fast-format --kotlinlang-style "$@" +else + echo "No Kotlin files to format -- expected outcome during incremental formatting" +fi + +# TODO(mbudayr): support palantir-java-format +# Process Java files +# grep -E '\.java$' "$FILE_LIST" | grep -v './buildSrc/build/' | tr '\n' '\0' | xargs -0 -r palantir-java-format --palantir --replace "$@" diff --git a/scripts/format b/scripts/format index 456a69d..65db176 100755 --- a/scripts/format +++ b/scripts/format @@ -4,5 +4,18 @@ set -e cd "$(dirname "$0")/.." -echo "==> Running spotlessApply" -./gradlew spotlessApply +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 index e3a5f5e..dbc8f77 100755 --- a/scripts/lint +++ b/scripts/lint @@ -4,5 +4,20 @@ set -e cd "$(dirname "$0")/.." -echo "==> Build classes" -./gradlew build testClasses -x test +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 index d2814ae..0b28f6e 100755 --- a/scripts/mock +++ b/scripts/mock @@ -21,7 +21,7 @@ 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.8.5 -- prism mock "$URL" &> .prism.log & + 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" @@ -37,5 +37,5 @@ if [ "$1" == "--daemon" ]; then echo else - npm exec --package=@stainless-api/prism-cli@5.8.5 -- prism mock "$URL" + npm exec --package=@stainless-api/prism-cli@5.15.0 -- prism mock "$URL" fi diff --git a/scripts/test b/scripts/test index 6b750a7..047bc1d 100755 --- a/scripts/test +++ b/scripts/test @@ -43,7 +43,7 @@ elif ! prism_is_running ; then 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=@stoplight/prism-cli@~5.3.2 -- prism mock path/to/your.openapi.yml${NC}" + echo -e " \$ ${YELLOW}npm exec --package=@stainless-api/prism-cli@5.15.0 -- prism mock path/to/your.openapi.yml${NC}" echo exit 1 @@ -53,4 +53,4 @@ else fi echo "==> Running tests" -./gradlew test +./gradlew test "$@" diff --git a/scripts/upload-artifacts b/scripts/upload-artifacts new file mode 100755 index 0000000..10f3c70 --- /dev/null +++ b/scripts/upload-artifacts @@ -0,0 +1,193 @@ +#!/usr/bin/env bash + +set -euo pipefail + +# ANSI Color Codes +GREEN='\033[32m' +RED='\033[31m' +NC='\033[0m' # No Color + +MAVEN_REPO_PATH="./build/local-maven-repo" + +log_error() { + local msg="$1" + local headers="$2" + local body="$3" + echo -e "${RED}${msg}${NC}" + [[ -f "$headers" ]] && echo -e "${RED}Headers:$(cat "$headers")${NC}" + echo -e "${RED}Body: ${body}${NC}" + exit 1 +} + +upload_file() { + local file_name="$1" + local tmp_headers + tmp_headers=$(mktemp) + + if [ -f "$file_name" ]; then + echo -e "${GREEN}Processing file: $file_name${NC}" + pkg_file_name="mvn${file_name#"${MAVEN_REPO_PATH}"}" + + # Get signed URL for uploading artifact file + signed_url_response=$(curl -X POST -G "$URL" \ + -sS --retry 5 \ + -D "$tmp_headers" \ + --data-urlencode "filename=$pkg_file_name" \ + -H "Authorization: Bearer $AUTH" \ + -H "Content-Type: application/json") + + # Validate JSON and extract URL + if ! signed_url=$(echo "$signed_url_response" | jq -e -r '.url' 2>/dev/null) || [[ "$signed_url" == "null" ]]; then + log_error "Failed to get valid signed URL" "$tmp_headers" "$signed_url_response" + fi + + # Set content-type based on file extension + local extension="${file_name##*.}" + local content_type + case "$extension" in + jar) content_type="application/java-archive" ;; + md5|sha1|sha256|sha512) content_type="text/plain" ;; + module) content_type="application/json" ;; + pom|xml) content_type="application/xml" ;; + html) content_type="text/html" ;; + *) content_type="application/octet-stream" ;; + esac + + # Upload file + upload_response=$(curl -v -X PUT \ + --retry 5 \ + --retry-all-errors \ + -D "$tmp_headers" \ + -H "Content-Type: $content_type" \ + --data-binary "@${file_name}" "$signed_url" 2>&1) + + if ! echo "$upload_response" | grep -q "HTTP/[0-9.]* 200"; then + log_error "Failed to upload artifact file" "$tmp_headers" "$upload_response" + fi + + # Insert small throttle to reduce rate limiting risk + sleep 0.1 + fi +} + +walk_tree() { + local current_dir="$1" + + for entry in "$current_dir"/*; do + # Check that entry is valid + [ -e "$entry" ] || [ -h "$entry" ] || continue + + if [ -d "$entry" ]; then + walk_tree "$entry" + else + upload_file "$entry" + fi + done +} + +generate_instructions() { + cat << EOF > "$MAVEN_REPO_PATH/index.html" + + + + Maven Repo + + +

Stainless SDK Maven Repository

+

This is the Maven repository for your Stainless Java SDK build.

+ +

Project configuration

+ +

The details depend on whether you're using Maven or Gradle as your build tool.

+ +

Maven

+ +

Add the following to your project's pom.xml:

+
<repositories>
+    <repository>
+        <id>stainless-sdk-repo</id>
+        <url>https://pkg.stainless.com/s/${PROJECT}/${SHA}/mvn</url>
+    </repository>
+</repositories>
+ +

Gradle

+

Add the following to your build.gradle file:

+
repositories {
+    maven {
+        url "https://pkg.stainless.com/s/${PROJECT}/${SHA}/mvn"
+    }
+}
+ +
+

Configuring authentication (if required)

+ +

Some accounts may require authentication to access the repository. If so, use the + following instructions, replacing YOUR_STAINLESS_API_TOKEN with your actual token.

+ +

Maven with authentication

+ +

First, ensure you have the following in your Maven settings.xml for repo authentication:

+
<servers>
+    <server>
+        <id>stainless-sdk-repo</id>
+        <configuration>
+            <httpHeaders>
+                <property>
+                    <name>Authorization</name>
+                    <value>Bearer YOUR_STAINLESS_API_TOKEN</value>
+                </property>
+            </httpHeaders>
+        </configuration>
+    </server>
+</servers>
+ +

Then, add the following to your project's pom.xml:

+
<repositories>
+    <repository>
+        <id>stainless-sdk-repo</id>
+        <url>https://pkg.stainless.com/s/${PROJECT}/${SHA}/mvn</url>
+    </repository>
+</repositories>
+ +

Gradle with authentication

+

Add the following to your build.gradle file:

+
repositories {
+    maven {
+        url "https://pkg.stainless.com/s/${PROJECT}/${SHA}/mvn"
+        credentials(HttpHeaderCredentials) {
+            name = "Authorization"
+            value = "Bearer YOUR_STAINLESS_API_TOKEN"
+        }
+        authentication {
+            header(HttpHeaderAuthentication)
+        }
+    }
+}
+
+ +

Using the repository

+

Once you've configured the repository, you can include dependencies from it as usual. See your + project README + for more details.

+ + +EOF + upload_file "${MAVEN_REPO_PATH}/index.html" + + echo "Configure maven or gradle to use the repo located at 'https://pkg.stainless.com/s/${PROJECT}/${SHA}/mvn'" + echo "For more details, see the directions in https://pkg.stainless.com/s/${PROJECT}/${SHA}/mvn/index.html" +} + +cd "$(dirname "$0")/.." + +echo "::group::Creating local Maven content" +./gradlew publishMavenPublicationToLocalFileSystemRepository -PpublishLocal +echo "::endgroup::" + +echo "::group::Uploading to pkg.stainless.com" +walk_tree "$MAVEN_REPO_PATH" +echo "::endgroup::" + +echo "::group::Generating instructions" +generate_instructions +echo "::endgroup::" diff --git a/settings.gradle.kts b/settings.gradle.kts index 7c8e897..62cdb99 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,6 +1,15 @@ rootProject.name = "arcade-java-root" -include("arcade-java") -include("arcade-java-client-okhttp") -include("arcade-java-core") -include("arcade-java-example") +val projectNames = rootDir.listFiles() + ?.asSequence() + .orEmpty() + .filter { file -> + file.isDirectory && + file.name.startsWith("arcade-java") && + file.listFiles()?.asSequence().orEmpty().any { it.name == "build.gradle.kts" } + } + .map { it.name } + .toList() + + listOf("arcade-spring-boot-starter") +println("projects: $projectNames") +projectNames.forEach { include(it) }