diff --git a/.codegen.json b/.codegen.json index 450692ca5..a2d278da9 100644 --- a/.codegen.json +++ b/.codegen.json @@ -1 +1 @@ -{ "engineHash": "6772894", "specHash": "7f8494a", "version": "10.21.0" } +{ "engineHash": "dabe8ed", "specHash": "7cec401", "version": "10.21.0" } diff --git a/docs/README.md b/docs/README.md index 6da729c0c..ce93ff79c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -14,6 +14,7 @@ General explanations of the available functionality and examples of how to use the SDK are available by topic: * [Ai](ai.md) +* [Aisessions](aisessions.md) * [Aistudio](aistudio.md) * [Appitemassociations](appitemassociations.md) * [Archives](archives.md) diff --git a/docs/aisessions.md b/docs/aisessions.md new file mode 100644 index 000000000..a288f080b --- /dev/null +++ b/docs/aisessions.md @@ -0,0 +1,74 @@ +# AiSessionsManager + + +- [List AI sessions](#list-ai-sessions) +- [Delete AI session](#delete-ai-session) + +## List AI sessions + +Returns a marker-paginated list of the AI sessions that the authenticated +user can read and that were created through the Box public API. Entries are +ordered by `sort` and `direction`, defaulting to `updated_at` descending so +the most recently active session appears first. + +The access token must have both the `ai.readwrite` and `root_readwrite` +scopes. + +A page may contain fewer than `limit` entries while further pages remain. +Treat a non-null `next_marker` as the only signal that more results exist. + +This operation is performed by calling function `getAiSessionsV2026R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2026.0/get-ai-sessions/). + +*Currently we don't have an example for calling `getAiSessionsV2026R0` in integration tests* + +### Arguments + +- queryParams `GetAiSessionsV2026R0QueryParams` + - Query parameters of getAiSessionsV2026R0 method +- headers `GetAiSessionsV2026R0Headers` + - Headers of getAiSessionsV2026R0 method + + +### Returns + +This function returns a value of type `AiSessionsV2026R0`. + +Returns a paginated list of AI sessions. + + +## Delete AI session + +Deletes an AI session created through the Box public API, together with its +agent tasks. The session's agent-generated files and uploaded files are +moved to the trash. Files attached as sources from elsewhere in Box are not +affected. Deleting a session does not stop a running task or notify the +agent. + +The access token must have both the `ai.readwrite` and `root_readwrite` +scopes. + +This operation is performed by calling function `deleteAiSessionByIdV2026R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2026.0/delete-ai-sessions-id/). + +*Currently we don't have an example for calling `deleteAiSessionByIdV2026R0` in integration tests* + +### Arguments + +- aiSessionId `String` + - The unique identifier of the AI session. This is the same value returned as `id` by the list endpoint and used as the A2A `contextId`. Example: "23489723" +- headers `DeleteAiSessionByIdV2026R0Headers` + - Headers of deleteAiSessionByIdV2026R0 method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the AI session was successfully deleted. + + diff --git a/docs/configuration.md b/docs/configuration.md index a07fc503f..d4179d1bc 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -11,6 +11,9 @@ - [Example Delays (with default settings)](#example-delays-with-default-settings) - [Retry-After Header](#retry-after-header) - [Network Exception Handling](#network-exception-handling) + - [Retrying Uploads](#retrying-uploads) + - [Streams That Can Be Retried](#streams-that-can-be-retried) + - [Handling Errors for Streams That Cannot Be Retried](#handling-errors-for-streams-that-cannot-be-retried) - [Customizing Retry Parameters](#customizing-retry-parameters) - [Custom Retry Strategy](#custom-retry-strategy) - [Timeouts](#timeouts) @@ -129,6 +132,70 @@ This means: - Network exception retries are tracked independently from HTTP error retries, each with their own counter and backoff progression. - A request can fail up to `maxRetriesOnException` times due to network exceptions, but each exception retry also increments the overall attempt counter, so the total number of retries across both exception and HTTP error types is bounded by `maxAttempts`. +### Retrying Uploads + +To retry a request that uploads content, the SDK has to send the content again. The SDK does not copy the content into memory to do that. Instead, it rewinds the `InputStream` you passed to the position it had when the upload started. Whether the request can be retried therefore depends on the type of the stream. + +| Stream type | Retried automatically | How the content is sent again | +| ------------------------------------------------------------------------------------------------------- | --------------------- | -------------------------------------------------------------------------- | +| `FileInputStream` | Yes | The file position is moved back to where it was when the upload started. | +| `ByteArrayInputStream` | Yes | The stream is reset to where it was when the upload started. | +| Any other stream, for example from `Files.newInputStream`, `BufferedInputStream`, or a network response | No | The content is sent once. If that attempt fails, the SDK throws the error. | + +If a request with a stream that cannot be rewound fails with a retryable error, such as `429 Too Many Requests` or a `5xx` status, the SDK does not retry it. It throws the original `BoxAPIError` instead, which keeps the response status and headers, including `Retry-After`. For a `401` response, the SDK still refreshes the access token, so your next request uses a valid token. + +Uploads to an upload session, such as `uploadBigFile` and `uploadFilePart`, are always retried. Each part is read into memory before it is sent, so it can be sent again regardless of the stream type. + +The SDK closes the stream you pass after the request finishes, including all retries, whether it succeeds or fails. Closing it yourself as well, for example with try-with-resources, is safe. + +Interceptors run before every attempt, but a request body that reads a stream is built on the first attempt and reused on retries. Changes an interceptor makes to the upload stream on a retry are therefore not applied. + +#### Streams That Can Be Retried + +To let the SDK retry uploads automatically, pass a `FileInputStream` when uploading from a file: + +```java +try (FileInputStream fileStream = new FileInputStream(new File("report.pdf"))) { + client.getUploads().uploadFile( + new UploadFileRequestBody( + new UploadFileRequestBodyAttributesField( + "report.pdf", new UploadFileRequestBodyAttributesParentField("0")), + fileStream)); +} +``` + +If you open files with `Files.newInputStream(path)`, use `new FileInputStream(path.toFile())` instead. The stream returned by `Files.newInputStream` cannot be rewound. + +For content that is already in memory, wrap it in a `ByteArrayInputStream`. Do not copy large files into memory only to make them retryable; use a `FileInputStream` instead. + +#### Handling Errors for Streams That Cannot Be Retried + +If you upload from a stream that cannot be rewound, handle retryable errors in your code and send a new stream on each attempt: + +```java +BoxAPIError lastError = null; +for (int attempt = 0; attempt < 3; attempt++) { + try (InputStream stream = openContentStream()) { + return client.getUploads().uploadFile( + new UploadFileRequestBody( + new UploadFileRequestBodyAttributesField( + "report.pdf", new UploadFileRequestBodyAttributesParentField("0")), + stream)); + } catch (BoxAPIError error) { + int status = error.getResponseInfo().getStatusCode(); + if (status != 429 && status < 500) { + throw error; + } + lastError = error; + String retryAfter = error.getResponseInfo().getHeaders().get("Retry-After"); + Thread.sleep(retryAfter != null ? (long) (Double.parseDouble(retryAfter) * 1000) : 1000L); + } +} +throw lastError; +``` + +`openContentStream()` stands for your own code that opens the content from the beginning, for example a new request to the system the content comes from. + ### Customizing Retry Parameters You can customize all retry parameters by initializing `BoxRetryStrategy` with the desired values and passing it to `NetworkSession`: diff --git a/src/main/java/com/box/sdkgen/box/errors/RequestInfo.java b/src/main/java/com/box/sdkgen/box/errors/RequestInfo.java index dcdb9edec..963207cc7 100644 --- a/src/main/java/com/box/sdkgen/box/errors/RequestInfo.java +++ b/src/main/java/com/box/sdkgen/box/errors/RequestInfo.java @@ -1,8 +1,10 @@ package com.box.sdkgen.box.errors; import com.box.sdkgen.internal.logging.DataSanitizer; +import com.box.sdkgen.networking.inputstreamrequestbody.InputStreamRequestBody; import java.util.Map; import java.util.stream.Collectors; +import okhttp3.MultipartBody; import okhttp3.Request; import okhttp3.RequestBody; import okio.Buffer; @@ -120,6 +122,10 @@ public static RequestInfo fromRequest(Request request, String contentType) { } private static String getRequestBodyAsString(RequestBody requestBody) { + // Writing a stream body here would read the whole file content into memory. + if (containsStream(requestBody)) { + return null; + } try { if (requestBody != null) { Buffer buffer = new Buffer(); @@ -132,6 +138,14 @@ private static String getRequestBodyAsString(RequestBody requestBody) { return null; } + private static boolean containsStream(RequestBody requestBody) { + if (requestBody instanceof MultipartBody) { + return ((MultipartBody) requestBody) + .parts().stream().anyMatch(part -> containsStream(part.body())); + } + return requestBody instanceof InputStreamRequestBody; + } + String print(DataSanitizer dataSanitizer) { Map sanitizedHeaders = dataSanitizer == null ? headers : dataSanitizer.sanitizeHeaders(headers); diff --git a/src/main/java/com/box/sdkgen/client/BoxClient.java b/src/main/java/com/box/sdkgen/client/BoxClient.java index a46b0c350..5cc1e6b45 100644 --- a/src/main/java/com/box/sdkgen/client/BoxClient.java +++ b/src/main/java/com/box/sdkgen/client/BoxClient.java @@ -4,6 +4,7 @@ import static com.box.sdkgen.internal.utils.UtilsManager.mapOf; import com.box.sdkgen.managers.ai.AiManager; +import com.box.sdkgen.managers.aisessions.AiSessionsManager; import com.box.sdkgen.managers.aistudio.AiStudioManager; import com.box.sdkgen.managers.appitemassociations.AppItemAssociationsManager; import com.box.sdkgen.managers.archives.ArchivesManager; @@ -285,6 +286,8 @@ public class BoxClient { public final ShuttleManager shuttle; + public final AiSessionsManager aiSessions; + public BoxClient(Authentication auth) { this.auth = auth; this.networkSession = new NetworkSession.Builder().baseUrls(new BaseUrls()).build(); @@ -649,6 +652,8 @@ public BoxClient(Authentication auth) { new QueryManager.Builder().auth(this.auth).networkSession(this.networkSession).build(); this.shuttle = new ShuttleManager.Builder().auth(this.auth).networkSession(this.networkSession).build(); + this.aiSessions = + new AiSessionsManager.Builder().auth(this.auth).networkSession(this.networkSession).build(); } protected BoxClient(Builder builder) { @@ -1015,6 +1020,8 @@ protected BoxClient(Builder builder) { new QueryManager.Builder().auth(this.auth).networkSession(this.networkSession).build(); this.shuttle = new ShuttleManager.Builder().auth(this.auth).networkSession(this.networkSession).build(); + this.aiSessions = + new AiSessionsManager.Builder().auth(this.auth).networkSession(this.networkSession).build(); } /** @@ -1490,6 +1497,10 @@ public ShuttleManager getShuttle() { return shuttle; } + public AiSessionsManager getAiSessions() { + return aiSessions; + } + public static class Builder { protected final Authentication auth; diff --git a/src/main/java/com/box/sdkgen/managers/aisessions/AiSessionsManager.java b/src/main/java/com/box/sdkgen/managers/aisessions/AiSessionsManager.java new file mode 100644 index 000000000..50bc8ee3f --- /dev/null +++ b/src/main/java/com/box/sdkgen/managers/aisessions/AiSessionsManager.java @@ -0,0 +1,180 @@ +package com.box.sdkgen.managers.aisessions; + +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.entryOf; +import static com.box.sdkgen.internal.utils.UtilsManager.mapOf; +import static com.box.sdkgen.internal.utils.UtilsManager.mergeMaps; +import static com.box.sdkgen.internal.utils.UtilsManager.prepareParams; + +import com.box.sdkgen.networking.auth.Authentication; +import com.box.sdkgen.networking.fetchoptions.FetchOptions; +import com.box.sdkgen.networking.fetchoptions.ResponseFormat; +import com.box.sdkgen.networking.fetchresponse.FetchResponse; +import com.box.sdkgen.networking.network.NetworkSession; +import com.box.sdkgen.schemas.v2026r0.aisessionsv2026r0.AiSessionsV2026R0; +import com.box.sdkgen.serialization.json.JsonManager; +import java.util.Map; + +public class AiSessionsManager { + + public Authentication auth; + + public NetworkSession networkSession; + + public AiSessionsManager() { + this.networkSession = new NetworkSession(); + } + + protected AiSessionsManager(Builder builder) { + this.auth = builder.auth; + this.networkSession = builder.networkSession; + } + + /** + * Returns a marker-paginated list of the AI sessions that the authenticated user can read and + * that were created through the Box public API. Entries are ordered by `sort` and `direction`, + * defaulting to `updated_at` descending so the most recently active session appears first. + * + *

The access token must have both the `ai.readwrite` and `root_readwrite` scopes. + * + *

A page may contain fewer than `limit` entries while further pages remain. Treat a non-null + * `next_marker` as the only signal that more results exist. + * + * @param queryParams Query parameters of getAiSessionsV2026R0 method + */ + public AiSessionsV2026R0 getAiSessionsV2026R0(GetAiSessionsV2026R0QueryParams queryParams) { + return getAiSessionsV2026R0(queryParams, new GetAiSessionsV2026R0Headers()); + } + + /** + * Returns a marker-paginated list of the AI sessions that the authenticated user can read and + * that were created through the Box public API. Entries are ordered by `sort` and `direction`, + * defaulting to `updated_at` descending so the most recently active session appears first. + * + *

The access token must have both the `ai.readwrite` and `root_readwrite` scopes. + * + *

A page may contain fewer than `limit` entries while further pages remain. Treat a non-null + * `next_marker` as the only signal that more results exist. + * + * @param queryParams Query parameters of getAiSessionsV2026R0 method + * @param headers Headers of getAiSessionsV2026R0 method + */ + public AiSessionsV2026R0 getAiSessionsV2026R0( + GetAiSessionsV2026R0QueryParams queryParams, GetAiSessionsV2026R0Headers headers) { + Map queryParamsMap = + prepareParams( + mapOf( + entryOf("source", convertToString(queryParams.getSource())), + entryOf("marker", convertToString(queryParams.getMarker())), + entryOf("sort", convertToString(queryParams.getSort())), + entryOf("direction", convertToString(queryParams.getDirection())), + entryOf("limit", convertToString(queryParams.getLimit())), + entryOf("client_ids", convertToString(queryParams.getClientIds())))); + Map headersMap = + prepareParams( + mergeMaps( + mapOf(entryOf("box-version", convertToString(headers.getBoxVersion()))), + headers.getExtraHeaders())); + FetchResponse response = + this.networkSession + .getNetworkClient() + .fetch( + new FetchOptions.Builder( + String.join( + "", this.networkSession.getBaseUrls().getBaseUrl(), "/2.0/ai_sessions"), + "GET") + .params(queryParamsMap) + .headers(headersMap) + .responseFormat(ResponseFormat.JSON) + .auth(this.auth) + .networkSession(this.networkSession) + .build()); + return JsonManager.deserialize(response.getData(), AiSessionsV2026R0.class); + } + + /** + * Deletes an AI session created through the Box public API, together with its agent tasks. The + * session's agent-generated files and uploaded files are moved to the trash. Files attached as + * sources from elsewhere in Box are not affected. Deleting a session does not stop a running task + * or notify the agent. + * + *

The access token must have both the `ai.readwrite` and `root_readwrite` scopes. + * + * @param aiSessionId The unique identifier of the AI session. This is the same value returned as + * `id` by the list endpoint and used as the A2A `contextId`. Example: "23489723" + */ + public void deleteAiSessionByIdV2026R0(String aiSessionId) { + deleteAiSessionByIdV2026R0(aiSessionId, new DeleteAiSessionByIdV2026R0Headers()); + } + + /** + * Deletes an AI session created through the Box public API, together with its agent tasks. The + * session's agent-generated files and uploaded files are moved to the trash. Files attached as + * sources from elsewhere in Box are not affected. Deleting a session does not stop a running task + * or notify the agent. + * + *

The access token must have both the `ai.readwrite` and `root_readwrite` scopes. + * + * @param aiSessionId The unique identifier of the AI session. This is the same value returned as + * `id` by the list endpoint and used as the A2A `contextId`. Example: "23489723" + * @param headers Headers of deleteAiSessionByIdV2026R0 method + */ + public void deleteAiSessionByIdV2026R0( + String aiSessionId, DeleteAiSessionByIdV2026R0Headers headers) { + Map headersMap = + prepareParams( + mergeMaps( + mapOf(entryOf("box-version", convertToString(headers.getBoxVersion()))), + headers.getExtraHeaders())); + FetchResponse response = + this.networkSession + .getNetworkClient() + .fetch( + new FetchOptions.Builder( + String.join( + "", + this.networkSession.getBaseUrls().getBaseUrl(), + "/2.0/ai_sessions/", + convertToString(aiSessionId)), + "DELETE") + .headers(headersMap) + .responseFormat(ResponseFormat.NO_CONTENT) + .auth(this.auth) + .networkSession(this.networkSession) + .build()); + } + + public Authentication getAuth() { + return auth; + } + + public NetworkSession getNetworkSession() { + return networkSession; + } + + public static class Builder { + + protected Authentication auth; + + protected NetworkSession networkSession; + + public Builder() {} + + public Builder auth(Authentication auth) { + this.auth = auth; + return this; + } + + public Builder networkSession(NetworkSession networkSession) { + this.networkSession = networkSession; + return this; + } + + public AiSessionsManager build() { + if (this.networkSession == null) { + this.networkSession = new NetworkSession(); + } + return new AiSessionsManager(this); + } + } +} diff --git a/src/main/java/com/box/sdkgen/managers/aisessions/DeleteAiSessionByIdV2026R0Headers.java b/src/main/java/com/box/sdkgen/managers/aisessions/DeleteAiSessionByIdV2026R0Headers.java new file mode 100644 index 000000000..08eda388d --- /dev/null +++ b/src/main/java/com/box/sdkgen/managers/aisessions/DeleteAiSessionByIdV2026R0Headers.java @@ -0,0 +1,68 @@ +package com.box.sdkgen.managers.aisessions; + +import static com.box.sdkgen.internal.utils.UtilsManager.mapOf; + +import com.box.sdkgen.parameters.v2026r0.boxversionheaderv2026r0.BoxVersionHeaderV2026R0; +import com.box.sdkgen.serialization.json.EnumWrapper; +import java.util.Map; + +public class DeleteAiSessionByIdV2026R0Headers { + + /** Version header. */ + public EnumWrapper boxVersion; + + /** Extra headers that will be included in the HTTP request. */ + public Map extraHeaders; + + public DeleteAiSessionByIdV2026R0Headers() { + this.boxVersion = new EnumWrapper(BoxVersionHeaderV2026R0._2026_0); + this.extraHeaders = mapOf(); + } + + protected DeleteAiSessionByIdV2026R0Headers(Builder builder) { + this.boxVersion = builder.boxVersion; + this.extraHeaders = builder.extraHeaders; + } + + public EnumWrapper getBoxVersion() { + return boxVersion; + } + + public Map getExtraHeaders() { + return extraHeaders; + } + + public static class Builder { + + protected EnumWrapper boxVersion; + + protected Map extraHeaders; + + public Builder() {} + + public Builder boxVersion(BoxVersionHeaderV2026R0 boxVersion) { + this.boxVersion = new EnumWrapper(boxVersion); + return this; + } + + public Builder boxVersion(EnumWrapper boxVersion) { + this.boxVersion = boxVersion; + return this; + } + + public Builder extraHeaders(Map extraHeaders) { + this.extraHeaders = extraHeaders; + return this; + } + + public DeleteAiSessionByIdV2026R0Headers build() { + if (this.boxVersion == null) { + this.boxVersion = new EnumWrapper(BoxVersionHeaderV2026R0._2026_0); + } + if (this.extraHeaders == null) { + this.extraHeaders = mapOf(); + } + return new DeleteAiSessionByIdV2026R0Headers(this); + } + } +} diff --git a/src/main/java/com/box/sdkgen/managers/aisessions/GetAiSessionsV2026R0Headers.java b/src/main/java/com/box/sdkgen/managers/aisessions/GetAiSessionsV2026R0Headers.java new file mode 100644 index 000000000..a2ab1a8b8 --- /dev/null +++ b/src/main/java/com/box/sdkgen/managers/aisessions/GetAiSessionsV2026R0Headers.java @@ -0,0 +1,68 @@ +package com.box.sdkgen.managers.aisessions; + +import static com.box.sdkgen.internal.utils.UtilsManager.mapOf; + +import com.box.sdkgen.parameters.v2026r0.boxversionheaderv2026r0.BoxVersionHeaderV2026R0; +import com.box.sdkgen.serialization.json.EnumWrapper; +import java.util.Map; + +public class GetAiSessionsV2026R0Headers { + + /** Version header. */ + public EnumWrapper boxVersion; + + /** Extra headers that will be included in the HTTP request. */ + public Map extraHeaders; + + public GetAiSessionsV2026R0Headers() { + this.boxVersion = new EnumWrapper(BoxVersionHeaderV2026R0._2026_0); + this.extraHeaders = mapOf(); + } + + protected GetAiSessionsV2026R0Headers(Builder builder) { + this.boxVersion = builder.boxVersion; + this.extraHeaders = builder.extraHeaders; + } + + public EnumWrapper getBoxVersion() { + return boxVersion; + } + + public Map getExtraHeaders() { + return extraHeaders; + } + + public static class Builder { + + protected EnumWrapper boxVersion; + + protected Map extraHeaders; + + public Builder() {} + + public Builder boxVersion(BoxVersionHeaderV2026R0 boxVersion) { + this.boxVersion = new EnumWrapper(boxVersion); + return this; + } + + public Builder boxVersion(EnumWrapper boxVersion) { + this.boxVersion = boxVersion; + return this; + } + + public Builder extraHeaders(Map extraHeaders) { + this.extraHeaders = extraHeaders; + return this; + } + + public GetAiSessionsV2026R0Headers build() { + if (this.boxVersion == null) { + this.boxVersion = new EnumWrapper(BoxVersionHeaderV2026R0._2026_0); + } + if (this.extraHeaders == null) { + this.extraHeaders = mapOf(); + } + return new GetAiSessionsV2026R0Headers(this); + } + } +} diff --git a/src/main/java/com/box/sdkgen/managers/aisessions/GetAiSessionsV2026R0QueryParams.java b/src/main/java/com/box/sdkgen/managers/aisessions/GetAiSessionsV2026R0QueryParams.java new file mode 100644 index 000000000..882d158c9 --- /dev/null +++ b/src/main/java/com/box/sdkgen/managers/aisessions/GetAiSessionsV2026R0QueryParams.java @@ -0,0 +1,147 @@ +package com.box.sdkgen.managers.aisessions; + +import com.box.sdkgen.serialization.json.EnumWrapper; +import java.util.List; + +public class GetAiSessionsV2026R0QueryParams { + + /** Restricts the list to AI sessions with this origin. The only supported value is `api`. */ + public final EnumWrapper source; + + /** + * The position marker at which to begin returning results, as returned in `next_marker` by the + * previous page. Omit it for the first page. All other parameters must match the request that + * returned the marker. + */ + public String marker; + + /** + * The field to sort results by. Possible values are `created_at`, `updated_at`, and `name`. + * Default is `updated_at`, which advances on each turn of session activity. + */ + public EnumWrapper sort; + + /** + * The direction to sort results in, either ascending (`asc`) or descending (`desc`). Default is + * `desc`. + */ + public EnumWrapper direction; + + /** + * The maximum number of AI sessions to return per page. The maximum is `100`; larger values are + * treated as `100`. The server may return fewer entries than requested. + */ + public Integer limit; + + /** + * A comma-separated list of OAuth client IDs. Restricts the list to AI sessions created by any of + * these applications. Client IDs that match no application are ignored, so the response is an + * empty list if none of them match. Empty entries are ignored, and an empty value is treated as + * if the parameter were not provided. + */ + public List clientIds; + + public GetAiSessionsV2026R0QueryParams(GetAiSessionsV2026R0QueryParamsSourceField source) { + this.source = new EnumWrapper(source); + } + + public GetAiSessionsV2026R0QueryParams( + EnumWrapper source) { + this.source = source; + } + + protected GetAiSessionsV2026R0QueryParams(Builder builder) { + this.source = builder.source; + this.marker = builder.marker; + this.sort = builder.sort; + this.direction = builder.direction; + this.limit = builder.limit; + this.clientIds = builder.clientIds; + } + + public EnumWrapper getSource() { + return source; + } + + public String getMarker() { + return marker; + } + + public EnumWrapper getSort() { + return sort; + } + + public EnumWrapper getDirection() { + return direction; + } + + public Integer getLimit() { + return limit; + } + + public List getClientIds() { + return clientIds; + } + + public static class Builder { + + protected final EnumWrapper source; + + protected String marker; + + protected EnumWrapper sort; + + protected EnumWrapper direction; + + protected Integer limit; + + protected List clientIds; + + public Builder(GetAiSessionsV2026R0QueryParamsSourceField source) { + this.source = new EnumWrapper(source); + } + + public Builder(EnumWrapper source) { + this.source = source; + } + + public Builder marker(String marker) { + this.marker = marker; + return this; + } + + public Builder sort(GetAiSessionsV2026R0QueryParamsSortField sort) { + this.sort = new EnumWrapper(sort); + return this; + } + + public Builder sort(EnumWrapper sort) { + this.sort = sort; + return this; + } + + public Builder direction(GetAiSessionsV2026R0QueryParamsDirectionField direction) { + this.direction = new EnumWrapper(direction); + return this; + } + + public Builder direction(EnumWrapper direction) { + this.direction = direction; + return this; + } + + public Builder limit(Integer limit) { + this.limit = limit; + return this; + } + + public Builder clientIds(List clientIds) { + this.clientIds = clientIds; + return this; + } + + public GetAiSessionsV2026R0QueryParams build() { + return new GetAiSessionsV2026R0QueryParams(this); + } + } +} diff --git a/src/main/java/com/box/sdkgen/managers/aisessions/GetAiSessionsV2026R0QueryParamsDirectionField.java b/src/main/java/com/box/sdkgen/managers/aisessions/GetAiSessionsV2026R0QueryParamsDirectionField.java new file mode 100644 index 000000000..c7c77b9ce --- /dev/null +++ b/src/main/java/com/box/sdkgen/managers/aisessions/GetAiSessionsV2026R0QueryParamsDirectionField.java @@ -0,0 +1,65 @@ +package com.box.sdkgen.managers.aisessions; + +import com.box.sdkgen.serialization.json.EnumWrapper; +import com.box.sdkgen.serialization.json.Valuable; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import java.io.IOException; +import java.util.Arrays; + +public enum GetAiSessionsV2026R0QueryParamsDirectionField implements Valuable { + ASC("asc"), + DESC("desc"); + + private final String value; + + GetAiSessionsV2026R0QueryParamsDirectionField(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + public static class GetAiSessionsV2026R0QueryParamsDirectionFieldDeserializer + extends JsonDeserializer> { + + public GetAiSessionsV2026R0QueryParamsDirectionFieldDeserializer() { + super(); + } + + @Override + public EnumWrapper deserialize( + JsonParser p, DeserializationContext ctxt) throws IOException { + String value = p.getValueAsString(); + return Arrays.stream(GetAiSessionsV2026R0QueryParamsDirectionField.values()) + .filter((v) -> v.getValue().equalsIgnoreCase(value)) + .findFirst() + .map(EnumWrapper::new) + .orElse(new EnumWrapper(value)); + } + } + + public static class GetAiSessionsV2026R0QueryParamsDirectionFieldSerializer + extends JsonSerializer> { + + public GetAiSessionsV2026R0QueryParamsDirectionFieldSerializer() { + super(); + } + + @Override + public void serialize( + EnumWrapper value, + JsonGenerator gen, + SerializerProvider serializers) + throws IOException { + gen.writeString(value.getStringValue()); + } + } +} diff --git a/src/main/java/com/box/sdkgen/managers/aisessions/GetAiSessionsV2026R0QueryParamsSortField.java b/src/main/java/com/box/sdkgen/managers/aisessions/GetAiSessionsV2026R0QueryParamsSortField.java new file mode 100644 index 000000000..2fd9d26ab --- /dev/null +++ b/src/main/java/com/box/sdkgen/managers/aisessions/GetAiSessionsV2026R0QueryParamsSortField.java @@ -0,0 +1,66 @@ +package com.box.sdkgen.managers.aisessions; + +import com.box.sdkgen.serialization.json.EnumWrapper; +import com.box.sdkgen.serialization.json.Valuable; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import java.io.IOException; +import java.util.Arrays; + +public enum GetAiSessionsV2026R0QueryParamsSortField implements Valuable { + CREATED_AT("created_at"), + UPDATED_AT("updated_at"), + NAME("name"); + + private final String value; + + GetAiSessionsV2026R0QueryParamsSortField(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + public static class GetAiSessionsV2026R0QueryParamsSortFieldDeserializer + extends JsonDeserializer> { + + public GetAiSessionsV2026R0QueryParamsSortFieldDeserializer() { + super(); + } + + @Override + public EnumWrapper deserialize( + JsonParser p, DeserializationContext ctxt) throws IOException { + String value = p.getValueAsString(); + return Arrays.stream(GetAiSessionsV2026R0QueryParamsSortField.values()) + .filter((v) -> v.getValue().equalsIgnoreCase(value)) + .findFirst() + .map(EnumWrapper::new) + .orElse(new EnumWrapper(value)); + } + } + + public static class GetAiSessionsV2026R0QueryParamsSortFieldSerializer + extends JsonSerializer> { + + public GetAiSessionsV2026R0QueryParamsSortFieldSerializer() { + super(); + } + + @Override + public void serialize( + EnumWrapper value, + JsonGenerator gen, + SerializerProvider serializers) + throws IOException { + gen.writeString(value.getStringValue()); + } + } +} diff --git a/src/main/java/com/box/sdkgen/managers/aisessions/GetAiSessionsV2026R0QueryParamsSourceField.java b/src/main/java/com/box/sdkgen/managers/aisessions/GetAiSessionsV2026R0QueryParamsSourceField.java new file mode 100644 index 000000000..767d9eb60 --- /dev/null +++ b/src/main/java/com/box/sdkgen/managers/aisessions/GetAiSessionsV2026R0QueryParamsSourceField.java @@ -0,0 +1,64 @@ +package com.box.sdkgen.managers.aisessions; + +import com.box.sdkgen.serialization.json.EnumWrapper; +import com.box.sdkgen.serialization.json.Valuable; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import java.io.IOException; +import java.util.Arrays; + +public enum GetAiSessionsV2026R0QueryParamsSourceField implements Valuable { + API("api"); + + private final String value; + + GetAiSessionsV2026R0QueryParamsSourceField(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + public static class GetAiSessionsV2026R0QueryParamsSourceFieldDeserializer + extends JsonDeserializer> { + + public GetAiSessionsV2026R0QueryParamsSourceFieldDeserializer() { + super(); + } + + @Override + public EnumWrapper deserialize( + JsonParser p, DeserializationContext ctxt) throws IOException { + String value = p.getValueAsString(); + return Arrays.stream(GetAiSessionsV2026R0QueryParamsSourceField.values()) + .filter((v) -> v.getValue().equalsIgnoreCase(value)) + .findFirst() + .map(EnumWrapper::new) + .orElse(new EnumWrapper(value)); + } + } + + public static class GetAiSessionsV2026R0QueryParamsSourceFieldSerializer + extends JsonSerializer> { + + public GetAiSessionsV2026R0QueryParamsSourceFieldSerializer() { + super(); + } + + @Override + public void serialize( + EnumWrapper value, + JsonGenerator gen, + SerializerProvider serializers) + throws IOException { + gen.writeString(value.getStringValue()); + } + } +} diff --git a/src/main/java/com/box/sdkgen/networking/boxnetworkclient/BoxNetworkClient.java b/src/main/java/com/box/sdkgen/networking/boxnetworkclient/BoxNetworkClient.java index dd203170e..7a66f7ecd 100644 --- a/src/main/java/com/box/sdkgen/networking/boxnetworkclient/BoxNetworkClient.java +++ b/src/main/java/com/box/sdkgen/networking/boxnetworkclient/BoxNetworkClient.java @@ -16,12 +16,14 @@ import com.box.sdkgen.networking.fetchoptions.MultipartItem; import com.box.sdkgen.networking.fetchoptions.ResponseFormat; import com.box.sdkgen.networking.fetchresponse.FetchResponse; +import com.box.sdkgen.networking.inputstreamrequestbody.InputStreamRequestBody; import com.box.sdkgen.networking.network.NetworkSession; import com.box.sdkgen.networking.networkclient.NetworkClient; import com.box.sdkgen.networking.proxyconfig.ProxyConfig; import com.box.sdkgen.networking.timeoutconfig.TimeoutConfig; import com.fasterxml.jackson.databind.JsonNode; import java.io.IOException; +import java.io.InputStream; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.URI; @@ -43,9 +45,6 @@ import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; -import okio.BufferedSink; -import okio.Okio; -import okio.Source; public class BoxNetworkClient implements NetworkClient { @@ -132,11 +131,20 @@ public BoxNetworkClient withTimeoutConfig(TimeoutConfig config) { } public FetchResponse fetch(FetchOptions options) { + try { + return fetchWithRetries(options); + } finally { + closeFileStreams(options); + } + } + + private FetchResponse fetchWithRetries(FetchOptions options) { NetworkSession networkSession = options.getNetworkSession() == null ? new NetworkSession() : options.getNetworkSession(); boolean authenticationNeeded = false; Request request; + RequestBody body = null; FetchResponse fetchResponse = new FetchResponse.Builder(0, new TreeMap<>()).build(); Exception exceptionThrown = null; @@ -146,21 +154,17 @@ public FetchResponse fetch(FetchOptions options) { boolean shouldRetry = false; while (true) { - FetchOptions attemptOptions = - (attemptNumber > 1 || numberOfRetriesOnException > 0 || options.getData() == null) - && options.getDataFactory() != null - ? withData(options, options.getDataFactory().create()) - : options; - FetchOptions fetchOptions = applyInterceptors(attemptOptions, networkSession); + boolean isFirstAttempt = attemptNumber == 1 && numberOfRetriesOnException == 0; + FetchOptions fetchOptions = applyInterceptors(options, networkSession); if (fetchOptions.getDataFactory() != null - && options.getDataFactory() == null - && (attemptNumber > 1 - || numberOfRetriesOnException > 0 - || fetchOptions.getData() == null)) { + && (!isFirstAttempt || fetchOptions.getData() == null)) { fetchOptions = withData(fetchOptions, fetchOptions.getDataFactory().create()); } - request = prepareRequest(fetchOptions, authenticationNeeded, networkSession); + if (isFirstAttempt || !containsFileStream(fetchOptions)) { + body = prepareRequestBody(fetchOptions); + } + request = prepareRequest(fetchOptions, body, authenticationNeeded, networkSession); Response response = null; String rawResponseBody = null; @@ -222,8 +226,9 @@ public FetchResponse fetch(FetchOptions options) { networkSession .getRetryStrategy() .shouldRetry(fetchOptions, fetchResponse, attemptForRetry); + boolean isRetryable = canBeResent(body); - if (shouldRetry) { + if (shouldRetry && isRetryable) { double retryDelay = networkSession .getRetryStrategy() @@ -301,11 +306,13 @@ private static FetchOptions withData(FetchOptions options, JsonNode data) { } private static Request prepareRequest( - FetchOptions options, boolean reauthenticate, NetworkSession networkSession) { + FetchOptions options, + RequestBody body, + boolean reauthenticate, + NetworkSession networkSession) { Request.Builder requestBuilder = new Request.Builder().url(options.getUrl()); Headers headers = prepareHeaders(options, reauthenticate, networkSession); HttpUrl url = prepareUrl(options); - RequestBody body = prepareRequestBody(options); requestBuilder.headers(headers); requestBuilder.url(url); @@ -438,23 +445,48 @@ private static int getRetryAfterTimeInSeconds(int attemptNumber, String retryAft return (int) (Math.pow(2, attemptNumber) * BASE_TIMEOUT * jitter); } - public static RequestBody createMultipartRequestBody(MultipartItem part) { - return new RequestBody() { - @Override - public MediaType contentType() { - if (part.contentType != null) { - return MediaType.parse(part.contentType); - } - return MediaType.parse("application/octet-stream"); - } + /** + * Returns whether the request body reads a file stream. Such a body is built once and reused on + * retries, because rebuilding it would read the stream from where the previous attempt stopped. + */ + private static boolean containsFileStream(FetchOptions options) { + return options.getFileStream() != null + || (options.getMultipartData() != null + && options.getMultipartData().stream().anyMatch(part -> part.getFileStream() != null)); + } - @Override - public void writeTo(BufferedSink sink) throws IOException { - try (Source source = Okio.source(part.getFileStream())) { - sink.writeAll(source); - } - } - }; + private static void closeFileStreams(FetchOptions options) { + if (options.getFileStream() != null) { + closeQuietly(options.getFileStream()); + } + if (options.getMultipartData() != null) { + options.getMultipartData().stream() + .map(MultipartItem::getFileStream) + .filter(Objects::nonNull) + .forEach(BoxNetworkClient::closeQuietly); + } + } + + /** A failure to close a stream must not replace the result or the error of the request. */ + private static void closeQuietly(InputStream stream) { + try { + stream.close(); + } catch (IOException ignored) { + } + } + + private static boolean canBeResent(RequestBody body) { + if (body instanceof MultipartBody) { + return ((MultipartBody) body).parts().stream().allMatch(part -> canBeResent(part.body())); + } + return !(body instanceof InputStreamRequestBody) + || ((InputStreamRequestBody) body).canBeResent(); + } + + public static RequestBody createMultipartRequestBody(MultipartItem part) { + MediaType contentType = + MediaType.parse(part.contentType != null ? part.contentType : "application/octet-stream"); + return new InputStreamRequestBody(part.getFileStream(), contentType); } public static OkHttpClient.Builder getDefaultOkHttpClientBuilder() { diff --git a/src/main/java/com/box/sdkgen/networking/defaultnetworkclient/DefaultNetworkClient.java b/src/main/java/com/box/sdkgen/networking/defaultnetworkclient/DefaultNetworkClient.java index f8bba1237..a8e4de908 100644 --- a/src/main/java/com/box/sdkgen/networking/defaultnetworkclient/DefaultNetworkClient.java +++ b/src/main/java/com/box/sdkgen/networking/defaultnetworkclient/DefaultNetworkClient.java @@ -11,9 +11,11 @@ import com.box.sdkgen.networking.fetchoptions.MultipartItem; import com.box.sdkgen.networking.fetchoptions.ResponseFormat; import com.box.sdkgen.networking.fetchresponse.FetchResponse; +import com.box.sdkgen.networking.inputstreamrequestbody.InputStreamRequestBody; import com.box.sdkgen.networking.network.NetworkSession; import com.box.sdkgen.networking.networkclient.NetworkClient; import java.io.IOException; +import java.io.InputStream; import java.util.Locale; import java.util.Map; import java.util.Objects; @@ -29,9 +31,6 @@ import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; -import okio.BufferedSink; -import okio.Okio; -import okio.Source; public class DefaultNetworkClient implements NetworkClient { @@ -46,6 +45,14 @@ public DefaultNetworkClient() { } public FetchResponse fetch(FetchOptions options) { + try { + return fetchWithRetries(options); + } finally { + closeFileStreams(options); + } + } + + private FetchResponse fetchWithRetries(FetchOptions options) { NetworkSession networkSession = options.getNetworkSession() == null ? new NetworkSession() : options.getNetworkSession(); @@ -58,6 +65,7 @@ public FetchResponse fetch(FetchOptions options) { boolean authenticationNeeded = false; Request request; + RequestBody body = prepareRequestBody(fetchOptions); FetchResponse fetchResponse = null; Exception exceptionThrown = null; @@ -67,7 +75,7 @@ public FetchResponse fetch(FetchOptions options) { boolean shouldRetry = false; while (true) { - request = prepareRequest(fetchOptions, authenticationNeeded, networkSession); + request = prepareRequest(fetchOptions, body, authenticationNeeded, networkSession); Response response = null; try { @@ -123,8 +131,9 @@ public FetchResponse fetch(FetchOptions options) { networkSession .getRetryStrategy() .shouldRetry(fetchOptions, fetchResponse, attemptForRetry); + boolean isRetryable = canBeResent(body); - if (shouldRetry) { + if (shouldRetry && isRetryable) { double retryDelay = networkSession .getRetryStrategy() @@ -167,11 +176,13 @@ public FetchResponse fetch(FetchOptions options) { } private static Request prepareRequest( - FetchOptions options, boolean reauthenticate, NetworkSession networkSession) { + FetchOptions options, + RequestBody body, + boolean reauthenticate, + NetworkSession networkSession) { Request.Builder requestBuilder = new Request.Builder().url(options.getUrl()); Headers headers = prepareHeaders(options, reauthenticate, networkSession); HttpUrl url = prepareUrl(options); - RequestBody body = prepareRequestBody(options); requestBuilder.headers(headers); requestBuilder.url(url); @@ -257,23 +268,38 @@ private Response executeOnClient(Request request) { } } - public static RequestBody createMultipartRequestBody(MultipartItem part) { - return new RequestBody() { - @Override - public MediaType contentType() { - if (part.contentType != null) { - return MediaType.parse(part.contentType); - } - return MediaType.parse("application/octet-stream"); - } + private static void closeFileStreams(FetchOptions options) { + if (options.getFileStream() != null) { + closeQuietly(options.getFileStream()); + } + if (options.getMultipartData() != null) { + options.getMultipartData().stream() + .map(MultipartItem::getFileStream) + .filter(Objects::nonNull) + .forEach(DefaultNetworkClient::closeQuietly); + } + } - @Override - public void writeTo(BufferedSink sink) throws IOException { - try (Source source = Okio.source(part.getFileStream())) { - sink.writeAll(source); - } - } - }; + /** A failure to close a stream must not replace the result or the error of the request. */ + private static void closeQuietly(InputStream stream) { + try { + stream.close(); + } catch (IOException ignored) { + } + } + + private static boolean canBeResent(RequestBody body) { + if (body instanceof MultipartBody) { + return ((MultipartBody) body).parts().stream().allMatch(part -> canBeResent(part.body())); + } + return !(body instanceof InputStreamRequestBody) + || ((InputStreamRequestBody) body).canBeResent(); + } + + public static RequestBody createMultipartRequestBody(MultipartItem part) { + MediaType contentType = + MediaType.parse(part.contentType != null ? part.contentType : "application/octet-stream"); + return new InputStreamRequestBody(part.getFileStream(), contentType); } public static OkHttpClient.Builder getDefaultOkHttpClientBuilder() { diff --git a/src/main/java/com/box/sdkgen/networking/inputstreamrequestbody/InputStreamRequestBody.java b/src/main/java/com/box/sdkgen/networking/inputstreamrequestbody/InputStreamRequestBody.java new file mode 100644 index 000000000..2105bc3a7 --- /dev/null +++ b/src/main/java/com/box/sdkgen/networking/inputstreamrequestbody/InputStreamRequestBody.java @@ -0,0 +1,86 @@ +package com.box.sdkgen.networking.inputstreamrequestbody; + +import java.io.ByteArrayInputStream; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import okhttp3.MediaType; +import okhttp3.RequestBody; +import okio.BufferedSink; +import okio.Okio; + +/** + * A request body that streams a caller-provided {@link InputStream} without buffering its content. + * + *

The body does not close the stream; the network client closes it once the request and all its + * retries finish. The body can be sent again on a retry only if the stream can be rewound without + * copying it: a {@link ByteArrayInputStream} via mark/reset, or a {@link FileInputStream} via its + * channel position. Any other stream can be sent only once. + */ +public class InputStreamRequestBody extends RequestBody { + + private static final long NO_FILE_POSITION = -1; + + private final InputStream stream; + private final MediaType contentType; + private final long initialFilePosition; + private boolean written; + + public InputStreamRequestBody(InputStream stream, MediaType contentType) { + this.stream = stream; + this.contentType = contentType; + if (stream instanceof ByteArrayInputStream) { + stream.mark(0); + } + this.initialFilePosition = readFilePosition(stream); + } + + @Override + public MediaType contentType() { + return contentType; + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + if (written) { + rewind(); + } + written = true; + sink.writeAll(Okio.source(stream)); + } + + /** + * Returns whether this body can be written again, either because it has not been written yet or + * because its stream can be rewound. + */ + public boolean canBeResent() { + return !written || isRewindable(); + } + + private boolean isRewindable() { + return stream instanceof ByteArrayInputStream || initialFilePosition != NO_FILE_POSITION; + } + + private void rewind() throws IOException { + if (stream instanceof ByteArrayInputStream) { + stream.reset(); + return; + } + if (initialFilePosition != NO_FILE_POSITION) { + ((FileInputStream) stream).getChannel().position(initialFilePosition); + return; + } + throw new IOException("Request body stream was already sent and cannot be rewound"); + } + + private static long readFilePosition(InputStream stream) { + if (!(stream instanceof FileInputStream)) { + return NO_FILE_POSITION; + } + try { + return ((FileInputStream) stream).getChannel().position(); + } catch (IOException e) { + return NO_FILE_POSITION; + } + } +} diff --git a/src/main/java/com/box/sdkgen/schemas/signrequestbase/SignRequestBase.java b/src/main/java/com/box/sdkgen/schemas/signrequestbase/SignRequestBase.java index b144af275..c02786273 100644 --- a/src/main/java/com/box/sdkgen/schemas/signrequestbase/SignRequestBase.java +++ b/src/main/java/com/box/sdkgen/schemas/signrequestbase/SignRequestBase.java @@ -48,10 +48,10 @@ public class SignRequestBase extends SerializableObject { * Message to include in sign request email. The field is cleaned through sanitization of specific * characters. However, some html tags are allowed. Links included in the message are also * converted to hyperlinks in the email. The message may contain the following html tags including - * `a`, `abbr`, `acronym`, `b`, `blockquote`, `code`, `em`, `i`, `ul`, `li`, `ol`, and `strong`. - * Be aware that when the text to html ratio is too high, the email may end up in spam filters. - * Custom styles on these tags are not allowed. If this field is not passed, a default message - * will be used. + * `a`, `abbr`, `b`, `blockquote`, `code`, `em`, `i`, `ul`, `li`, `ol`, and `strong`. Be aware + * that when the text to html ratio is too high, the email may end up in spam filters. Custom + * styles on these tags are not allowed. If this field is not passed, a default message will be + * used. */ @JsonProperty("email_message") @Nullable diff --git a/src/main/java/com/box/sdkgen/schemas/v2026r0/aisessionsv2026r0/AiSessionsV2026R0.java b/src/main/java/com/box/sdkgen/schemas/v2026r0/aisessionsv2026r0/AiSessionsV2026R0.java new file mode 100644 index 000000000..9918160b7 --- /dev/null +++ b/src/main/java/com/box/sdkgen/schemas/v2026r0/aisessionsv2026r0/AiSessionsV2026R0.java @@ -0,0 +1,117 @@ +package com.box.sdkgen.schemas.v2026r0.aisessionsv2026r0; + +import com.box.sdkgen.internal.Nullable; +import com.box.sdkgen.internal.NullableFieldTracker; +import com.box.sdkgen.internal.SerializableObject; +import com.box.sdkgen.schemas.v2026r0.aisessionv2026r0.AiSessionV2026R0; +import com.fasterxml.jackson.annotation.JsonFilter; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import java.util.Objects; + +/** A paginated list of AI sessions. */ +@JsonFilter("nullablePropertyFilter") +public class AiSessionsV2026R0 extends SerializableObject { + + /** A list of AI sessions. The list is empty when there are no results. */ + protected final List entries; + + /** + * The limit that was used for these entries. This will be the same as the `limit` query parameter + * unless that value exceeded the maximum value allowed. The maximum value varies by API. + */ + protected final long limit; + + /** The marker for the start of the next page of results. */ + @JsonProperty("next_marker") + @Nullable + protected String nextMarker; + + public AiSessionsV2026R0( + @JsonProperty("entries") List entries, @JsonProperty("limit") long limit) { + super(); + this.entries = entries; + this.limit = limit; + } + + protected AiSessionsV2026R0(Builder builder) { + super(); + this.entries = builder.entries; + this.limit = builder.limit; + this.nextMarker = builder.nextMarker; + markNullableFieldsAsSet(builder.getExplicitlySetNullableFields()); + } + + public List getEntries() { + return entries; + } + + public long getLimit() { + return limit; + } + + public String getNextMarker() { + return nextMarker; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AiSessionsV2026R0 casted = (AiSessionsV2026R0) o; + return Objects.equals(entries, casted.entries) + && Objects.equals(limit, casted.limit) + && Objects.equals(nextMarker, casted.nextMarker); + } + + @Override + public int hashCode() { + return Objects.hash(entries, limit, nextMarker); + } + + @Override + public String toString() { + return "AiSessionsV2026R0{" + + "entries='" + + entries + + '\'' + + ", " + + "limit='" + + limit + + '\'' + + ", " + + "nextMarker='" + + nextMarker + + '\'' + + "}"; + } + + public static class Builder extends NullableFieldTracker { + + protected final List entries; + + protected final long limit; + + protected String nextMarker; + + public Builder(List entries, long limit) { + super(); + this.entries = entries; + this.limit = limit; + } + + public Builder nextMarker(String nextMarker) { + this.nextMarker = nextMarker; + this.markNullableFieldAsSet("next_marker"); + return this; + } + + public AiSessionsV2026R0 build() { + return new AiSessionsV2026R0(this); + } + } +} diff --git a/src/main/java/com/box/sdkgen/schemas/v2026r0/aisessionv2026r0/AiSessionV2026R0.java b/src/main/java/com/box/sdkgen/schemas/v2026r0/aisessionv2026r0/AiSessionV2026R0.java new file mode 100644 index 000000000..ee4513536 --- /dev/null +++ b/src/main/java/com/box/sdkgen/schemas/v2026r0/aisessionv2026r0/AiSessionV2026R0.java @@ -0,0 +1,289 @@ +package com.box.sdkgen.schemas.v2026r0.aisessionv2026r0; + +import com.box.sdkgen.internal.Nullable; +import com.box.sdkgen.internal.NullableFieldTracker; +import com.box.sdkgen.internal.SerializableObject; +import com.box.sdkgen.internal.utils.DateTimeUtils; +import com.box.sdkgen.schemas.v2026r0.userbasev2026r0.UserBaseV2026R0; +import com.box.sdkgen.serialization.json.EnumWrapper; +import com.fasterxml.jackson.annotation.JsonFilter; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import java.time.OffsetDateTime; +import java.util.Objects; + +/** + * A standard representation of an AI session. An AI session holds the conversation state for a + * series of interactions with a Box AI agent. Its `id` is the A2A context identifier for that + * conversation. + */ +@JsonFilter("nullablePropertyFilter") +public class AiSessionV2026R0 extends SerializableObject { + + /** The value is always `ai_session`. */ + @JsonDeserialize(using = AiSessionV2026R0TypeField.AiSessionV2026R0TypeFieldDeserializer.class) + @JsonSerialize(using = AiSessionV2026R0TypeField.AiSessionV2026R0TypeFieldSerializer.class) + protected EnumWrapper type; + + /** + * The unique identifier for the AI session. This is also the A2A `contextId` for the + * conversation. Treat the value as opaque. + */ + protected final String id; + + /** + * The display name of the AI session. Sessions created through the A2A API are named + * automatically. The value is `null` only when no name was recorded. + */ + @Nullable protected String name; + + /** + * The origin of the AI session. Currently always `api`. New values may be added, so clients must + * tolerate values they do not recognize. + */ + @JsonDeserialize( + using = AiSessionV2026R0SourceField.AiSessionV2026R0SourceFieldDeserializer.class) + @JsonSerialize(using = AiSessionV2026R0SourceField.AiSessionV2026R0SourceFieldSerializer.class) + protected EnumWrapper source; + + /** + * The OAuth client ID of the application that created the AI session, as shown in the Developer + * Console. The value is `null` if the application is not known. + */ + @JsonProperty("client_id") + @Nullable + protected String clientId; + + @JsonProperty("created_by") + protected final UserBaseV2026R0 createdBy; + + @JsonProperty("updated_by") + protected final UserBaseV2026R0 updatedBy; + + /** The date and time when the AI session was created. */ + @JsonProperty("created_at") + @JsonSerialize(using = DateTimeUtils.DateTimeSerializer.class) + @JsonDeserialize(using = DateTimeUtils.DateTimeDeserializer.class) + protected final OffsetDateTime createdAt; + + /** + * The date and time when the AI session was last updated. It advances on each turn of session + * activity, so it also serves as the most recently used ordering. + */ + @JsonProperty("updated_at") + @JsonSerialize(using = DateTimeUtils.DateTimeSerializer.class) + @JsonDeserialize(using = DateTimeUtils.DateTimeDeserializer.class) + protected final OffsetDateTime updatedAt; + + public AiSessionV2026R0( + @JsonProperty("id") String id, + @JsonProperty("created_by") UserBaseV2026R0 createdBy, + @JsonProperty("updated_by") UserBaseV2026R0 updatedBy, + @JsonProperty("created_at") OffsetDateTime createdAt, + @JsonProperty("updated_at") OffsetDateTime updatedAt) { + super(); + this.id = id; + this.createdBy = createdBy; + this.updatedBy = updatedBy; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.type = new EnumWrapper(AiSessionV2026R0TypeField.AI_SESSION); + this.source = new EnumWrapper(AiSessionV2026R0SourceField.API); + } + + protected AiSessionV2026R0(Builder builder) { + super(); + this.type = builder.type; + this.id = builder.id; + this.name = builder.name; + this.source = builder.source; + this.clientId = builder.clientId; + this.createdBy = builder.createdBy; + this.updatedBy = builder.updatedBy; + this.createdAt = builder.createdAt; + this.updatedAt = builder.updatedAt; + markNullableFieldsAsSet(builder.getExplicitlySetNullableFields()); + } + + public EnumWrapper getType() { + return type; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + public EnumWrapper getSource() { + return source; + } + + public String getClientId() { + return clientId; + } + + public UserBaseV2026R0 getCreatedBy() { + return createdBy; + } + + public UserBaseV2026R0 getUpdatedBy() { + return updatedBy; + } + + public OffsetDateTime getCreatedAt() { + return createdAt; + } + + public OffsetDateTime getUpdatedAt() { + return updatedAt; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AiSessionV2026R0 casted = (AiSessionV2026R0) o; + return Objects.equals(type, casted.type) + && Objects.equals(id, casted.id) + && Objects.equals(name, casted.name) + && Objects.equals(source, casted.source) + && Objects.equals(clientId, casted.clientId) + && Objects.equals(createdBy, casted.createdBy) + && Objects.equals(updatedBy, casted.updatedBy) + && Objects.equals(createdAt, casted.createdAt) + && Objects.equals(updatedAt, casted.updatedAt); + } + + @Override + public int hashCode() { + return Objects.hash( + type, id, name, source, clientId, createdBy, updatedBy, createdAt, updatedAt); + } + + @Override + public String toString() { + return "AiSessionV2026R0{" + + "type='" + + type + + '\'' + + ", " + + "id='" + + id + + '\'' + + ", " + + "name='" + + name + + '\'' + + ", " + + "source='" + + source + + '\'' + + ", " + + "clientId='" + + clientId + + '\'' + + ", " + + "createdBy='" + + createdBy + + '\'' + + ", " + + "updatedBy='" + + updatedBy + + '\'' + + ", " + + "createdAt='" + + createdAt + + '\'' + + ", " + + "updatedAt='" + + updatedAt + + '\'' + + "}"; + } + + public static class Builder extends NullableFieldTracker { + + protected EnumWrapper type; + + protected final String id; + + protected String name; + + protected EnumWrapper source; + + protected String clientId; + + protected final UserBaseV2026R0 createdBy; + + protected final UserBaseV2026R0 updatedBy; + + protected final OffsetDateTime createdAt; + + protected final OffsetDateTime updatedAt; + + public Builder( + String id, + UserBaseV2026R0 createdBy, + UserBaseV2026R0 updatedBy, + OffsetDateTime createdAt, + OffsetDateTime updatedAt) { + super(); + this.id = id; + this.createdBy = createdBy; + this.updatedBy = updatedBy; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + } + + public Builder type(AiSessionV2026R0TypeField type) { + this.type = new EnumWrapper(type); + return this; + } + + public Builder type(EnumWrapper type) { + this.type = type; + return this; + } + + public Builder name(String name) { + this.name = name; + this.markNullableFieldAsSet("name"); + return this; + } + + public Builder source(AiSessionV2026R0SourceField source) { + this.source = new EnumWrapper(source); + return this; + } + + public Builder source(EnumWrapper source) { + this.source = source; + return this; + } + + public Builder clientId(String clientId) { + this.clientId = clientId; + this.markNullableFieldAsSet("client_id"); + return this; + } + + public AiSessionV2026R0 build() { + if (this.type == null) { + this.type = + new EnumWrapper(AiSessionV2026R0TypeField.AI_SESSION); + } + if (this.source == null) { + this.source = new EnumWrapper(AiSessionV2026R0SourceField.API); + } + return new AiSessionV2026R0(this); + } + } +} diff --git a/src/main/java/com/box/sdkgen/schemas/v2026r0/aisessionv2026r0/AiSessionV2026R0SourceField.java b/src/main/java/com/box/sdkgen/schemas/v2026r0/aisessionv2026r0/AiSessionV2026R0SourceField.java new file mode 100644 index 000000000..d63f712b4 --- /dev/null +++ b/src/main/java/com/box/sdkgen/schemas/v2026r0/aisessionv2026r0/AiSessionV2026R0SourceField.java @@ -0,0 +1,64 @@ +package com.box.sdkgen.schemas.v2026r0.aisessionv2026r0; + +import com.box.sdkgen.serialization.json.EnumWrapper; +import com.box.sdkgen.serialization.json.Valuable; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import java.io.IOException; +import java.util.Arrays; + +public enum AiSessionV2026R0SourceField implements Valuable { + API("api"); + + private final String value; + + AiSessionV2026R0SourceField(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + public static class AiSessionV2026R0SourceFieldDeserializer + extends JsonDeserializer> { + + public AiSessionV2026R0SourceFieldDeserializer() { + super(); + } + + @Override + public EnumWrapper deserialize( + JsonParser p, DeserializationContext ctxt) throws IOException { + String value = p.getValueAsString(); + return Arrays.stream(AiSessionV2026R0SourceField.values()) + .filter((v) -> v.getValue().equalsIgnoreCase(value)) + .findFirst() + .map(EnumWrapper::new) + .orElse(new EnumWrapper(value)); + } + } + + public static class AiSessionV2026R0SourceFieldSerializer + extends JsonSerializer> { + + public AiSessionV2026R0SourceFieldSerializer() { + super(); + } + + @Override + public void serialize( + EnumWrapper value, + JsonGenerator gen, + SerializerProvider serializers) + throws IOException { + gen.writeString(value.getStringValue()); + } + } +} diff --git a/src/main/java/com/box/sdkgen/schemas/v2026r0/aisessionv2026r0/AiSessionV2026R0TypeField.java b/src/main/java/com/box/sdkgen/schemas/v2026r0/aisessionv2026r0/AiSessionV2026R0TypeField.java new file mode 100644 index 000000000..ad1bcfb11 --- /dev/null +++ b/src/main/java/com/box/sdkgen/schemas/v2026r0/aisessionv2026r0/AiSessionV2026R0TypeField.java @@ -0,0 +1,64 @@ +package com.box.sdkgen.schemas.v2026r0.aisessionv2026r0; + +import com.box.sdkgen.serialization.json.EnumWrapper; +import com.box.sdkgen.serialization.json.Valuable; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import java.io.IOException; +import java.util.Arrays; + +public enum AiSessionV2026R0TypeField implements Valuable { + AI_SESSION("ai_session"); + + private final String value; + + AiSessionV2026R0TypeField(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + public static class AiSessionV2026R0TypeFieldDeserializer + extends JsonDeserializer> { + + public AiSessionV2026R0TypeFieldDeserializer() { + super(); + } + + @Override + public EnumWrapper deserialize( + JsonParser p, DeserializationContext ctxt) throws IOException { + String value = p.getValueAsString(); + return Arrays.stream(AiSessionV2026R0TypeField.values()) + .filter((v) -> v.getValue().equalsIgnoreCase(value)) + .findFirst() + .map(EnumWrapper::new) + .orElse(new EnumWrapper(value)); + } + } + + public static class AiSessionV2026R0TypeFieldSerializer + extends JsonSerializer> { + + public AiSessionV2026R0TypeFieldSerializer() { + super(); + } + + @Override + public void serialize( + EnumWrapper value, + JsonGenerator gen, + SerializerProvider serializers) + throws IOException { + gen.writeString(value.getStringValue()); + } + } +} diff --git a/src/test/java/com/box/sdkgen/networking/boxnetworkclient/BoxNetworkClientUploadRetryTest.java b/src/test/java/com/box/sdkgen/networking/boxnetworkclient/BoxNetworkClientUploadRetryTest.java new file mode 100644 index 000000000..eda0cf46f --- /dev/null +++ b/src/test/java/com/box/sdkgen/networking/boxnetworkclient/BoxNetworkClientUploadRetryTest.java @@ -0,0 +1,296 @@ +package com.box.sdkgen.networking.boxnetworkclient; + +import static com.box.sdkgen.serialization.json.JsonManager.jsonToSerializedData; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.box.sdkgen.box.errors.BoxAPIError; +import com.box.sdkgen.networking.fetchoptions.FetchOptions; +import com.box.sdkgen.networking.fetchoptions.MultipartItem; +import com.box.sdkgen.networking.fetchresponse.FetchResponse; +import com.box.sdkgen.networking.interceptors.Interceptor; +import com.box.sdkgen.networking.network.NetworkSession; +import com.box.sdkgen.networking.retries.BoxRetryStrategy; +import com.box.sdkgen.networking.retries.RetryStrategy; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Queue; +import java.util.Random; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; +import okhttp3.ConnectionSpec; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +@Timeout(value = 30, threadMode = Timeout.ThreadMode.SEPARATE_THREAD) +public class BoxNetworkClientUploadRetryTest { + + private static final byte[] FILE_CONTENT = randomBytes(256 * 1024); + private static final int SUCCESS_STATUS = 201; + + private final List receivedBodies = Collections.synchronizedList(new ArrayList<>()); + private final List receivedCustomHeaders = + Collections.synchronizedList(new ArrayList<>()); + private final Queue failureStatuses = new ConcurrentLinkedQueue<>(); + private final BoxNetworkClient client = + new BoxNetworkClient( + BoxNetworkClient.getDefaultOkHttpClientBuilder() + .connectionSpecs(Collections.singletonList(ConnectionSpec.CLEARTEXT)) + .build()); + private final ExecutorService serverExecutor = Executors.newCachedThreadPool(); + private HttpServer server; + private String url; + + @BeforeEach + public void startServer() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/", this::respond); + server.setExecutor(serverExecutor); + server.start(); + url = "http://127.0.0.1:" + server.getAddress().getPort() + "/files/content"; + } + + @AfterEach + public void stopServer() { + server.stop(0); + serverExecutor.shutdownNow(); + } + + @Test + public void testMultipartUploadWithByteArrayStreamIsRetriedWithFullContent() { + failureStatuses.add(429); + + FetchResponse response = client.fetch(multipartUpload(new ByteArrayInputStream(FILE_CONTENT))); + + assertEquals(SUCCESS_STATUS, response.getStatus()); + assertEquals(2, receivedBodies.size()); + assertContainsFileContent(receivedBodies.get(0)); + assertArrayEquals(receivedBodies.get(0), receivedBodies.get(1)); + } + + @Test + public void testMultipartUploadWithFileStreamIsRetriedWithFullContent() throws IOException { + failureStatuses.add(503); + + try (FileInputStream stream = new FileInputStream(createTempFile())) { + FetchResponse response = client.fetch(multipartUpload(stream)); + + assertEquals(SUCCESS_STATUS, response.getStatus()); + assertFalse(stream.getChannel().isOpen()); + } + assertEquals(2, receivedBodies.size()); + assertContainsFileContent(receivedBodies.get(0)); + assertArrayEquals(receivedBodies.get(0), receivedBodies.get(1)); + } + + @Test + public void testMultipartUploadWithInterceptorIsRetriedWithFullContent() { + failureStatuses.add(429); + Interceptor headerInterceptor = + new Interceptor() { + @Override + public FetchOptions beforeRequest(FetchOptions options) { + return new FetchOptions.Builder(options.getUrl(), options.getMethod()) + .headers(Collections.singletonMap("X-Custom-Header", "value")) + .contentType(options.getContentType()) + .multipartData(options.getMultipartData()) + .build(); + } + + @Override + public FetchResponse afterRequest(FetchResponse response) { + return response; + } + }; + NetworkSession networkSession = + networkSessionWithoutRetryDelay().withInterceptors(Arrays.asList(headerInterceptor)); + + FetchResponse response = + client.fetch(multipartUpload(new ByteArrayInputStream(FILE_CONTENT), networkSession)); + + assertEquals(SUCCESS_STATUS, response.getStatus()); + assertEquals(Arrays.asList("value", "value"), receivedCustomHeaders); + assertEquals(2, receivedBodies.size()); + assertContainsFileContent(receivedBodies.get(0)); + assertArrayEquals(receivedBodies.get(0), receivedBodies.get(1)); + } + + @Test + public void testMultipartUploadWithStreamThatCannotBeRewoundIsNotRetried() throws IOException { + failureStatuses.add(429); + InputStream stream = new BufferedInputStream(Files.newInputStream(createTempFile().toPath())); + + BoxAPIError error = + assertThrows(BoxAPIError.class, () -> client.fetch(multipartUpload(stream))); + + assertEquals(429, error.getResponseInfo().getStatusCode()); + assertEquals("0", error.getResponseInfo().getHeaders().get("Retry-After")); + assertEquals(1, receivedBodies.size()); + assertThrows(IOException.class, stream::available); + } + + @Test + public void testRetryStrategyIsCalledWhenUploadStreamCannotBeRewound() { + failureStatuses.add(429); + AtomicInteger retryStrategyCalls = new AtomicInteger(); + RetryStrategy retryStrategy = + new RetryStrategy() { + @Override + public boolean shouldRetry( + FetchOptions fetchOptions, FetchResponse fetchResponse, int attemptNumber) { + retryStrategyCalls.incrementAndGet(); + return true; + } + + @Override + public double retryAfter( + FetchOptions fetchOptions, FetchResponse fetchResponse, int attemptNumber) { + return 0; + } + }; + NetworkSession networkSession = + new NetworkSession.Builder().retryStrategy(retryStrategy).build(); + InputStream stream = new BufferedInputStream(new ByteArrayInputStream(FILE_CONTENT)); + + assertThrows(BoxAPIError.class, () -> client.fetch(multipartUpload(stream, networkSession))); + + assertEquals(1, retryStrategyCalls.get()); + assertEquals(1, receivedBodies.size()); + } + + @Test + public void testUploadPartWithStreamThatCannotBeRewoundIsRetriedWithFullContent() { + failureStatuses.add(429); + InputStream stream = new BufferedInputStream(new ByteArrayInputStream(FILE_CONTENT)); + FetchOptions options = + new FetchOptions.Builder(url, "PUT") + .contentType("application/octet-stream") + .fileStream(stream) + .networkSession(networkSessionWithoutRetryDelay()) + .build(); + + FetchResponse response = client.fetch(options); + + assertEquals(SUCCESS_STATUS, response.getStatus()); + assertEquals(2, receivedBodies.size()); + assertArrayEquals(FILE_CONTENT, receivedBodies.get(0)); + assertArrayEquals(FILE_CONTENT, receivedBodies.get(1)); + } + + @Test + public void testUploadErrorDoesNotIncludeFileContent() throws IOException { + failureStatuses.add(409); + + try (FileInputStream stream = new FileInputStream(createTempFile())) { + BoxAPIError error = + assertThrows(BoxAPIError.class, () -> client.fetch(multipartUpload(stream))); + + assertEquals(409, error.getResponseInfo().getStatusCode()); + assertTrue(error.toString().contains("body='null'")); + } + assertEquals(1, receivedBodies.size()); + } + + private FetchOptions multipartUpload(InputStream fileStream) { + return multipartUpload(fileStream, networkSessionWithoutRetryDelay()); + } + + private FetchOptions multipartUpload(InputStream fileStream, NetworkSession networkSession) { + List parts = + Arrays.asList( + new MultipartItem.Builder("attributes") + .data(jsonToSerializedData("{\"name\":\"file.bin\",\"parent\":{\"id\":\"0\"}}")) + .build(), + new MultipartItem.Builder("file").fileStream(fileStream).fileName("file.bin").build()); + return new FetchOptions.Builder(url, "POST") + .contentType("multipart/form-data") + .multipartData(parts) + .networkSession(networkSession) + .build(); + } + + private static NetworkSession networkSessionWithoutRetryDelay() { + return new NetworkSession.Builder() + .retryStrategy(new BoxRetryStrategy.Builder().retryBaseInterval(0).build()) + .build(); + } + + private void respond(HttpExchange exchange) throws IOException { + receivedBodies.add(readAll(exchange.getRequestBody())); + receivedCustomHeaders.add(exchange.getRequestHeaders().getFirst("X-Custom-Header")); + Integer failureStatus = failureStatuses.poll(); + byte[] responseBody = "{}".getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + if (failureStatus != null && failureStatus == 429) { + exchange.getResponseHeaders().add("Retry-After", "0"); + } + exchange.sendResponseHeaders( + failureStatus != null ? failureStatus : SUCCESS_STATUS, responseBody.length); + try (OutputStream output = exchange.getResponseBody()) { + output.write(responseBody); + } + } + + private static void assertContainsFileContent(byte[] body) { + assertTrue( + indexOf(body, FILE_CONTENT) >= 0, "Request body does not contain the full file content"); + } + + private static int indexOf(byte[] array, byte[] target) { + outer: + for (int i = 0; i <= array.length - target.length; i++) { + for (int j = 0; j < target.length; j++) { + if (array[i + j] != target[j]) { + continue outer; + } + } + return i; + } + return -1; + } + + private static byte[] readAll(InputStream input) throws IOException { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + byte[] buffer = new byte[8192]; + int read; + while ((read = input.read(buffer)) != -1) { + output.write(buffer, 0, read); + } + return output.toByteArray(); + } + + private static File createTempFile() throws IOException { + File file = Files.createTempFile("upload-retry", ".bin").toFile(); + file.deleteOnExit(); + Files.write(file.toPath(), FILE_CONTENT); + return file; + } + + private static byte[] randomBytes(int size) { + byte[] bytes = new byte[size]; + new Random(0).nextBytes(bytes); + return bytes; + } +} diff --git a/src/test/java/com/box/sdkgen/networking/inputstreamrequestbody/InputStreamRequestBodyTest.java b/src/test/java/com/box/sdkgen/networking/inputstreamrequestbody/InputStreamRequestBodyTest.java new file mode 100644 index 000000000..b031a6adc --- /dev/null +++ b/src/test/java/com/box/sdkgen/networking/inputstreamrequestbody/InputStreamRequestBodyTest.java @@ -0,0 +1,102 @@ +package com.box.sdkgen.networking.inputstreamrequestbody; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FilterInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.Arrays; +import okhttp3.MediaType; +import okio.Buffer; +import org.junit.jupiter.api.Test; + +public class InputStreamRequestBodyTest { + + private static final MediaType CONTENT_TYPE = MediaType.parse("application/octet-stream"); + private static final byte[] CONTENT = "0123456789abcdef".getBytes(StandardCharsets.UTF_8); + private static final int INITIAL_POSITION = 4; + + @Test + public void testByteArrayStreamIsSentAgainFromItsInitialPosition() throws IOException { + ByteArrayInputStream stream = new ByteArrayInputStream(CONTENT); + stream.skip(INITIAL_POSITION); + InputStreamRequestBody body = new InputStreamRequestBody(stream, CONTENT_TYPE); + byte[] expected = Arrays.copyOfRange(CONTENT, INITIAL_POSITION, CONTENT.length); + + assertArrayEquals(expected, write(body)); + assertTrue(body.canBeResent()); + assertArrayEquals(expected, write(body)); + } + + @Test + public void testFileStreamIsSentAgainFromItsInitialPosition() throws IOException { + File file = createTempFile(); + try (FileInputStream stream = new FileInputStream(file)) { + stream.skip(INITIAL_POSITION); + InputStreamRequestBody body = new InputStreamRequestBody(stream, CONTENT_TYPE); + byte[] expected = Arrays.copyOfRange(CONTENT, INITIAL_POSITION, CONTENT.length); + + assertArrayEquals(expected, write(body)); + assertTrue(body.canBeResent()); + assertArrayEquals(expected, write(body)); + } + } + + @Test + public void testStreamThatCannotBeRewoundIsSentOnlyOnce() throws IOException { + InputStream stream = new BufferedInputStream(new ByteArrayInputStream(CONTENT)); + InputStreamRequestBody body = new InputStreamRequestBody(stream, CONTENT_TYPE); + + assertTrue(body.canBeResent()); + assertArrayEquals(CONTENT, write(body)); + assertFalse(body.canBeResent()); + assertThrows(IOException.class, () -> write(body)); + } + + @Test + public void testStreamIsNotClosedAfterBeingSent() throws IOException { + CloseTrackingInputStream stream = + new CloseTrackingInputStream(new ByteArrayInputStream(CONTENT)); + InputStreamRequestBody body = new InputStreamRequestBody(stream, CONTENT_TYPE); + + write(body); + + assertFalse(stream.closed); + } + + private static byte[] write(InputStreamRequestBody body) throws IOException { + Buffer buffer = new Buffer(); + body.writeTo(buffer); + return buffer.readByteArray(); + } + + private static File createTempFile() throws IOException { + File file = Files.createTempFile("input-stream-request-body", ".bin").toFile(); + file.deleteOnExit(); + Files.write(file.toPath(), CONTENT); + return file; + } + + private static class CloseTrackingInputStream extends FilterInputStream { + private boolean closed; + + CloseTrackingInputStream(InputStream in) { + super(in); + } + + @Override + public void close() throws IOException { + closed = true; + super.close(); + } + } +} diff --git a/src/test/java/com/box/sdkgen/test/BoxNetworkClientRetryTest.java b/src/test/java/com/box/sdkgen/test/BoxNetworkClientRetryTest.java index 13dc52822..f714afe8a 100644 --- a/src/test/java/com/box/sdkgen/test/BoxNetworkClientRetryTest.java +++ b/src/test/java/com/box/sdkgen/test/BoxNetworkClientRetryTest.java @@ -124,7 +124,7 @@ public void testRetryStrategyReceivesRegeneratedRequestData() throws Exception { } @Test - public void testInterceptorRunsOnEachRetryWithRebuiltData() throws Exception { + public void testInterceptorRunsOnEachRetryBeforeDataIsRebuilt() throws Exception { try (MockWebServer server = new MockWebServer()) { server.enqueue(jsonResponse(500, "{\"error\":\"retry\"}")); server.enqueue(jsonResponse(200, "{\"ok\":true}")); @@ -158,7 +158,74 @@ public FetchResponse afterRequest(FetchResponse response) { .networkSession(networkSession) .build()); - assertEquals(Arrays.asList("D1", "D2"), interceptorData); + assertEquals(Arrays.asList("D1", "D1"), interceptorData); + assertEquals("attempt=D1", takeBody(server)); + assertEquals("attempt=D2", takeBody(server)); + assertEquals(1, dataFactory.calls); + } + } + + @Test + public void testDataFactoryRemovedByInterceptorIsNotUsed() throws Exception { + try (MockWebServer server = new MockWebServer()) { + server.enqueue(jsonResponse(500, "{\"error\":\"retry\"}")); + server.enqueue(jsonResponse(200, "{\"ok\":true}")); + server.start(); + + NetworkSession networkSession = + new NetworkSession() + .withInterceptors( + Arrays.asList( + interceptorReplacingOptions( + options -> + baseOptions( + options.getUrl(), jsonToSerializedData("{\"attempt\":\"I\"}")) + .build()))) + .withRetryStrategy( + retryWhen((options, response, attempt) -> response.getStatus() == 500)); + + CountingDataFactory dataFactory = new CountingDataFactory(); + testNetworkClient() + .fetch( + baseOptions(server.url("/").toString(), jsonToSerializedData("{\"attempt\":\"D1\"}")) + .dataFactory(dataFactory) + .networkSession(networkSession) + .build()); + + assertEquals("attempt=I", takeBody(server)); + assertEquals("attempt=I", takeBody(server)); + assertEquals(0, dataFactory.calls); + } + } + + @Test + public void testDataFactoryAddedByInterceptorIsUsedOnRetry() throws Exception { + try (MockWebServer server = new MockWebServer()) { + server.enqueue(jsonResponse(500, "{\"error\":\"retry\"}")); + server.enqueue(jsonResponse(200, "{\"ok\":true}")); + server.start(); + + CountingDataFactory dataFactory = new CountingDataFactory(); + NetworkSession networkSession = + new NetworkSession() + .withInterceptors( + Arrays.asList( + interceptorReplacingOptions( + options -> + baseOptions(options.getUrl(), options.getData()) + .dataFactory(dataFactory) + .build()))) + .withRetryStrategy( + retryWhen((options, response, attempt) -> response.getStatus() == 500)); + + testNetworkClient() + .fetch( + baseOptions(server.url("/").toString(), jsonToSerializedData("{\"attempt\":\"D1\"}")) + .networkSession(networkSession) + .build()); + + assertEquals("attempt=D1", takeBody(server)); + assertEquals("attempt=D2", takeBody(server)); assertEquals(1, dataFactory.calls); } } @@ -353,6 +420,21 @@ private JwtPayload decodePayload(String assertion) throws Exception { return objectMapper.readValue(payload, JwtPayload.class); } + private Interceptor interceptorReplacingOptions( + java.util.function.UnaryOperator replace) { + return new Interceptor() { + @Override + public FetchOptions beforeRequest(FetchOptions options) { + return replace.apply(options); + } + + @Override + public FetchResponse afterRequest(FetchResponse response) { + return response; + } + }; + } + private interface RetryPredicate { boolean shouldRetry(FetchOptions options, FetchResponse response, int attemptNumber); }