|
| 1 | +/* |
| 2 | + * OpenFGA |
| 3 | + * A high performance and flexible authorization/permission engine built for developers and inspired by Google Zanzibar. |
| 4 | + * |
| 5 | + * The version of the OpenAPI document: 1.x |
| 6 | + |
| 7 | + * |
| 8 | + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). |
| 9 | + * https://openapi-generator.tech |
| 10 | + * Do not edit the class manually. |
| 11 | + */ |
| 12 | + |
| 13 | +package dev.openfga.sdk.api; |
| 14 | + |
| 15 | +import static dev.openfga.sdk.util.StringUtil.isNullOrWhitespace; |
| 16 | + |
| 17 | +import com.fasterxml.jackson.core.type.TypeReference; |
| 18 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 19 | +import dev.openfga.sdk.api.client.ApiClient; |
| 20 | +import dev.openfga.sdk.api.configuration.Configuration; |
| 21 | +import dev.openfga.sdk.api.model.Status; |
| 22 | +import dev.openfga.sdk.api.model.StreamResult; |
| 23 | +import dev.openfga.sdk.errors.ApiException; |
| 24 | +import dev.openfga.sdk.errors.FgaInvalidParameterException; |
| 25 | +import java.net.http.HttpRequest; |
| 26 | +import java.net.http.HttpResponse; |
| 27 | +import java.util.concurrent.CompletableFuture; |
| 28 | +import java.util.function.Consumer; |
| 29 | +import java.util.stream.Stream; |
| 30 | + |
| 31 | +/** |
| 32 | + * Base class for handling streaming API responses. |
| 33 | + * This class provides generic streaming functionality that can be reused across |
| 34 | + * different streaming endpoints by handling the common streaming parsing and error handling logic. |
| 35 | + * |
| 36 | + * @param <T> The type of response objects in the stream |
| 37 | + */ |
| 38 | +public abstract class BaseStreamingApi<T> { |
| 39 | + protected final Configuration configuration; |
| 40 | + protected final ApiClient apiClient; |
| 41 | + protected final ObjectMapper objectMapper; |
| 42 | + protected final TypeReference<StreamResult<T>> streamResultTypeRef; |
| 43 | + |
| 44 | + /** |
| 45 | + * Constructor for BaseStreamingApi |
| 46 | + * |
| 47 | + * @param configuration The API configuration |
| 48 | + * @param apiClient The API client for making HTTP requests |
| 49 | + * @param streamResultTypeRef TypeReference for deserializing StreamResult<T> |
| 50 | + */ |
| 51 | + protected BaseStreamingApi( |
| 52 | + Configuration configuration, ApiClient apiClient, TypeReference<StreamResult<T>> streamResultTypeRef) { |
| 53 | + this.configuration = configuration; |
| 54 | + this.apiClient = apiClient; |
| 55 | + this.objectMapper = apiClient.getObjectMapper(); |
| 56 | + this.streamResultTypeRef = streamResultTypeRef; |
| 57 | + } |
| 58 | + |
| 59 | + /** |
| 60 | + * Process a streaming response asynchronously. |
| 61 | + * Each line in the response is parsed and delivered to the consumer callback. |
| 62 | + * |
| 63 | + * @param request The HTTP request to execute |
| 64 | + * @param consumer Callback to handle each response object (invoked asynchronously) |
| 65 | + * @param errorConsumer Optional callback to handle errors during streaming |
| 66 | + * @return CompletableFuture<Void> that completes when streaming finishes |
| 67 | + */ |
| 68 | + protected CompletableFuture<Void> processStreamingResponse( |
| 69 | + HttpRequest request, Consumer<T> consumer, Consumer<Throwable> errorConsumer) { |
| 70 | + |
| 71 | + // Use async HTTP client with streaming body handler |
| 72 | + // ofLines() provides line-by-line streaming |
| 73 | + return apiClient |
| 74 | + .getHttpClient() |
| 75 | + .sendAsync(request, HttpResponse.BodyHandlers.ofLines()) |
| 76 | + .thenCompose(response -> { |
| 77 | + // Check response status |
| 78 | + int statusCode = response.statusCode(); |
| 79 | + if (statusCode < 200 || statusCode >= 300) { |
| 80 | + ApiException apiException = |
| 81 | + new ApiException(statusCode, "API error: " + statusCode, response.headers(), null); |
| 82 | + return CompletableFuture.failedFuture(apiException); |
| 83 | + } |
| 84 | + |
| 85 | + // Process the stream - this runs on HttpClient's executor thread |
| 86 | + try (Stream<String> lines = response.body()) { |
| 87 | + lines.forEach(line -> { |
| 88 | + if (!isNullOrWhitespace(line)) { |
| 89 | + processLine(line, consumer, errorConsumer); |
| 90 | + } |
| 91 | + }); |
| 92 | + return CompletableFuture.completedFuture((Void) null); |
| 93 | + } catch (Exception e) { |
| 94 | + return CompletableFuture.failedFuture(e); |
| 95 | + } |
| 96 | + }) |
| 97 | + .handle((result, throwable) -> { |
| 98 | + if (throwable != null) { |
| 99 | + // Unwrap CompletionException to get the original exception |
| 100 | + Throwable actualException = throwable; |
| 101 | + if (throwable instanceof java.util.concurrent.CompletionException |
| 102 | + && throwable.getCause() != null) { |
| 103 | + actualException = throwable.getCause(); |
| 104 | + } |
| 105 | + |
| 106 | + if (errorConsumer != null) { |
| 107 | + errorConsumer.accept(actualException); |
| 108 | + } |
| 109 | + // Re-throw to keep the CompletableFuture in failed state |
| 110 | + if (actualException instanceof RuntimeException) { |
| 111 | + throw (RuntimeException) actualException; |
| 112 | + } |
| 113 | + throw new RuntimeException(actualException); |
| 114 | + } |
| 115 | + return result; |
| 116 | + }); |
| 117 | + } |
| 118 | + |
| 119 | + /** |
| 120 | + * Process a single line from the stream |
| 121 | + * |
| 122 | + * @param line The JSON line to process |
| 123 | + * @param consumer Callback to handle the parsed result |
| 124 | + * @param errorConsumer Optional callback to handle errors |
| 125 | + */ |
| 126 | + private void processLine(String line, Consumer<T> consumer, Consumer<Throwable> errorConsumer) { |
| 127 | + try { |
| 128 | + // Parse the JSON line to extract the object |
| 129 | + StreamResult<T> streamResult = objectMapper.readValue(line, streamResultTypeRef); |
| 130 | + |
| 131 | + if (streamResult.getError() != null) { |
| 132 | + // Handle error in stream |
| 133 | + if (errorConsumer != null) { |
| 134 | + Status error = streamResult.getError(); |
| 135 | + String errorMessage = error.getMessage() != null |
| 136 | + ? "Stream error: " + error.getMessage() |
| 137 | + : "Stream error: " + (error.getCode() != null ? "code " + error.getCode() : "unknown"); |
| 138 | + errorConsumer.accept(new ApiException(errorMessage)); |
| 139 | + } |
| 140 | + } else if (streamResult.getResult() != null) { |
| 141 | + // Deliver the response object to the consumer |
| 142 | + T result = streamResult.getResult(); |
| 143 | + if (result != null) { |
| 144 | + consumer.accept(result); |
| 145 | + } |
| 146 | + } |
| 147 | + } catch (Exception e) { |
| 148 | + if (errorConsumer != null) { |
| 149 | + errorConsumer.accept(e); |
| 150 | + } |
| 151 | + } |
| 152 | + } |
| 153 | + |
| 154 | + /** |
| 155 | + * Build an HTTP request for the streaming endpoint |
| 156 | + * |
| 157 | + * @param method HTTP method (e.g., "POST") |
| 158 | + * @param path The API path |
| 159 | + * @param body The request body |
| 160 | + * @param configuration The configuration to use |
| 161 | + * @return HttpRequest ready to execute |
| 162 | + * @throws ApiException if request building fails |
| 163 | + * @throws FgaInvalidParameterException if parameters are invalid |
| 164 | + */ |
| 165 | + protected HttpRequest buildHttpRequest(String method, String path, Object body, Configuration configuration) |
| 166 | + throws ApiException, FgaInvalidParameterException { |
| 167 | + try { |
| 168 | + byte[] bodyBytes = objectMapper.writeValueAsBytes(body); |
| 169 | + HttpRequest.Builder requestBuilder = ApiClient.requestBuilder(method, path, bodyBytes, configuration); |
| 170 | + |
| 171 | + // Apply request interceptors if any |
| 172 | + var interceptor = apiClient.getRequestInterceptor(); |
| 173 | + if (interceptor != null) { |
| 174 | + interceptor.accept(requestBuilder); |
| 175 | + } |
| 176 | + |
| 177 | + return requestBuilder.build(); |
| 178 | + } catch (Exception e) { |
| 179 | + throw new ApiException(e); |
| 180 | + } |
| 181 | + } |
| 182 | +} |
0 commit comments