diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 260533c..552eeb5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -36,3 +36,26 @@ jobs: - name: Test run: ./gradlew test + publish: + needs: [ compile, test ] + if: github.event_name == 'push' && contains(github.ref, 'refs/tags/') + runs-on: ubuntu-latest + + steps: + - name: Checkout repo + uses: actions/checkout@v3 + + - name: Set up Java + id: setup-jre + uses: actions/setup-java@v1 + with: + java-version: "11" + architecture: x64 + + - name: Publish to maven + run: | + ./gradlew publish + env: + MAVEN_USERNAME: ${{ secrets.MAVEN_USERNAME }} + MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }} + MAVEN_PUBLISH_REGISTRY_URL: "https://s01.oss.sonatype.org/content/repositories/releases/" diff --git a/README.md b/README.md new file mode 100644 index 0000000..1c3ce8f --- /dev/null +++ b/README.md @@ -0,0 +1,157 @@ +# Intercom Java Library + +[![fern shield](https://img.shields.io/badge/%F0%9F%8C%BF-Built%20with%20Fern-brightgreen)](https://buildwithfern.com?utm_source=github&utm_medium=github&utm_campaign=readme&utm_source=https%3A%2F%2Fgithub.com%2Fintercom%2Fintercom-java) + +The Intercom Java library provides convenient access to the Intercom API from Java. + +## Usage + +Instantiate and use the client with the following: + +```java +package com.example.usage; + +import com.intercom.api.Intercom; +import com.intercom.api.resources.articles.requests.CreateArticleRequest; +import com.intercom.api.resources.articles.types.CreateArticleRequestState; + +public class Example { + public static void main(String[] args) { + Intercom client = Intercom + .builder() + .token("") + .build(); + + client.articles().create( + CreateArticleRequest + .builder() + .title("Thanks for everything") + .authorId(1295) + .description("Description of the Article") + .body("Body of the Article") + .state(CreateArticleRequestState.PUBLISHED) + .build() + ); + } +} +``` + +## Environments + +This SDK allows you to configure different environments for API requests. + +```java +import com.intercom.api.Intercom; +import com.intercom.api.core.Environment; + +Intercom client = Intercom + .builder() + .environment(Environment.USProduction) + .build(); +``` + +## Base Url + +You can set a custom base URL when constructing the client. + +```java +import com.intercom.api.Intercom; + +Intercom client = Intercom + .builder() + .url("https://example.com") + .build(); +``` + +## Exception Handling + +When the API returns a non-success status code (4xx or 5xx response), an API exception will be thrown. + +```java +import com.intercom.api.core.IntercomApiApiException; + +try { + client.articles().create(...); +} catch (IntercomApiApiException e) { + // Do something with the API exception... +} +``` + +## Advanced + +### Custom Client + +This SDK is built to work with any instance of `OkHttpClient`. By default, if no client is provided, the SDK will construct one. +However, you can pass your own client like so: + +```java +import com.intercom.api.Intercom; +import okhttp3.OkHttpClient; + +OkHttpClient customClient = ...; + +Intercom client = Intercom + .builder() + .httpClient(customClient) + .build(); +``` + +### Retries + +The SDK is instrumented with automatic retries with exponential backoff. A request will be retried as long +as the request is deemed retriable and the number of retry attempts has not grown larger than the configured +retry limit (default: 2). + +A request is deemed retriable when any of the following HTTP status codes is returned: + +- [408](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/408) (Timeout) +- [429](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429) (Too Many Requests) +- [5XX](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500) (Internal Server Errors) + +Use the `maxRetries` request option to configure this behavior. + +```java +import com.intercom.api.core.RequestOptions; + +client.articles().create( + ..., + RequestOptions + .builder() + .maxRetries(1) + .build() +); +``` + +### Timeouts + +The SDK defaults to a 60 second timeout. You can configure this with a timeout option at the client or request level. + +```java +import com.intercom.api.Intercom; +import com.intercom.api.core.RequestOptions; + +// Client level +Intercom client = Intercom + .builder() + .timeout(10) + .build(); + +// Request level +client.articles().create( + ..., + RequestOptions + .builder() + .timeout(10) + .build() +); +``` + +## Contributing + +While we value open-source contributions to this SDK, this library is generated programmatically. +Additions made directly to this library would have to be moved over to our generation code, +otherwise they would be overwritten upon the next generated release. Feel free to open a PR as +a proof of concept, but know that we will not be able to merge it as-is. We suggest opening +an issue first to discuss with us! + +On the other hand, contributions to the README are always very welcome! \ No newline at end of file diff --git a/build.gradle b/build.gradle index d311e1f..93668e9 100644 --- a/build.gradle +++ b/build.gradle @@ -42,6 +42,23 @@ java { } +group = 'io.intercom' + +version = '3.0.0-alpha0' + +jar { + dependsOn(":generatePomFileForMavenPublication") + archiveBaseName = "intercom-java" +} + +sourcesJar { + archiveBaseName = "intercom-java" +} + +javadocJar { + archiveBaseName = "intercom-java" +} + test { useJUnitPlatform() testLogging { @@ -49,3 +66,36 @@ test { } } +publishing { + publications { + maven(MavenPublication) { + groupId = 'io.intercom' + artifactId = 'intercom-java' + version = '3.0.0-alpha0' + from components.java + pom { + licenses { + license { + name = 'The MIT License (MIT)' + url = 'https://mit-license.org/' + } + } + scm { + connection = 'scm:git:git://github.com/intercom/intercom-java.git' + developerConnection = 'scm:git:git://github.com/intercom/intercom-java.git' + url = 'https://github.com/intercom/intercom-java' + } + } + } + } + repositories { + maven { + url "$System.env.MAVEN_PUBLISH_REGISTRY_URL" + credentials { + username "$System.env.MAVEN_USERNAME" + password "$System.env.MAVEN_PASSWORD" + } + } + } +} + diff --git a/settings.gradle b/settings.gradle index aed36fe..486d83d 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1 +1,3 @@ +rootProject.name = 'intercom-java' + include 'sample-app' \ No newline at end of file diff --git a/src/main/java/com/intercom/api/AsyncIntercomBuilder.java b/src/main/java/com/intercom/api/AsyncIntercomBuilder.java index 1573744..778432b 100644 --- a/src/main/java/com/intercom/api/AsyncIntercomBuilder.java +++ b/src/main/java/com/intercom/api/AsyncIntercomBuilder.java @@ -34,13 +34,21 @@ public AsyncIntercomBuilder url(String url) { } /** - * Sets the timeout (in seconds) for the client + * Sets the timeout (in seconds) for the client. Defaults to 60 seconds. */ public AsyncIntercomBuilder timeout(int timeout) { this.clientOptionsBuilder.timeout(timeout); return this; } + /** + * Sets the maximum number of retries for the client. Defaults to 2 retries. + */ + public AsyncIntercomBuilder maxRetries(int maxRetries) { + this.clientOptionsBuilder.maxRetries(maxRetries); + return this; + } + /** * Sets the underlying OkHttp client */ diff --git a/src/main/java/com/intercom/api/IntercomBuilder.java b/src/main/java/com/intercom/api/IntercomBuilder.java index 02ad048..ff8fbaa 100644 --- a/src/main/java/com/intercom/api/IntercomBuilder.java +++ b/src/main/java/com/intercom/api/IntercomBuilder.java @@ -34,13 +34,21 @@ public IntercomBuilder url(String url) { } /** - * Sets the timeout (in seconds) for the client + * Sets the timeout (in seconds) for the client. Defaults to 60 seconds. */ public IntercomBuilder timeout(int timeout) { this.clientOptionsBuilder.timeout(timeout); return this; } + /** + * Sets the maximum number of retries for the client. Defaults to 2 retries. + */ + public IntercomBuilder maxRetries(int maxRetries) { + this.clientOptionsBuilder.maxRetries(maxRetries); + return this; + } + /** * Sets the underlying OkHttp client */ diff --git a/src/main/java/com/intercom/api/core/ClientOptions.java b/src/main/java/com/intercom/api/core/ClientOptions.java index 9d841f2..8107f56 100644 --- a/src/main/java/com/intercom/api/core/ClientOptions.java +++ b/src/main/java/com/intercom/api/core/ClientOptions.java @@ -64,9 +64,10 @@ private ClientOptions( this.headers.putAll(headers); this.headers.putAll(new HashMap() { { + put("User-Agent", "io.intercom:intercom-java/3.0.0-alpha0"); put("X-Fern-Language", "JAVA"); put("X-Fern-SDK-Name", "com.intercom.fern:api-sdk"); - put("X-Fern-SDK-Version", "0.0.155"); + put("X-Fern-SDK-Version", "3.0.0-alpha0"); } }); this.headerSuppliers = headerSuppliers; @@ -133,12 +134,11 @@ public static final class Builder { private final Map> headerSuppliers = new HashMap<>(); - private int timeout = 60; + private int maxRetries = 2; - private OkHttpClient httpClient = new OkHttpClient.Builder() - .addInterceptor(new RetryInterceptor(3)) - .callTimeout(this.timeout, TimeUnit.SECONDS) - .build(); + private Optional timeout = Optional.empty(); + + private OkHttpClient httpClient = null; private Optional version = Optional.empty(); @@ -161,10 +161,26 @@ public Builder addHeader(String key, Supplier value) { * Override the timeout in seconds. Defaults to 60 seconds. */ public Builder timeout(int timeout) { + this.timeout = Optional.of(timeout); + return this; + } + + /** + * Override the timeout in seconds. Defaults to 60 seconds. + */ + public Builder timeout(Optional timeout) { this.timeout = timeout; return this; } + /** + * Override the maximum number of retries. Defaults to 2 retries. + */ + public Builder maxRetries(int maxRetries) { + this.maxRetries = maxRetries; + return this; + } + public Builder httpClient(OkHttpClient httpClient) { this.httpClient = httpClient; return this; @@ -179,7 +195,28 @@ public Builder version(ApiVersion version) { } public ClientOptions build() { - return new ClientOptions(environment, headers, headerSuppliers, httpClient, this.timeout, version); + OkHttpClient.Builder httpClientBuilder = + this.httpClient != null ? this.httpClient.newBuilder() : new OkHttpClient.Builder(); + + if (this.httpClient != null) { + timeout.ifPresent(timeout -> httpClientBuilder + .callTimeout(timeout, TimeUnit.SECONDS) + .connectTimeout(0, TimeUnit.SECONDS) + .writeTimeout(0, TimeUnit.SECONDS) + .readTimeout(0, TimeUnit.SECONDS)); + } else { + httpClientBuilder + .callTimeout(this.timeout.orElse(60), TimeUnit.SECONDS) + .connectTimeout(0, TimeUnit.SECONDS) + .writeTimeout(0, TimeUnit.SECONDS) + .readTimeout(0, TimeUnit.SECONDS) + .addInterceptor(new RetryInterceptor(this.maxRetries)); + } + + this.httpClient = httpClientBuilder.build(); + this.timeout = Optional.of(httpClient.callTimeoutMillis() / 1000); + + return new ClientOptions(environment, headers, headerSuppliers, httpClient, this.timeout.get(), version); } } } diff --git a/src/main/java/com/intercom/api/core/IntercomApiException.java b/src/main/java/com/intercom/api/core/IntercomApiException.java index 0dc0621..f99fe97 100644 --- a/src/main/java/com/intercom/api/core/IntercomApiException.java +++ b/src/main/java/com/intercom/api/core/IntercomApiException.java @@ -3,6 +3,12 @@ */ package com.intercom.api.core; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import okhttp3.Response; + /** * This exception type will be thrown for any non-2XX API responses. */ @@ -17,10 +23,25 @@ public class IntercomApiException extends IntercomException { */ private final Object body; + private final Map> headers; + public IntercomApiException(String message, int statusCode, Object body) { super(message); this.statusCode = statusCode; this.body = body; + this.headers = new HashMap<>(); + } + + public IntercomApiException(String message, int statusCode, Object body, Response rawResponse) { + super(message); + this.statusCode = statusCode; + this.body = body; + this.headers = new HashMap<>(); + rawResponse.headers().forEach(header -> { + String key = header.component1(); + String value = header.component2(); + this.headers.computeIfAbsent(key, _str -> new ArrayList<>()).add(value); + }); } /** @@ -37,6 +58,13 @@ public Object body() { return this.body; } + /** + * @return the headers + */ + public Map> headers() { + return this.headers; + } + @java.lang.Override public String toString() { return "IntercomApiException{" + "message: " + getMessage() + ", statusCode: " + statusCode + ", body: " + body diff --git a/src/main/java/com/intercom/api/core/IntercomHttpResponse.java b/src/main/java/com/intercom/api/core/IntercomHttpResponse.java new file mode 100644 index 0000000..9bf4035 --- /dev/null +++ b/src/main/java/com/intercom/api/core/IntercomHttpResponse.java @@ -0,0 +1,37 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.core; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import okhttp3.Response; + +public final class IntercomHttpResponse { + + private final T body; + + private final Map> headers; + + public IntercomHttpResponse(T body, Response rawResponse) { + this.body = body; + + Map> headers = new HashMap<>(); + rawResponse.headers().forEach(header -> { + String key = header.component1(); + String value = header.component2(); + headers.computeIfAbsent(key, _str -> new ArrayList<>()).add(value); + }); + this.headers = headers; + } + + public T body() { + return this.body; + } + + public Map> headers() { + return headers; + } +} diff --git a/src/main/java/com/intercom/api/core/RetryInterceptor.java b/src/main/java/com/intercom/api/core/RetryInterceptor.java index 1f61a2c..0c1e4ec 100644 --- a/src/main/java/com/intercom/api/core/RetryInterceptor.java +++ b/src/main/java/com/intercom/api/core/RetryInterceptor.java @@ -52,7 +52,7 @@ private Response retryChain(Response response, Chain chain) throws IOException { } private static boolean shouldRetry(int statusCode) { - return statusCode == 408 || statusCode == 409 || statusCode == 429 || statusCode >= 500; + return statusCode == 408 || statusCode == 429 || statusCode >= 500; } private final class ExponentialBackoff { diff --git a/src/main/java/com/intercom/api/errors/BadRequestError.java b/src/main/java/com/intercom/api/errors/BadRequestError.java index b20358b..ac6cca6 100644 --- a/src/main/java/com/intercom/api/errors/BadRequestError.java +++ b/src/main/java/com/intercom/api/errors/BadRequestError.java @@ -4,6 +4,7 @@ package com.intercom.api.errors; import com.intercom.api.core.IntercomApiException; +import okhttp3.Response; public final class BadRequestError extends IntercomApiException { /** @@ -16,6 +17,11 @@ public BadRequestError(Object body) { this.body = body; } + public BadRequestError(Object body, Response rawResponse) { + super("BadRequestError", 400, body, rawResponse); + this.body = body; + } + /** * @return the body */ diff --git a/src/main/java/com/intercom/api/errors/ForbiddenError.java b/src/main/java/com/intercom/api/errors/ForbiddenError.java index bddad94..42f8a5c 100644 --- a/src/main/java/com/intercom/api/errors/ForbiddenError.java +++ b/src/main/java/com/intercom/api/errors/ForbiddenError.java @@ -5,6 +5,7 @@ import com.intercom.api.core.IntercomApiException; import com.intercom.api.types.Error; +import okhttp3.Response; public final class ForbiddenError extends IntercomApiException { /** @@ -17,6 +18,11 @@ public ForbiddenError(Error body) { this.body = body; } + public ForbiddenError(Error body, Response rawResponse) { + super("ForbiddenError", 403, body, rawResponse); + this.body = body; + } + /** * @return the body */ diff --git a/src/main/java/com/intercom/api/errors/NotFoundError.java b/src/main/java/com/intercom/api/errors/NotFoundError.java index 730f46b..b2f1687 100644 --- a/src/main/java/com/intercom/api/errors/NotFoundError.java +++ b/src/main/java/com/intercom/api/errors/NotFoundError.java @@ -4,6 +4,7 @@ package com.intercom.api.errors; import com.intercom.api.core.IntercomApiException; +import okhttp3.Response; public final class NotFoundError extends IntercomApiException { /** @@ -16,6 +17,11 @@ public NotFoundError(Object body) { this.body = body; } + public NotFoundError(Object body, Response rawResponse) { + super("NotFoundError", 404, body, rawResponse); + this.body = body; + } + /** * @return the body */ diff --git a/src/main/java/com/intercom/api/errors/UnauthorizedError.java b/src/main/java/com/intercom/api/errors/UnauthorizedError.java index 5d07b74..d1f571b 100644 --- a/src/main/java/com/intercom/api/errors/UnauthorizedError.java +++ b/src/main/java/com/intercom/api/errors/UnauthorizedError.java @@ -5,6 +5,7 @@ import com.intercom.api.core.IntercomApiException; import com.intercom.api.types.Error; +import okhttp3.Response; public final class UnauthorizedError extends IntercomApiException { /** @@ -17,6 +18,11 @@ public UnauthorizedError(Error body) { this.body = body; } + public UnauthorizedError(Error body, Response rawResponse) { + super("UnauthorizedError", 401, body, rawResponse); + this.body = body; + } + /** * @return the body */ diff --git a/src/main/java/com/intercom/api/errors/UnprocessableEntityError.java b/src/main/java/com/intercom/api/errors/UnprocessableEntityError.java index 1125624..fb6e8f5 100644 --- a/src/main/java/com/intercom/api/errors/UnprocessableEntityError.java +++ b/src/main/java/com/intercom/api/errors/UnprocessableEntityError.java @@ -4,6 +4,7 @@ package com.intercom.api.errors; import com.intercom.api.core.IntercomApiException; +import okhttp3.Response; public final class UnprocessableEntityError extends IntercomApiException { /** @@ -16,6 +17,11 @@ public UnprocessableEntityError(Object body) { this.body = body; } + public UnprocessableEntityError(Object body, Response rawResponse) { + super("UnprocessableEntityError", 422, body, rawResponse); + this.body = body; + } + /** * @return the body */ diff --git a/src/main/java/com/intercom/api/resources/admins/AdminsClient.java b/src/main/java/com/intercom/api/resources/admins/AdminsClient.java index ca154a4..bc494a2 100644 --- a/src/main/java/com/intercom/api/resources/admins/AdminsClient.java +++ b/src/main/java/com/intercom/api/resources/admins/AdminsClient.java @@ -3,16 +3,8 @@ */ package com.intercom.api.resources.admins; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; -import com.intercom.api.core.QueryStringMapper; import com.intercom.api.core.RequestOptions; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.admins.requests.ConfigureAwayAdminRequest; import com.intercom.api.resources.admins.requests.FindAdminRequest; import com.intercom.api.resources.admins.requests.ListAllActivityLogsRequest; @@ -20,21 +12,22 @@ import com.intercom.api.types.ActivityLogList; import com.intercom.api.types.AdminList; import com.intercom.api.types.AdminWithApp; -import com.intercom.api.types.Error; -import java.io.IOException; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; public class AdminsClient { protected final ClientOptions clientOptions; + private final RawAdminsClient rawClient; + public AdminsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawAdminsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawAdminsClient withRawResponse() { + return this.rawClient; } /** @@ -45,7 +38,7 @@ public AdminsClient(ClientOptions clientOptions) { * */ public AdminWithApp identify() { - return identify(null); + return this.rawClient.identify().body(); } /** @@ -56,247 +49,62 @@ public AdminWithApp identify() { * */ public AdminWithApp identify(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("me") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), AdminWithApp.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.identify(requestOptions).body(); } /** * You can set an Admin as away for the Inbox. */ public Admin away(ConfigureAwayAdminRequest request) { - return away(request, null); + return this.rawClient.away(request).body(); } /** * You can set an Admin as away for the Inbox. */ public Admin away(ConfigureAwayAdminRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("admins") - .addPathSegment(request.getAdminId()) - .addPathSegments("away") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PUT", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Admin.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.away(request, requestOptions).body(); } /** * You can get a log of activities by all admins in an app. */ public ActivityLogList listAllActivityLogs(ListAllActivityLogsRequest request) { - return listAllActivityLogs(request, null); + return this.rawClient.listAllActivityLogs(request).body(); } /** * You can get a log of activities by all admins in an app. */ public ActivityLogList listAllActivityLogs(ListAllActivityLogsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("admins/activity_logs"); - QueryStringMapper.addQueryParameter(httpUrl, "created_at_after", request.getCreatedAtAfter(), false); - if (request.getCreatedAtBefore().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "created_at_before", request.getCreatedAtBefore().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ActivityLogList.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.listAllActivityLogs(request, requestOptions).body(); } /** * You can fetch a list of admins for a given workspace. */ public AdminList list() { - return list(null); + return this.rawClient.list().body(); } /** * You can fetch a list of admins for a given workspace. */ public AdminList list(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("admins") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), AdminList.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.list(requestOptions).body(); } /** * You can retrieve the details of a single admin. */ public Admin find(FindAdminRequest request) { - return find(request, null); + return this.rawClient.find(request).body(); } /** * You can retrieve the details of a single admin. */ public Admin find(FindAdminRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("admins") - .addPathSegment(request.getAdminId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Admin.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.find(request, requestOptions).body(); } } diff --git a/src/main/java/com/intercom/api/resources/admins/AsyncAdminsClient.java b/src/main/java/com/intercom/api/resources/admins/AsyncAdminsClient.java index 28a8409..6a00a05 100644 --- a/src/main/java/com/intercom/api/resources/admins/AsyncAdminsClient.java +++ b/src/main/java/com/intercom/api/resources/admins/AsyncAdminsClient.java @@ -3,16 +3,8 @@ */ package com.intercom.api.resources.admins; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; -import com.intercom.api.core.QueryStringMapper; import com.intercom.api.core.RequestOptions; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.admins.requests.ConfigureAwayAdminRequest; import com.intercom.api.resources.admins.requests.FindAdminRequest; import com.intercom.api.resources.admins.requests.ListAllActivityLogsRequest; @@ -20,25 +12,23 @@ import com.intercom.api.types.ActivityLogList; import com.intercom.api.types.AdminList; import com.intercom.api.types.AdminWithApp; -import com.intercom.api.types.Error; -import java.io.IOException; import java.util.concurrent.CompletableFuture; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; public class AsyncAdminsClient { protected final ClientOptions clientOptions; + private final AsyncRawAdminsClient rawClient; + public AsyncAdminsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new AsyncRawAdminsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawAdminsClient withRawResponse() { + return this.rawClient; } /** @@ -49,7 +39,7 @@ public AsyncAdminsClient(ClientOptions clientOptions) { * */ public CompletableFuture identify() { - return identify(null); + return this.rawClient.identify().thenApply(response -> response.body()); } /** @@ -60,131 +50,28 @@ public CompletableFuture identify() { * */ public CompletableFuture identify(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("me") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), AdminWithApp.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.identify(requestOptions).thenApply(response -> response.body()); } /** * You can set an Admin as away for the Inbox. */ public CompletableFuture away(ConfigureAwayAdminRequest request) { - return away(request, null); + return this.rawClient.away(request).thenApply(response -> response.body()); } /** * You can set an Admin as away for the Inbox. */ public CompletableFuture away(ConfigureAwayAdminRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("admins") - .addPathSegment(request.getAdminId()) - .addPathSegments("away") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PUT", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Admin.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.away(request, requestOptions).thenApply(response -> response.body()); } /** * You can get a log of activities by all admins in an app. */ public CompletableFuture listAllActivityLogs(ListAllActivityLogsRequest request) { - return listAllActivityLogs(request, null); + return this.rawClient.listAllActivityLogs(request).thenApply(response -> response.body()); } /** @@ -192,192 +79,34 @@ public CompletableFuture listAllActivityLogs(ListAllActivityLog */ public CompletableFuture listAllActivityLogs( ListAllActivityLogsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("admins/activity_logs"); - QueryStringMapper.addQueryParameter(httpUrl, "created_at_after", request.getCreatedAtAfter(), false); - if (request.getCreatedAtBefore().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "created_at_before", request.getCreatedAtBefore().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ActivityLogList.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.listAllActivityLogs(request, requestOptions).thenApply(response -> response.body()); } /** * You can fetch a list of admins for a given workspace. */ public CompletableFuture list() { - return list(null); + return this.rawClient.list().thenApply(response -> response.body()); } /** * You can fetch a list of admins for a given workspace. */ public CompletableFuture list(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("admins") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), AdminList.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.list(requestOptions).thenApply(response -> response.body()); } /** * You can retrieve the details of a single admin. */ public CompletableFuture find(FindAdminRequest request) { - return find(request, null); + return this.rawClient.find(request).thenApply(response -> response.body()); } /** * You can retrieve the details of a single admin. */ public CompletableFuture find(FindAdminRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("admins") - .addPathSegment(request.getAdminId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Admin.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.find(request, requestOptions).thenApply(response -> response.body()); } } diff --git a/src/main/java/com/intercom/api/resources/admins/AsyncRawAdminsClient.java b/src/main/java/com/intercom/api/resources/admins/AsyncRawAdminsClient.java new file mode 100644 index 0000000..91b3115 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/admins/AsyncRawAdminsClient.java @@ -0,0 +1,402 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.admins; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.QueryStringMapper; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.admins.requests.ConfigureAwayAdminRequest; +import com.intercom.api.resources.admins.requests.FindAdminRequest; +import com.intercom.api.resources.admins.requests.ListAllActivityLogsRequest; +import com.intercom.api.resources.admins.types.Admin; +import com.intercom.api.types.ActivityLogList; +import com.intercom.api.types.AdminList; +import com.intercom.api.types.AdminWithApp; +import com.intercom.api.types.Error; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawAdminsClient { + protected final ClientOptions clientOptions; + + public AsyncRawAdminsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can view the currently authorised admin along with the embedded app object (a "workspace" in legacy terminology). + *
+ *

🚧 Single Sign On

+ *

If you are building a custom "Log in with Intercom" flow for your site, and you call the /me endpoint to identify the logged-in user, you should not accept any sign-ins from users with unverified email addresses as it poses a potential impersonation security risk.

+ *
+ */ + public CompletableFuture> identify() { + return identify(null); + } + + /** + * You can view the currently authorised admin along with the embedded app object (a "workspace" in legacy terminology). + *
+ *

🚧 Single Sign On

+ *

If you are building a custom "Log in with Intercom" flow for your site, and you call the /me endpoint to identify the logged-in user, you should not accept any sign-ins from users with unverified email addresses as it poses a potential impersonation security risk.

+ *
+ */ + public CompletableFuture> identify(RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("me") + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), AdminWithApp.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can set an Admin as away for the Inbox. + */ + public CompletableFuture> away(ConfigureAwayAdminRequest request) { + return away(request, null); + } + + /** + * You can set an Admin as away for the Inbox. + */ + public CompletableFuture> away( + ConfigureAwayAdminRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("admins") + .addPathSegment(request.getAdminId()) + .addPathSegments("away") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Admin.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can get a log of activities by all admins in an app. + */ + public CompletableFuture> listAllActivityLogs( + ListAllActivityLogsRequest request) { + return listAllActivityLogs(request, null); + } + + /** + * You can get a log of activities by all admins in an app. + */ + public CompletableFuture> listAllActivityLogs( + ListAllActivityLogsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("admins/activity_logs"); + QueryStringMapper.addQueryParameter(httpUrl, "created_at_after", request.getCreatedAtAfter(), false); + if (request.getCreatedAtBefore().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "created_at_before", request.getCreatedAtBefore().get(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ActivityLogList.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can fetch a list of admins for a given workspace. + */ + public CompletableFuture> list() { + return list(null); + } + + /** + * You can fetch a list of admins for a given workspace. + */ + public CompletableFuture> list(RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("admins") + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), AdminList.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can retrieve the details of a single admin. + */ + public CompletableFuture> find(FindAdminRequest request) { + return find(request, null); + } + + /** + * You can retrieve the details of a single admin. + */ + public CompletableFuture> find( + FindAdminRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("admins") + .addPathSegment(request.getAdminId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Admin.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/intercom/api/resources/admins/RawAdminsClient.java b/src/main/java/com/intercom/api/resources/admins/RawAdminsClient.java new file mode 100644 index 0000000..e34c4c2 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/admins/RawAdminsClient.java @@ -0,0 +1,318 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.admins; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.QueryStringMapper; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.admins.requests.ConfigureAwayAdminRequest; +import com.intercom.api.resources.admins.requests.FindAdminRequest; +import com.intercom.api.resources.admins.requests.ListAllActivityLogsRequest; +import com.intercom.api.resources.admins.types.Admin; +import com.intercom.api.types.ActivityLogList; +import com.intercom.api.types.AdminList; +import com.intercom.api.types.AdminWithApp; +import com.intercom.api.types.Error; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawAdminsClient { + protected final ClientOptions clientOptions; + + public RawAdminsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can view the currently authorised admin along with the embedded app object (a "workspace" in legacy terminology). + *
+ *

🚧 Single Sign On

+ *

If you are building a custom "Log in with Intercom" flow for your site, and you call the /me endpoint to identify the logged-in user, you should not accept any sign-ins from users with unverified email addresses as it poses a potential impersonation security risk.

+ *
+ */ + public IntercomHttpResponse identify() { + return identify(null); + } + + /** + * You can view the currently authorised admin along with the embedded app object (a "workspace" in legacy terminology). + *
+ *

🚧 Single Sign On

+ *

If you are building a custom "Log in with Intercom" flow for your site, and you call the /me endpoint to identify the logged-in user, you should not accept any sign-ins from users with unverified email addresses as it poses a potential impersonation security risk.

+ *
+ */ + public IntercomHttpResponse identify(RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("me") + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), AdminWithApp.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can set an Admin as away for the Inbox. + */ + public IntercomHttpResponse away(ConfigureAwayAdminRequest request) { + return away(request, null); + } + + /** + * You can set an Admin as away for the Inbox. + */ + public IntercomHttpResponse away(ConfigureAwayAdminRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("admins") + .addPathSegment(request.getAdminId()) + .addPathSegments("away") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Admin.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can get a log of activities by all admins in an app. + */ + public IntercomHttpResponse listAllActivityLogs(ListAllActivityLogsRequest request) { + return listAllActivityLogs(request, null); + } + + /** + * You can get a log of activities by all admins in an app. + */ + public IntercomHttpResponse listAllActivityLogs( + ListAllActivityLogsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("admins/activity_logs"); + QueryStringMapper.addQueryParameter(httpUrl, "created_at_after", request.getCreatedAtAfter(), false); + if (request.getCreatedAtBefore().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "created_at_before", request.getCreatedAtBefore().get(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ActivityLogList.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can fetch a list of admins for a given workspace. + */ + public IntercomHttpResponse list() { + return list(null); + } + + /** + * You can fetch a list of admins for a given workspace. + */ + public IntercomHttpResponse list(RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("admins") + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), AdminList.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can retrieve the details of a single admin. + */ + public IntercomHttpResponse find(FindAdminRequest request) { + return find(request, null); + } + + /** + * You can retrieve the details of a single admin. + */ + public IntercomHttpResponse find(FindAdminRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("admins") + .addPathSegment(request.getAdminId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Admin.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/intercom/api/resources/articles/ArticlesClient.java b/src/main/java/com/intercom/api/resources/articles/ArticlesClient.java index 8c35cba..e7d0664 100644 --- a/src/main/java/com/intercom/api/resources/articles/ArticlesClient.java +++ b/src/main/java/com/intercom/api/resources/articles/ArticlesClient.java @@ -3,18 +3,9 @@ */ package com.intercom.api.resources.articles; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; -import com.intercom.api.core.QueryStringMapper; import com.intercom.api.core.RequestOptions; import com.intercom.api.core.pagination.SyncPagingIterable; -import com.intercom.api.errors.BadRequestError; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.articles.requests.CreateArticleRequest; import com.intercom.api.resources.articles.requests.DeleteArticleRequest; import com.intercom.api.resources.articles.requests.FindArticleRequest; @@ -24,24 +15,23 @@ import com.intercom.api.resources.articles.types.Article; import com.intercom.api.resources.articles.types.ArticleListItem; import com.intercom.api.resources.articles.types.SearchArticlesResponse; -import com.intercom.api.types.ArticleList; import com.intercom.api.types.DeletedArticleObject; -import com.intercom.api.types.Error; -import java.io.IOException; -import java.util.List; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; public class ArticlesClient { protected final ClientOptions clientOptions; + private final RawArticlesClient rawClient; + public ArticlesClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawArticlesClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawArticlesClient withRawResponse() { + return this.rawClient; } /** @@ -52,7 +42,7 @@ public ArticlesClient(ClientOptions clientOptions) { * */ public SyncPagingIterable list() { - return list(ListArticlesRequest.builder().build()); + return this.rawClient.list().body(); } /** @@ -63,7 +53,7 @@ public SyncPagingIterable list() { * */ public SyncPagingIterable list(ListArticlesRequest request) { - return list(request, null); + return this.rawClient.list(request).body(); } /** @@ -74,351 +64,83 @@ public SyncPagingIterable list(ListArticlesRequest request) { * */ public SyncPagingIterable list(ListArticlesRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("articles"); - if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getPerPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "per_page", request.getPerPage().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - ArticleList parsedResponse = - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ArticleList.class); - int newPageNumber = request.getPage().map(page -> page + 1).orElse(1); - ListArticlesRequest nextRequest = ListArticlesRequest.builder() - .from(request) - .page(newPageNumber) - .build(); - List result = parsedResponse.getData(); - return new SyncPagingIterable(true, result, () -> list(nextRequest, requestOptions)); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.list(request, requestOptions).body(); } /** * You can create a new article by making a POST request to https://api.intercom.io/articles. */ public Article create(CreateArticleRequest request) { - return create(request, null); + return this.rawClient.create(request).body(); } /** * You can create a new article by making a POST request to https://api.intercom.io/articles. */ public Article create(CreateArticleRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("articles") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Article.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.create(request, requestOptions).body(); } /** * You can fetch the details of a single article by making a GET request to https://api.intercom.io/articles/<id>. */ public Article find(FindArticleRequest request) { - return find(request, null); + return this.rawClient.find(request).body(); } /** * You can fetch the details of a single article by making a GET request to https://api.intercom.io/articles/<id>. */ public Article find(FindArticleRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("articles") - .addPathSegment(request.getArticleId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Article.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.find(request, requestOptions).body(); } /** * You can update the details of a single article by making a PUT request to https://api.intercom.io/articles/<id>. */ public Article update(UpdateArticleRequest request) { - return update(request, null); + return this.rawClient.update(request).body(); } /** * You can update the details of a single article by making a PUT request to https://api.intercom.io/articles/<id>. */ public Article update(UpdateArticleRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("articles") - .addPathSegment(request.getArticleId()) - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PUT", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Article.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.update(request, requestOptions).body(); } /** * You can delete a single article by making a DELETE request to https://api.intercom.io/articles/<id>. */ public DeletedArticleObject delete(DeleteArticleRequest request) { - return delete(request, null); + return this.rawClient.delete(request).body(); } /** * You can delete a single article by making a DELETE request to https://api.intercom.io/articles/<id>. */ public DeletedArticleObject delete(DeleteArticleRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("articles") - .addPathSegment(request.getArticleId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeletedArticleObject.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.delete(request, requestOptions).body(); } /** * You can search for articles by making a GET request to https://api.intercom.io/articles/search. */ public SearchArticlesResponse search() { - return search(SearchArticlesRequest.builder().build()); + return this.rawClient.search().body(); } /** * You can search for articles by making a GET request to https://api.intercom.io/articles/search. */ public SearchArticlesResponse search(SearchArticlesRequest request) { - return search(request, null); + return this.rawClient.search(request).body(); } /** * You can search for articles by making a GET request to https://api.intercom.io/articles/search. */ public SearchArticlesResponse search(SearchArticlesRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("articles/search"); - if (request.getPhrase().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "phrase", request.getPhrase().get(), false); - } - if (request.getState().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "state", request.getState().get(), false); - } - if (request.getHelpCenterId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "help_center_id", request.getHelpCenterId().get().toString(), false); - } - if (request.getHighlight().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "highlight", request.getHighlight().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SearchArticlesResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.search(request, requestOptions).body(); } } diff --git a/src/main/java/com/intercom/api/resources/articles/AsyncArticlesClient.java b/src/main/java/com/intercom/api/resources/articles/AsyncArticlesClient.java index 8e523dd..b0c29c4 100644 --- a/src/main/java/com/intercom/api/resources/articles/AsyncArticlesClient.java +++ b/src/main/java/com/intercom/api/resources/articles/AsyncArticlesClient.java @@ -3,18 +3,9 @@ */ package com.intercom.api.resources.articles; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; -import com.intercom.api.core.QueryStringMapper; import com.intercom.api.core.RequestOptions; import com.intercom.api.core.pagination.SyncPagingIterable; -import com.intercom.api.errors.BadRequestError; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.articles.requests.CreateArticleRequest; import com.intercom.api.resources.articles.requests.DeleteArticleRequest; import com.intercom.api.resources.articles.requests.FindArticleRequest; @@ -24,29 +15,24 @@ import com.intercom.api.resources.articles.types.Article; import com.intercom.api.resources.articles.types.ArticleListItem; import com.intercom.api.resources.articles.types.SearchArticlesResponse; -import com.intercom.api.types.ArticleList; import com.intercom.api.types.DeletedArticleObject; -import com.intercom.api.types.Error; -import java.io.IOException; -import java.util.List; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; public class AsyncArticlesClient { protected final ClientOptions clientOptions; + private final AsyncRawArticlesClient rawClient; + public AsyncArticlesClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new AsyncRawArticlesClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawArticlesClient withRawResponse() { + return this.rawClient; } /** @@ -57,7 +43,7 @@ public AsyncArticlesClient(ClientOptions clientOptions) { * */ public CompletableFuture> list() { - return list(ListArticlesRequest.builder().build()); + return this.rawClient.list().thenApply(response -> response.body()); } /** @@ -68,7 +54,7 @@ public CompletableFuture> list() { * */ public CompletableFuture> list(ListArticlesRequest request) { - return list(request, null); + return this.rawClient.list(request).thenApply(response -> response.body()); } /** @@ -80,382 +66,77 @@ public CompletableFuture> list(ListArticlesR */ public CompletableFuture> list( ListArticlesRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("articles"); - if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getPerPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "per_page", request.getPerPage().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - ArticleList parsedResponse = - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ArticleList.class); - int newPageNumber = - request.getPage().map(page -> page + 1).orElse(1); - ListArticlesRequest nextRequest = ListArticlesRequest.builder() - .from(request) - .page(newPageNumber) - .build(); - List result = parsedResponse.getData(); - future.complete(new SyncPagingIterable(true, result, () -> { - try { - return list(nextRequest, requestOptions).get(); - } catch (InterruptedException | ExecutionException e) { - throw new RuntimeException(e); - } - })); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.list(request, requestOptions).thenApply(response -> response.body()); } /** * You can create a new article by making a POST request to https://api.intercom.io/articles. */ public CompletableFuture
create(CreateArticleRequest request) { - return create(request, null); + return this.rawClient.create(request).thenApply(response -> response.body()); } /** * You can create a new article by making a POST request to https://api.intercom.io/articles. */ public CompletableFuture
create(CreateArticleRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("articles") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture
future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Article.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.create(request, requestOptions).thenApply(response -> response.body()); } /** * You can fetch the details of a single article by making a GET request to https://api.intercom.io/articles/<id>. */ public CompletableFuture
find(FindArticleRequest request) { - return find(request, null); + return this.rawClient.find(request).thenApply(response -> response.body()); } /** * You can fetch the details of a single article by making a GET request to https://api.intercom.io/articles/<id>. */ public CompletableFuture
find(FindArticleRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("articles") - .addPathSegment(request.getArticleId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture
future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Article.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.find(request, requestOptions).thenApply(response -> response.body()); } /** * You can update the details of a single article by making a PUT request to https://api.intercom.io/articles/<id>. */ public CompletableFuture
update(UpdateArticleRequest request) { - return update(request, null); + return this.rawClient.update(request).thenApply(response -> response.body()); } /** * You can update the details of a single article by making a PUT request to https://api.intercom.io/articles/<id>. */ public CompletableFuture
update(UpdateArticleRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("articles") - .addPathSegment(request.getArticleId()) - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PUT", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture
future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Article.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.update(request, requestOptions).thenApply(response -> response.body()); } /** * You can delete a single article by making a DELETE request to https://api.intercom.io/articles/<id>. */ public CompletableFuture delete(DeleteArticleRequest request) { - return delete(request, null); + return this.rawClient.delete(request).thenApply(response -> response.body()); } /** * You can delete a single article by making a DELETE request to https://api.intercom.io/articles/<id>. */ public CompletableFuture delete(DeleteArticleRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("articles") - .addPathSegment(request.getArticleId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeletedArticleObject.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.delete(request, requestOptions).thenApply(response -> response.body()); } /** * You can search for articles by making a GET request to https://api.intercom.io/articles/search. */ public CompletableFuture search() { - return search(SearchArticlesRequest.builder().build()); + return this.rawClient.search().thenApply(response -> response.body()); } /** * You can search for articles by making a GET request to https://api.intercom.io/articles/search. */ public CompletableFuture search(SearchArticlesRequest request) { - return search(request, null); + return this.rawClient.search(request).thenApply(response -> response.body()); } /** @@ -463,71 +144,6 @@ public CompletableFuture search(SearchArticlesRequest re */ public CompletableFuture search( SearchArticlesRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("articles/search"); - if (request.getPhrase().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "phrase", request.getPhrase().get(), false); - } - if (request.getState().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "state", request.getState().get(), false); - } - if (request.getHelpCenterId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "help_center_id", request.getHelpCenterId().get().toString(), false); - } - if (request.getHighlight().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "highlight", request.getHighlight().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), SearchArticlesResponse.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.search(request, requestOptions).thenApply(response -> response.body()); } } diff --git a/src/main/java/com/intercom/api/resources/articles/AsyncRawArticlesClient.java b/src/main/java/com/intercom/api/resources/articles/AsyncRawArticlesClient.java new file mode 100644 index 0000000..f7b5511 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/articles/AsyncRawArticlesClient.java @@ -0,0 +1,563 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.articles; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.QueryStringMapper; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.core.pagination.SyncPagingIterable; +import com.intercom.api.errors.BadRequestError; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.articles.requests.CreateArticleRequest; +import com.intercom.api.resources.articles.requests.DeleteArticleRequest; +import com.intercom.api.resources.articles.requests.FindArticleRequest; +import com.intercom.api.resources.articles.requests.ListArticlesRequest; +import com.intercom.api.resources.articles.requests.SearchArticlesRequest; +import com.intercom.api.resources.articles.requests.UpdateArticleRequest; +import com.intercom.api.resources.articles.types.Article; +import com.intercom.api.resources.articles.types.ArticleListItem; +import com.intercom.api.resources.articles.types.SearchArticlesResponse; +import com.intercom.api.types.ArticleList; +import com.intercom.api.types.DeletedArticleObject; +import com.intercom.api.types.Error; +import java.io.IOException; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawArticlesClient { + protected final ClientOptions clientOptions; + + public AsyncRawArticlesClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can fetch a list of all articles by making a GET request to https://api.intercom.io/articles. + *
+ *

📘 How are the articles sorted and ordered?

+ *

Articles will be returned in descending order on the updated_at attribute. This means if you need to iterate through results then we'll show the most recently updated articles first.

+ *
+ */ + public CompletableFuture>> list() { + return list(ListArticlesRequest.builder().build()); + } + + /** + * You can fetch a list of all articles by making a GET request to https://api.intercom.io/articles. + *
+ *

📘 How are the articles sorted and ordered?

+ *

Articles will be returned in descending order on the updated_at attribute. This means if you need to iterate through results then we'll show the most recently updated articles first.

+ *
+ */ + public CompletableFuture>> list( + ListArticlesRequest request) { + return list(request, null); + } + + /** + * You can fetch a list of all articles by making a GET request to https://api.intercom.io/articles. + *
+ *

📘 How are the articles sorted and ordered?

+ *

Articles will be returned in descending order on the updated_at attribute. This means if you need to iterate through results then we'll show the most recently updated articles first.

+ *
+ */ + public CompletableFuture>> list( + ListArticlesRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("articles"); + if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "page", request.getPage().get().toString(), false); + } + if (request.getPerPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "per_page", request.getPerPage().get().toString(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture>> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + ArticleList parsedResponse = + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ArticleList.class); + int newPageNumber = + request.getPage().map(page -> page + 1).orElse(1); + ListArticlesRequest nextRequest = ListArticlesRequest.builder() + .from(request) + .page(newPageNumber) + .build(); + List result = parsedResponse.getData(); + future.complete(new IntercomHttpResponse<>( + new SyncPagingIterable(true, result, () -> { + try { + return list(nextRequest, requestOptions) + .get() + .body(); + } catch (InterruptedException | ExecutionException e) { + throw new RuntimeException(e); + } + }), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can create a new article by making a POST request to https://api.intercom.io/articles. + */ + public CompletableFuture> create(CreateArticleRequest request) { + return create(request, null); + } + + /** + * You can create a new article by making a POST request to https://api.intercom.io/articles. + */ + public CompletableFuture> create( + CreateArticleRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("articles") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Article.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can fetch the details of a single article by making a GET request to https://api.intercom.io/articles/<id>. + */ + public CompletableFuture> find(FindArticleRequest request) { + return find(request, null); + } + + /** + * You can fetch the details of a single article by making a GET request to https://api.intercom.io/articles/<id>. + */ + public CompletableFuture> find( + FindArticleRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("articles") + .addPathSegment(request.getArticleId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Article.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can update the details of a single article by making a PUT request to https://api.intercom.io/articles/<id>. + */ + public CompletableFuture> update(UpdateArticleRequest request) { + return update(request, null); + } + + /** + * You can update the details of a single article by making a PUT request to https://api.intercom.io/articles/<id>. + */ + public CompletableFuture> update( + UpdateArticleRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("articles") + .addPathSegment(request.getArticleId()) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Article.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can delete a single article by making a DELETE request to https://api.intercom.io/articles/<id>. + */ + public CompletableFuture> delete(DeleteArticleRequest request) { + return delete(request, null); + } + + /** + * You can delete a single article by making a DELETE request to https://api.intercom.io/articles/<id>. + */ + public CompletableFuture> delete( + DeleteArticleRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("articles") + .addPathSegment(request.getArticleId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeletedArticleObject.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can search for articles by making a GET request to https://api.intercom.io/articles/search. + */ + public CompletableFuture> search() { + return search(SearchArticlesRequest.builder().build()); + } + + /** + * You can search for articles by making a GET request to https://api.intercom.io/articles/search. + */ + public CompletableFuture> search(SearchArticlesRequest request) { + return search(request, null); + } + + /** + * You can search for articles by making a GET request to https://api.intercom.io/articles/search. + */ + public CompletableFuture> search( + SearchArticlesRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("articles/search"); + if (request.getPhrase().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "phrase", request.getPhrase().get(), false); + } + if (request.getState().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "state", request.getState().get(), false); + } + if (request.getHelpCenterId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "help_center_id", request.getHelpCenterId().get().toString(), false); + } + if (request.getHighlight().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "highlight", request.getHighlight().get().toString(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), SearchArticlesResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/intercom/api/resources/articles/RawArticlesClient.java b/src/main/java/com/intercom/api/resources/articles/RawArticlesClient.java new file mode 100644 index 0000000..85302d6 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/articles/RawArticlesClient.java @@ -0,0 +1,449 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.articles; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.QueryStringMapper; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.core.pagination.SyncPagingIterable; +import com.intercom.api.errors.BadRequestError; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.articles.requests.CreateArticleRequest; +import com.intercom.api.resources.articles.requests.DeleteArticleRequest; +import com.intercom.api.resources.articles.requests.FindArticleRequest; +import com.intercom.api.resources.articles.requests.ListArticlesRequest; +import com.intercom.api.resources.articles.requests.SearchArticlesRequest; +import com.intercom.api.resources.articles.requests.UpdateArticleRequest; +import com.intercom.api.resources.articles.types.Article; +import com.intercom.api.resources.articles.types.ArticleListItem; +import com.intercom.api.resources.articles.types.SearchArticlesResponse; +import com.intercom.api.types.ArticleList; +import com.intercom.api.types.DeletedArticleObject; +import com.intercom.api.types.Error; +import java.io.IOException; +import java.util.List; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawArticlesClient { + protected final ClientOptions clientOptions; + + public RawArticlesClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can fetch a list of all articles by making a GET request to https://api.intercom.io/articles. + *
+ *

📘 How are the articles sorted and ordered?

+ *

Articles will be returned in descending order on the updated_at attribute. This means if you need to iterate through results then we'll show the most recently updated articles first.

+ *
+ */ + public IntercomHttpResponse> list() { + return list(ListArticlesRequest.builder().build()); + } + + /** + * You can fetch a list of all articles by making a GET request to https://api.intercom.io/articles. + *
+ *

📘 How are the articles sorted and ordered?

+ *

Articles will be returned in descending order on the updated_at attribute. This means if you need to iterate through results then we'll show the most recently updated articles first.

+ *
+ */ + public IntercomHttpResponse> list(ListArticlesRequest request) { + return list(request, null); + } + + /** + * You can fetch a list of all articles by making a GET request to https://api.intercom.io/articles. + *
+ *

📘 How are the articles sorted and ordered?

+ *

Articles will be returned in descending order on the updated_at attribute. This means if you need to iterate through results then we'll show the most recently updated articles first.

+ *
+ */ + public IntercomHttpResponse> list( + ListArticlesRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("articles"); + if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "page", request.getPage().get().toString(), false); + } + if (request.getPerPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "per_page", request.getPerPage().get().toString(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + ArticleList parsedResponse = + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ArticleList.class); + int newPageNumber = request.getPage().map(page -> page + 1).orElse(1); + ListArticlesRequest nextRequest = ListArticlesRequest.builder() + .from(request) + .page(newPageNumber) + .build(); + List result = parsedResponse.getData(); + return new IntercomHttpResponse<>( + new SyncPagingIterable(true, result, () -> list(nextRequest, requestOptions) + .body()), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can create a new article by making a POST request to https://api.intercom.io/articles. + */ + public IntercomHttpResponse
create(CreateArticleRequest request) { + return create(request, null); + } + + /** + * You can create a new article by making a POST request to https://api.intercom.io/articles. + */ + public IntercomHttpResponse
create(CreateArticleRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("articles") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Article.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can fetch the details of a single article by making a GET request to https://api.intercom.io/articles/<id>. + */ + public IntercomHttpResponse
find(FindArticleRequest request) { + return find(request, null); + } + + /** + * You can fetch the details of a single article by making a GET request to https://api.intercom.io/articles/<id>. + */ + public IntercomHttpResponse
find(FindArticleRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("articles") + .addPathSegment(request.getArticleId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Article.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can update the details of a single article by making a PUT request to https://api.intercom.io/articles/<id>. + */ + public IntercomHttpResponse
update(UpdateArticleRequest request) { + return update(request, null); + } + + /** + * You can update the details of a single article by making a PUT request to https://api.intercom.io/articles/<id>. + */ + public IntercomHttpResponse
update(UpdateArticleRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("articles") + .addPathSegment(request.getArticleId()) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Article.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can delete a single article by making a DELETE request to https://api.intercom.io/articles/<id>. + */ + public IntercomHttpResponse delete(DeleteArticleRequest request) { + return delete(request, null); + } + + /** + * You can delete a single article by making a DELETE request to https://api.intercom.io/articles/<id>. + */ + public IntercomHttpResponse delete( + DeleteArticleRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("articles") + .addPathSegment(request.getArticleId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeletedArticleObject.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can search for articles by making a GET request to https://api.intercom.io/articles/search. + */ + public IntercomHttpResponse search() { + return search(SearchArticlesRequest.builder().build()); + } + + /** + * You can search for articles by making a GET request to https://api.intercom.io/articles/search. + */ + public IntercomHttpResponse search(SearchArticlesRequest request) { + return search(request, null); + } + + /** + * You can search for articles by making a GET request to https://api.intercom.io/articles/search. + */ + public IntercomHttpResponse search( + SearchArticlesRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("articles/search"); + if (request.getPhrase().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "phrase", request.getPhrase().get(), false); + } + if (request.getState().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "state", request.getState().get(), false); + } + if (request.getHelpCenterId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "help_center_id", request.getHelpCenterId().get().toString(), false); + } + if (request.getHighlight().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "highlight", request.getHighlight().get().toString(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SearchArticlesResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/intercom/api/resources/companies/AsyncCompaniesClient.java b/src/main/java/com/intercom/api/resources/companies/AsyncCompaniesClient.java index 0168958..289e047 100644 --- a/src/main/java/com/intercom/api/resources/companies/AsyncCompaniesClient.java +++ b/src/main/java/com/intercom/api/resources/companies/AsyncCompaniesClient.java @@ -3,18 +3,9 @@ */ package com.intercom.api.resources.companies; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; -import com.intercom.api.core.QueryStringMapper; import com.intercom.api.core.RequestOptions; import com.intercom.api.core.pagination.SyncPagingIterable; -import com.intercom.api.errors.BadRequestError; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.companies.requests.AttachContactToCompanyRequest; import com.intercom.api.resources.companies.requests.CreateOrUpdateCompanyRequest; import com.intercom.api.resources.companies.requests.DeleteCompanyRequest; @@ -30,30 +21,24 @@ import com.intercom.api.types.CompanyAttachedContacts; import com.intercom.api.types.CompanyAttachedSegments; import com.intercom.api.types.CompanyList; -import com.intercom.api.types.CompanyScroll; import com.intercom.api.types.DeletedCompanyObject; -import com.intercom.api.types.Error; -import java.io.IOException; -import java.util.List; -import java.util.Optional; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; public class AsyncCompaniesClient { protected final ClientOptions clientOptions; + private final AsyncRawCompaniesClient rawClient; + public AsyncCompaniesClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new AsyncRawCompaniesClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawCompaniesClient withRawResponse() { + return this.rawClient; } /** @@ -65,7 +50,7 @@ public AsyncCompaniesClient(ClientOptions clientOptions) { *

https://api.intercom.io/companies?segment_id={segment_id}

*/ public CompletableFuture retrieve() { - return retrieve(RetrieveCompanyRequest.builder().build()); + return this.rawClient.retrieve().thenApply(response -> response.body()); } /** @@ -77,7 +62,7 @@ public CompletableFuture retrieve() { *

https://api.intercom.io/companies?segment_id={segment_id}

*/ public CompletableFuture retrieve(RetrieveCompanyRequest request) { - return retrieve(request, null); + return this.rawClient.retrieve(request).thenApply(response -> response.body()); } /** @@ -89,84 +74,7 @@ public CompletableFuture retrieve(RetrieveCompanyRequest request) { *

https://api.intercom.io/companies?segment_id={segment_id}

*/ public CompletableFuture retrieve(RetrieveCompanyRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("companies"); - if (request.getName().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "name", request.getName().get(), false); - } - if (request.getCompanyId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "company_id", request.getCompanyId().get(), false); - } - if (request.getTagId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "tag_id", request.getTagId().get(), false); - } - if (request.getSegmentId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "segment_id", request.getSegmentId().get(), false); - } - if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getPerPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "per_page", request.getPerPage().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CompanyList.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.retrieve(request, requestOptions).thenApply(response -> response.body()); } /** @@ -178,7 +86,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { * {% /admonition %}

*/ public CompletableFuture createOrUpdate() { - return createOrUpdate(CreateOrUpdateCompanyRequest.builder().build()); + return this.rawClient.createOrUpdate().thenApply(response -> response.body()); } /** @@ -190,7 +98,7 @@ public CompletableFuture createOrUpdate() { * {% /admonition %}

*/ public CompletableFuture createOrUpdate(CreateOrUpdateCompanyRequest request) { - return createOrUpdate(request, null); + return this.rawClient.createOrUpdate(request).thenApply(response -> response.body()); } /** @@ -203,137 +111,21 @@ public CompletableFuture createOrUpdate(CreateOrUpdateCompanyRequest re */ public CompletableFuture createOrUpdate( CreateOrUpdateCompanyRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("companies") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Company.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.createOrUpdate(request, requestOptions).thenApply(response -> response.body()); } /** * You can fetch a single company. */ public CompletableFuture find(FindCompanyRequest request) { - return find(request, null); + return this.rawClient.find(request).thenApply(response -> response.body()); } /** * You can fetch a single company. */ public CompletableFuture find(FindCompanyRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("companies") - .addPathSegment(request.getCompanyId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Company.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.find(request, requestOptions).thenApply(response -> response.body()); } /** @@ -343,7 +135,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { * {% /admonition %}

*/ public CompletableFuture update(UpdateCompanyRequest request) { - return update(request, null); + return this.rawClient.update(request).thenApply(response -> response.body()); } /** @@ -353,139 +145,28 @@ public CompletableFuture update(UpdateCompanyRequest request) { * {% /admonition %}

*/ public CompletableFuture update(UpdateCompanyRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("companies") - .addPathSegment(request.getCompanyId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("PUT", RequestBody.create("", null)) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Company.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.update(request, requestOptions).thenApply(response -> response.body()); } /** * You can delete a single company. */ public CompletableFuture delete(DeleteCompanyRequest request) { - return delete(request, null); + return this.rawClient.delete(request).thenApply(response -> response.body()); } /** * You can delete a single company. */ public CompletableFuture delete(DeleteCompanyRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("companies") - .addPathSegment(request.getCompanyId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeletedCompanyObject.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.delete(request, requestOptions).thenApply(response -> response.body()); } /** * You can fetch a list of all contacts that belong to a company. */ public CompletableFuture listAttachedContacts(ListAttachedContactsRequest request) { - return listAttachedContacts(request, null); + return this.rawClient.listAttachedContacts(request).thenApply(response -> response.body()); } /** @@ -493,71 +174,7 @@ public CompletableFuture listAttachedContacts(ListAttac */ public CompletableFuture listAttachedContacts( ListAttachedContactsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("companies") - .addPathSegment(request.getCompanyId()) - .addPathSegments("contacts"); - if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getPerPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "per_page", request.getPerPage().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), CompanyAttachedContacts.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.listAttachedContacts(request, requestOptions).thenApply(response -> response.body()); } /** @@ -565,7 +182,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { */ public CompletableFuture listAttachedSegments( ListSegmentsAttachedToCompanyRequest request) { - return listAttachedSegments(request, null); + return this.rawClient.listAttachedSegments(request).thenApply(response -> response.body()); } /** @@ -573,64 +190,7 @@ public CompletableFuture listAttachedSegments( */ public CompletableFuture listAttachedSegments( ListSegmentsAttachedToCompanyRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("companies") - .addPathSegment(request.getCompanyId()) - .addPathSegments("segments") - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), CompanyAttachedSegments.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.listAttachedSegments(request, requestOptions).thenApply(response -> response.body()); } /** @@ -643,7 +203,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { * {% /admonition %}

*/ public CompletableFuture> list() { - return list(ListCompaniesRequest.builder().build()); + return this.rawClient.list().thenApply(response -> response.body()); } /** @@ -656,7 +216,7 @@ public CompletableFuture> list() { * {% /admonition %}

*/ public CompletableFuture> list(ListCompaniesRequest request) { - return list(request, null); + return this.rawClient.list(request).thenApply(response -> response.body()); } /** @@ -670,82 +230,7 @@ public CompletableFuture> list(ListCompaniesRequest */ public CompletableFuture> list( ListCompaniesRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("companies/list"); - if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getPerPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "per_page", request.getPerPage().get().toString(), false); - } - if (request.getOrder().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "order", request.getOrder().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("POST", RequestBody.create("", null)) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - CompanyList parsedResponse = - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CompanyList.class); - int newPageNumber = - request.getPage().map(page -> page + 1).orElse(1); - ListCompaniesRequest nextRequest = ListCompaniesRequest.builder() - .from(request) - .page(newPageNumber) - .build(); - List result = parsedResponse.getData(); - future.complete(new SyncPagingIterable(true, result, () -> { - try { - return list(nextRequest, requestOptions).get(); - } catch (InterruptedException | ExecutionException e) { - throw new RuntimeException(e); - } - })); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.list(request, requestOptions).thenApply(response -> response.body()); } /** @@ -766,7 +251,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { * {% /admonition %}

*/ public CompletableFuture> scroll() { - return scroll(ScrollCompaniesRequest.builder().build()); + return this.rawClient.scroll().thenApply(response -> response.body()); } /** @@ -787,7 +272,7 @@ public CompletableFuture> scroll() { * {% /admonition %}

*/ public CompletableFuture> scroll(ScrollCompaniesRequest request) { - return scroll(request, null); + return this.rawClient.scroll(request).thenApply(response -> response.body()); } /** @@ -809,80 +294,14 @@ public CompletableFuture> scroll(ScrollCompaniesRequ */ public CompletableFuture> scroll( ScrollCompaniesRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("companies/scroll"); - if (request.getScrollParam().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "scroll_param", request.getScrollParam().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - CompanyScroll parsedResponse = - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CompanyScroll.class); - Optional startingAfter = parsedResponse.getScrollParam(); - ScrollCompaniesRequest nextRequest = ScrollCompaniesRequest.builder() - .from(request) - .scrollParam(startingAfter) - .build(); - List result = parsedResponse.getData(); - future.complete(new SyncPagingIterable(startingAfter.isPresent(), result, () -> { - try { - return scroll(nextRequest, requestOptions).get(); - } catch (InterruptedException | ExecutionException e) { - throw new RuntimeException(e); - } - })); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.scroll(request, requestOptions).thenApply(response -> response.body()); } /** * You can attach a company to a single contact. */ public CompletableFuture attachContact(AttachContactToCompanyRequest request) { - return attachContact(request, null); + return this.rawClient.attachContact(request).thenApply(response -> response.body()); } /** @@ -890,81 +309,14 @@ public CompletableFuture attachContact(AttachContactToCompanyRequest re */ public CompletableFuture attachContact( AttachContactToCompanyRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("companies") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Company.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.attachContact(request, requestOptions).thenApply(response -> response.body()); } /** * You can detach a company from a single contact. */ public CompletableFuture detachContact(DetachContactFromCompanyRequest request) { - return detachContact(request, null); + return this.rawClient.detachContact(request).thenApply(response -> response.body()); } /** @@ -972,63 +324,6 @@ public CompletableFuture detachContact(DetachContactFromCompanyRequest */ public CompletableFuture detachContact( DetachContactFromCompanyRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("companies") - .addPathSegment(request.getCompanyId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Company.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.detachContact(request, requestOptions).thenApply(response -> response.body()); } } diff --git a/src/main/java/com/intercom/api/resources/companies/AsyncRawCompaniesClient.java b/src/main/java/com/intercom/api/resources/companies/AsyncRawCompaniesClient.java new file mode 100644 index 0000000..fea4f30 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/companies/AsyncRawCompaniesClient.java @@ -0,0 +1,1090 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.companies; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.QueryStringMapper; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.core.pagination.SyncPagingIterable; +import com.intercom.api.errors.BadRequestError; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.companies.requests.AttachContactToCompanyRequest; +import com.intercom.api.resources.companies.requests.CreateOrUpdateCompanyRequest; +import com.intercom.api.resources.companies.requests.DeleteCompanyRequest; +import com.intercom.api.resources.companies.requests.DetachContactFromCompanyRequest; +import com.intercom.api.resources.companies.requests.FindCompanyRequest; +import com.intercom.api.resources.companies.requests.ListAttachedContactsRequest; +import com.intercom.api.resources.companies.requests.ListCompaniesRequest; +import com.intercom.api.resources.companies.requests.ListSegmentsAttachedToCompanyRequest; +import com.intercom.api.resources.companies.requests.RetrieveCompanyRequest; +import com.intercom.api.resources.companies.requests.ScrollCompaniesRequest; +import com.intercom.api.resources.companies.requests.UpdateCompanyRequest; +import com.intercom.api.resources.companies.types.Company; +import com.intercom.api.types.CompanyAttachedContacts; +import com.intercom.api.types.CompanyAttachedSegments; +import com.intercom.api.types.CompanyList; +import com.intercom.api.types.CompanyScroll; +import com.intercom.api.types.DeletedCompanyObject; +import com.intercom.api.types.Error; +import java.io.IOException; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawCompaniesClient { + protected final ClientOptions clientOptions; + + public AsyncRawCompaniesClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can fetch a single company by passing in company_id or name. + *

https://api.intercom.io/companies?name={name}

+ *

https://api.intercom.io/companies?company_id={company_id}

+ *

You can fetch all companies and filter by segment_id or tag_id as a query parameter.

+ *

https://api.intercom.io/companies?tag_id={tag_id}

+ *

https://api.intercom.io/companies?segment_id={segment_id}

+ */ + public CompletableFuture> retrieve() { + return retrieve(RetrieveCompanyRequest.builder().build()); + } + + /** + * You can fetch a single company by passing in company_id or name. + *

https://api.intercom.io/companies?name={name}

+ *

https://api.intercom.io/companies?company_id={company_id}

+ *

You can fetch all companies and filter by segment_id or tag_id as a query parameter.

+ *

https://api.intercom.io/companies?tag_id={tag_id}

+ *

https://api.intercom.io/companies?segment_id={segment_id}

+ */ + public CompletableFuture> retrieve(RetrieveCompanyRequest request) { + return retrieve(request, null); + } + + /** + * You can fetch a single company by passing in company_id or name. + *

https://api.intercom.io/companies?name={name}

+ *

https://api.intercom.io/companies?company_id={company_id}

+ *

You can fetch all companies and filter by segment_id or tag_id as a query parameter.

+ *

https://api.intercom.io/companies?tag_id={tag_id}

+ *

https://api.intercom.io/companies?segment_id={segment_id}

+ */ + public CompletableFuture> retrieve( + RetrieveCompanyRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("companies"); + if (request.getName().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "name", request.getName().get(), false); + } + if (request.getCompanyId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "company_id", request.getCompanyId().get(), false); + } + if (request.getTagId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "tag_id", request.getTagId().get(), false); + } + if (request.getSegmentId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "segment_id", request.getSegmentId().get(), false); + } + if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "page", request.getPage().get().toString(), false); + } + if (request.getPerPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "per_page", request.getPerPage().get().toString(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CompanyList.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can create or update a company. + *

Companies will be only visible in Intercom when there is at least one associated user.

+ *

Companies are looked up via company_id in a POST request, if not found via company_id, the new company will be created, if found, that company will be updated.

+ *

{% admonition type="warning" name="Using company_id" %} + * You can set a unique company_id value when creating a company. However, it is not possible to update company_id. Be sure to set a unique value once upon creation of the company. + * {% /admonition %}

+ */ + public CompletableFuture> createOrUpdate() { + return createOrUpdate(CreateOrUpdateCompanyRequest.builder().build()); + } + + /** + * You can create or update a company. + *

Companies will be only visible in Intercom when there is at least one associated user.

+ *

Companies are looked up via company_id in a POST request, if not found via company_id, the new company will be created, if found, that company will be updated.

+ *

{% admonition type="warning" name="Using company_id" %} + * You can set a unique company_id value when creating a company. However, it is not possible to update company_id. Be sure to set a unique value once upon creation of the company. + * {% /admonition %}

+ */ + public CompletableFuture> createOrUpdate(CreateOrUpdateCompanyRequest request) { + return createOrUpdate(request, null); + } + + /** + * You can create or update a company. + *

Companies will be only visible in Intercom when there is at least one associated user.

+ *

Companies are looked up via company_id in a POST request, if not found via company_id, the new company will be created, if found, that company will be updated.

+ *

{% admonition type="warning" name="Using company_id" %} + * You can set a unique company_id value when creating a company. However, it is not possible to update company_id. Be sure to set a unique value once upon creation of the company. + * {% /admonition %}

+ */ + public CompletableFuture> createOrUpdate( + CreateOrUpdateCompanyRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("companies") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Company.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can fetch a single company. + */ + public CompletableFuture> find(FindCompanyRequest request) { + return find(request, null); + } + + /** + * You can fetch a single company. + */ + public CompletableFuture> find( + FindCompanyRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("companies") + .addPathSegment(request.getCompanyId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Company.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can update a single company using the Intercom provisioned id. + *

{% admonition type="warning" name="Using company_id" %} + * When updating a company it is not possible to update company_id. This can only be set once upon creation of the company. + * {% /admonition %}

+ */ + public CompletableFuture> update(UpdateCompanyRequest request) { + return update(request, null); + } + + /** + * You can update a single company using the Intercom provisioned id. + *

{% admonition type="warning" name="Using company_id" %} + * When updating a company it is not possible to update company_id. This can only be set once upon creation of the company. + * {% /admonition %}

+ */ + public CompletableFuture> update( + UpdateCompanyRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("companies") + .addPathSegment(request.getCompanyId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("PUT", RequestBody.create("", null)) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Company.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can delete a single company. + */ + public CompletableFuture> delete(DeleteCompanyRequest request) { + return delete(request, null); + } + + /** + * You can delete a single company. + */ + public CompletableFuture> delete( + DeleteCompanyRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("companies") + .addPathSegment(request.getCompanyId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeletedCompanyObject.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can fetch a list of all contacts that belong to a company. + */ + public CompletableFuture> listAttachedContacts( + ListAttachedContactsRequest request) { + return listAttachedContacts(request, null); + } + + /** + * You can fetch a list of all contacts that belong to a company. + */ + public CompletableFuture> listAttachedContacts( + ListAttachedContactsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("companies") + .addPathSegment(request.getCompanyId()) + .addPathSegments("contacts"); + if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "page", request.getPage().get().toString(), false); + } + if (request.getPerPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "per_page", request.getPerPage().get().toString(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), CompanyAttachedContacts.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can fetch a list of all segments that belong to a company. + */ + public CompletableFuture> listAttachedSegments( + ListSegmentsAttachedToCompanyRequest request) { + return listAttachedSegments(request, null); + } + + /** + * You can fetch a list of all segments that belong to a company. + */ + public CompletableFuture> listAttachedSegments( + ListSegmentsAttachedToCompanyRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("companies") + .addPathSegment(request.getCompanyId()) + .addPathSegments("segments") + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), CompanyAttachedSegments.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can list companies. The company list is sorted by the last_request_at field and by default is ordered descending, most recently requested first. + *

Note that the API does not include companies who have no associated users in list responses.

+ *

When using the Companies endpoint and the pages object to iterate through the returned companies, there is a limit of 10,000 Companies that can be returned. If you need to list or iterate on more than 10,000 Companies, please use the Scroll API. + * {% admonition type="warning" name="Pagination" %} + * You can use pagination to limit the number of results returned. The default is 20 results per page. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %}

+ */ + public CompletableFuture>> list() { + return list(ListCompaniesRequest.builder().build()); + } + + /** + * You can list companies. The company list is sorted by the last_request_at field and by default is ordered descending, most recently requested first. + *

Note that the API does not include companies who have no associated users in list responses.

+ *

When using the Companies endpoint and the pages object to iterate through the returned companies, there is a limit of 10,000 Companies that can be returned. If you need to list or iterate on more than 10,000 Companies, please use the Scroll API. + * {% admonition type="warning" name="Pagination" %} + * You can use pagination to limit the number of results returned. The default is 20 results per page. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %}

+ */ + public CompletableFuture>> list(ListCompaniesRequest request) { + return list(request, null); + } + + /** + * You can list companies. The company list is sorted by the last_request_at field and by default is ordered descending, most recently requested first. + *

Note that the API does not include companies who have no associated users in list responses.

+ *

When using the Companies endpoint and the pages object to iterate through the returned companies, there is a limit of 10,000 Companies that can be returned. If you need to list or iterate on more than 10,000 Companies, please use the Scroll API. + * {% admonition type="warning" name="Pagination" %} + * You can use pagination to limit the number of results returned. The default is 20 results per page. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %}

+ */ + public CompletableFuture>> list( + ListCompaniesRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("companies/list"); + if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "page", request.getPage().get().toString(), false); + } + if (request.getPerPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "per_page", request.getPerPage().get().toString(), false); + } + if (request.getOrder().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "order", request.getOrder().get(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("POST", RequestBody.create("", null)) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture>> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + CompanyList parsedResponse = + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CompanyList.class); + int newPageNumber = + request.getPage().map(page -> page + 1).orElse(1); + ListCompaniesRequest nextRequest = ListCompaniesRequest.builder() + .from(request) + .page(newPageNumber) + .build(); + List result = parsedResponse.getData(); + future.complete(new IntercomHttpResponse<>( + new SyncPagingIterable(true, result, () -> { + try { + return list(nextRequest, requestOptions) + .get() + .body(); + } catch (InterruptedException | ExecutionException e) { + throw new RuntimeException(e); + } + }), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * The list all companies functionality does not work well for huge datasets, and can result in errors and performance problems when paging deeply. The Scroll API provides an efficient mechanism for iterating over all companies in a dataset. + *
    + *
  • Each app can only have 1 scroll open at a time. You'll get an error message if you try to have more than one open per app.
  • + *
  • If the scroll isn't used for 1 minute, it expires and calls with that scroll param will fail
  • + *
  • If the end of the scroll is reached, "companies" will be empty and the scroll parameter will expire
  • + *
+ *

{% admonition type="info" name="Scroll Parameter" %} + * You can get the first page of companies by simply sending a GET request to the scroll endpoint. + * For subsequent requests you will need to use the scroll parameter from the response. + * {% /admonition %} + * {% admonition type="danger" name="Scroll network timeouts" %} + * Since scroll is often used on large datasets network errors such as timeouts can be encountered. When this occurs you will see a HTTP 500 error with the following message: + * "Request failed due to an internal network error. Please restart the scroll operation." + * If this happens, you will need to restart your scroll query: It is not possible to continue from a specific point when using scroll. + * {% /admonition %}

+ */ + public CompletableFuture>> scroll() { + return scroll(ScrollCompaniesRequest.builder().build()); + } + + /** + * The list all companies functionality does not work well for huge datasets, and can result in errors and performance problems when paging deeply. The Scroll API provides an efficient mechanism for iterating over all companies in a dataset. + *
    + *
  • Each app can only have 1 scroll open at a time. You'll get an error message if you try to have more than one open per app.
  • + *
  • If the scroll isn't used for 1 minute, it expires and calls with that scroll param will fail
  • + *
  • If the end of the scroll is reached, "companies" will be empty and the scroll parameter will expire
  • + *
+ *

{% admonition type="info" name="Scroll Parameter" %} + * You can get the first page of companies by simply sending a GET request to the scroll endpoint. + * For subsequent requests you will need to use the scroll parameter from the response. + * {% /admonition %} + * {% admonition type="danger" name="Scroll network timeouts" %} + * Since scroll is often used on large datasets network errors such as timeouts can be encountered. When this occurs you will see a HTTP 500 error with the following message: + * "Request failed due to an internal network error. Please restart the scroll operation." + * If this happens, you will need to restart your scroll query: It is not possible to continue from a specific point when using scroll. + * {% /admonition %}

+ */ + public CompletableFuture>> scroll(ScrollCompaniesRequest request) { + return scroll(request, null); + } + + /** + * The list all companies functionality does not work well for huge datasets, and can result in errors and performance problems when paging deeply. The Scroll API provides an efficient mechanism for iterating over all companies in a dataset. + *
    + *
  • Each app can only have 1 scroll open at a time. You'll get an error message if you try to have more than one open per app.
  • + *
  • If the scroll isn't used for 1 minute, it expires and calls with that scroll param will fail
  • + *
  • If the end of the scroll is reached, "companies" will be empty and the scroll parameter will expire
  • + *
+ *

{% admonition type="info" name="Scroll Parameter" %} + * You can get the first page of companies by simply sending a GET request to the scroll endpoint. + * For subsequent requests you will need to use the scroll parameter from the response. + * {% /admonition %} + * {% admonition type="danger" name="Scroll network timeouts" %} + * Since scroll is often used on large datasets network errors such as timeouts can be encountered. When this occurs you will see a HTTP 500 error with the following message: + * "Request failed due to an internal network error. Please restart the scroll operation." + * If this happens, you will need to restart your scroll query: It is not possible to continue from a specific point when using scroll. + * {% /admonition %}

+ */ + public CompletableFuture>> scroll( + ScrollCompaniesRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("companies/scroll"); + if (request.getScrollParam().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "scroll_param", request.getScrollParam().get(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture>> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + CompanyScroll parsedResponse = + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CompanyScroll.class); + Optional startingAfter = parsedResponse.getScrollParam(); + ScrollCompaniesRequest nextRequest = ScrollCompaniesRequest.builder() + .from(request) + .scrollParam(startingAfter) + .build(); + List result = parsedResponse.getData(); + future.complete(new IntercomHttpResponse<>( + new SyncPagingIterable(startingAfter.isPresent(), result, () -> { + try { + return scroll(nextRequest, requestOptions) + .get() + .body(); + } catch (InterruptedException | ExecutionException e) { + throw new RuntimeException(e); + } + }), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can attach a company to a single contact. + */ + public CompletableFuture> attachContact(AttachContactToCompanyRequest request) { + return attachContact(request, null); + } + + /** + * You can attach a company to a single contact. + */ + public CompletableFuture> attachContact( + AttachContactToCompanyRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("companies") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Company.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can detach a company from a single contact. + */ + public CompletableFuture> detachContact(DetachContactFromCompanyRequest request) { + return detachContact(request, null); + } + + /** + * You can detach a company from a single contact. + */ + public CompletableFuture> detachContact( + DetachContactFromCompanyRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("companies") + .addPathSegment(request.getCompanyId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Company.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/intercom/api/resources/companies/CompaniesClient.java b/src/main/java/com/intercom/api/resources/companies/CompaniesClient.java index 4811c45..1268935 100644 --- a/src/main/java/com/intercom/api/resources/companies/CompaniesClient.java +++ b/src/main/java/com/intercom/api/resources/companies/CompaniesClient.java @@ -3,18 +3,9 @@ */ package com.intercom.api.resources.companies; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; -import com.intercom.api.core.QueryStringMapper; import com.intercom.api.core.RequestOptions; import com.intercom.api.core.pagination.SyncPagingIterable; -import com.intercom.api.errors.BadRequestError; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.companies.requests.AttachContactToCompanyRequest; import com.intercom.api.resources.companies.requests.CreateOrUpdateCompanyRequest; import com.intercom.api.resources.companies.requests.DeleteCompanyRequest; @@ -30,25 +21,23 @@ import com.intercom.api.types.CompanyAttachedContacts; import com.intercom.api.types.CompanyAttachedSegments; import com.intercom.api.types.CompanyList; -import com.intercom.api.types.CompanyScroll; import com.intercom.api.types.DeletedCompanyObject; -import com.intercom.api.types.Error; -import java.io.IOException; -import java.util.List; -import java.util.Optional; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; public class CompaniesClient { protected final ClientOptions clientOptions; + private final RawCompaniesClient rawClient; + public CompaniesClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawCompaniesClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawCompaniesClient withRawResponse() { + return this.rawClient; } /** @@ -60,7 +49,7 @@ public CompaniesClient(ClientOptions clientOptions) { *

https://api.intercom.io/companies?segment_id={segment_id}

*/ public CompanyList retrieve() { - return retrieve(RetrieveCompanyRequest.builder().build()); + return this.rawClient.retrieve().body(); } /** @@ -72,7 +61,7 @@ public CompanyList retrieve() { *

https://api.intercom.io/companies?segment_id={segment_id}

*/ public CompanyList retrieve(RetrieveCompanyRequest request) { - return retrieve(request, null); + return this.rawClient.retrieve(request).body(); } /** @@ -84,68 +73,7 @@ public CompanyList retrieve(RetrieveCompanyRequest request) { *

https://api.intercom.io/companies?segment_id={segment_id}

*/ public CompanyList retrieve(RetrieveCompanyRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("companies"); - if (request.getName().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "name", request.getName().get(), false); - } - if (request.getCompanyId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "company_id", request.getCompanyId().get(), false); - } - if (request.getTagId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "tag_id", request.getTagId().get(), false); - } - if (request.getSegmentId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "segment_id", request.getSegmentId().get(), false); - } - if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getPerPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "per_page", request.getPerPage().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CompanyList.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.retrieve(request, requestOptions).body(); } /** @@ -157,7 +85,7 @@ public CompanyList retrieve(RetrieveCompanyRequest request, RequestOptions reque * {% /admonition %}

*/ public Company createOrUpdate() { - return createOrUpdate(CreateOrUpdateCompanyRequest.builder().build()); + return this.rawClient.createOrUpdate().body(); } /** @@ -169,7 +97,7 @@ public Company createOrUpdate() { * {% /admonition %}

*/ public Company createOrUpdate(CreateOrUpdateCompanyRequest request) { - return createOrUpdate(request, null); + return this.rawClient.createOrUpdate(request).body(); } /** @@ -181,106 +109,21 @@ public Company createOrUpdate(CreateOrUpdateCompanyRequest request) { * {% /admonition %}

*/ public Company createOrUpdate(CreateOrUpdateCompanyRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("companies") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Company.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.createOrUpdate(request, requestOptions).body(); } /** * You can fetch a single company. */ public Company find(FindCompanyRequest request) { - return find(request, null); + return this.rawClient.find(request).body(); } /** * You can fetch a single company. */ public Company find(FindCompanyRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("companies") - .addPathSegment(request.getCompanyId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Company.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.find(request, requestOptions).body(); } /** @@ -290,7 +133,7 @@ public Company find(FindCompanyRequest request, RequestOptions requestOptions) { * {% /admonition %}

*/ public Company update(UpdateCompanyRequest request) { - return update(request, null); + return this.rawClient.update(request).body(); } /** @@ -300,106 +143,28 @@ public Company update(UpdateCompanyRequest request) { * {% /admonition %}

*/ public Company update(UpdateCompanyRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("companies") - .addPathSegment(request.getCompanyId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("PUT", RequestBody.create("", null)) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Company.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.update(request, requestOptions).body(); } /** * You can delete a single company. */ public DeletedCompanyObject delete(DeleteCompanyRequest request) { - return delete(request, null); + return this.rawClient.delete(request).body(); } /** * You can delete a single company. */ public DeletedCompanyObject delete(DeleteCompanyRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("companies") - .addPathSegment(request.getCompanyId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeletedCompanyObject.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.delete(request, requestOptions).body(); } /** * You can fetch a list of all contacts that belong to a company. */ public CompanyAttachedContacts listAttachedContacts(ListAttachedContactsRequest request) { - return listAttachedContacts(request, null); + return this.rawClient.listAttachedContacts(request).body(); } /** @@ -407,61 +172,14 @@ public CompanyAttachedContacts listAttachedContacts(ListAttachedContactsRequest */ public CompanyAttachedContacts listAttachedContacts( ListAttachedContactsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("companies") - .addPathSegment(request.getCompanyId()) - .addPathSegments("contacts"); - if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getPerPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "per_page", request.getPerPage().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CompanyAttachedContacts.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.listAttachedContacts(request, requestOptions).body(); } /** * You can fetch a list of all segments that belong to a company. */ public CompanyAttachedSegments listAttachedSegments(ListSegmentsAttachedToCompanyRequest request) { - return listAttachedSegments(request, null); + return this.rawClient.listAttachedSegments(request).body(); } /** @@ -469,47 +187,7 @@ public CompanyAttachedSegments listAttachedSegments(ListSegmentsAttachedToCompan */ public CompanyAttachedSegments listAttachedSegments( ListSegmentsAttachedToCompanyRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("companies") - .addPathSegment(request.getCompanyId()) - .addPathSegments("segments") - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CompanyAttachedSegments.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.listAttachedSegments(request, requestOptions).body(); } /** @@ -522,7 +200,7 @@ public CompanyAttachedSegments listAttachedSegments( * {% /admonition %}

*/ public SyncPagingIterable list() { - return list(ListCompaniesRequest.builder().build()); + return this.rawClient.list().body(); } /** @@ -535,7 +213,7 @@ public SyncPagingIterable list() { * {% /admonition %}

*/ public SyncPagingIterable list(ListCompaniesRequest request) { - return list(request, null); + return this.rawClient.list(request).body(); } /** @@ -548,60 +226,7 @@ public SyncPagingIterable list(ListCompaniesRequest request) { * {% /admonition %}

*/ public SyncPagingIterable list(ListCompaniesRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("companies/list"); - if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getPerPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "per_page", request.getPerPage().get().toString(), false); - } - if (request.getOrder().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "order", request.getOrder().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("POST", RequestBody.create("", null)) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - CompanyList parsedResponse = - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CompanyList.class); - int newPageNumber = request.getPage().map(page -> page + 1).orElse(1); - ListCompaniesRequest nextRequest = ListCompaniesRequest.builder() - .from(request) - .page(newPageNumber) - .build(); - List result = parsedResponse.getData(); - return new SyncPagingIterable(true, result, () -> list(nextRequest, requestOptions)); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.list(request, requestOptions).body(); } /** @@ -622,7 +247,7 @@ public SyncPagingIterable list(ListCompaniesRequest request, RequestOpt * {% /admonition %}

*/ public SyncPagingIterable scroll() { - return scroll(ScrollCompaniesRequest.builder().build()); + return this.rawClient.scroll().body(); } /** @@ -643,7 +268,7 @@ public SyncPagingIterable scroll() { * {% /admonition %}

*/ public SyncPagingIterable scroll(ScrollCompaniesRequest request) { - return scroll(request, null); + return this.rawClient.scroll(request).body(); } /** @@ -664,171 +289,34 @@ public SyncPagingIterable scroll(ScrollCompaniesRequest request) { * {% /admonition %}

*/ public SyncPagingIterable scroll(ScrollCompaniesRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("companies/scroll"); - if (request.getScrollParam().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "scroll_param", request.getScrollParam().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - CompanyScroll parsedResponse = - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CompanyScroll.class); - Optional startingAfter = parsedResponse.getScrollParam(); - ScrollCompaniesRequest nextRequest = ScrollCompaniesRequest.builder() - .from(request) - .scrollParam(startingAfter) - .build(); - List result = parsedResponse.getData(); - return new SyncPagingIterable( - startingAfter.isPresent(), result, () -> scroll(nextRequest, requestOptions)); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.scroll(request, requestOptions).body(); } /** * You can attach a company to a single contact. */ public Company attachContact(AttachContactToCompanyRequest request) { - return attachContact(request, null); + return this.rawClient.attachContact(request).body(); } /** * You can attach a company to a single contact. */ public Company attachContact(AttachContactToCompanyRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("companies") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Company.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.attachContact(request, requestOptions).body(); } /** * You can detach a company from a single contact. */ public Company detachContact(DetachContactFromCompanyRequest request) { - return detachContact(request, null); + return this.rawClient.detachContact(request).body(); } /** * You can detach a company from a single contact. */ public Company detachContact(DetachContactFromCompanyRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("companies") - .addPathSegment(request.getCompanyId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Company.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.detachContact(request, requestOptions).body(); } } diff --git a/src/main/java/com/intercom/api/resources/companies/RawCompaniesClient.java b/src/main/java/com/intercom/api/resources/companies/RawCompaniesClient.java new file mode 100644 index 0000000..3b48b7b --- /dev/null +++ b/src/main/java/com/intercom/api/resources/companies/RawCompaniesClient.java @@ -0,0 +1,881 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.companies; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.QueryStringMapper; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.core.pagination.SyncPagingIterable; +import com.intercom.api.errors.BadRequestError; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.companies.requests.AttachContactToCompanyRequest; +import com.intercom.api.resources.companies.requests.CreateOrUpdateCompanyRequest; +import com.intercom.api.resources.companies.requests.DeleteCompanyRequest; +import com.intercom.api.resources.companies.requests.DetachContactFromCompanyRequest; +import com.intercom.api.resources.companies.requests.FindCompanyRequest; +import com.intercom.api.resources.companies.requests.ListAttachedContactsRequest; +import com.intercom.api.resources.companies.requests.ListCompaniesRequest; +import com.intercom.api.resources.companies.requests.ListSegmentsAttachedToCompanyRequest; +import com.intercom.api.resources.companies.requests.RetrieveCompanyRequest; +import com.intercom.api.resources.companies.requests.ScrollCompaniesRequest; +import com.intercom.api.resources.companies.requests.UpdateCompanyRequest; +import com.intercom.api.resources.companies.types.Company; +import com.intercom.api.types.CompanyAttachedContacts; +import com.intercom.api.types.CompanyAttachedSegments; +import com.intercom.api.types.CompanyList; +import com.intercom.api.types.CompanyScroll; +import com.intercom.api.types.DeletedCompanyObject; +import com.intercom.api.types.Error; +import java.io.IOException; +import java.util.List; +import java.util.Optional; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawCompaniesClient { + protected final ClientOptions clientOptions; + + public RawCompaniesClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can fetch a single company by passing in company_id or name. + *

https://api.intercom.io/companies?name={name}

+ *

https://api.intercom.io/companies?company_id={company_id}

+ *

You can fetch all companies and filter by segment_id or tag_id as a query parameter.

+ *

https://api.intercom.io/companies?tag_id={tag_id}

+ *

https://api.intercom.io/companies?segment_id={segment_id}

+ */ + public IntercomHttpResponse retrieve() { + return retrieve(RetrieveCompanyRequest.builder().build()); + } + + /** + * You can fetch a single company by passing in company_id or name. + *

https://api.intercom.io/companies?name={name}

+ *

https://api.intercom.io/companies?company_id={company_id}

+ *

You can fetch all companies and filter by segment_id or tag_id as a query parameter.

+ *

https://api.intercom.io/companies?tag_id={tag_id}

+ *

https://api.intercom.io/companies?segment_id={segment_id}

+ */ + public IntercomHttpResponse retrieve(RetrieveCompanyRequest request) { + return retrieve(request, null); + } + + /** + * You can fetch a single company by passing in company_id or name. + *

https://api.intercom.io/companies?name={name}

+ *

https://api.intercom.io/companies?company_id={company_id}

+ *

You can fetch all companies and filter by segment_id or tag_id as a query parameter.

+ *

https://api.intercom.io/companies?tag_id={tag_id}

+ *

https://api.intercom.io/companies?segment_id={segment_id}

+ */ + public IntercomHttpResponse retrieve(RetrieveCompanyRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("companies"); + if (request.getName().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "name", request.getName().get(), false); + } + if (request.getCompanyId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "company_id", request.getCompanyId().get(), false); + } + if (request.getTagId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "tag_id", request.getTagId().get(), false); + } + if (request.getSegmentId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "segment_id", request.getSegmentId().get(), false); + } + if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "page", request.getPage().get().toString(), false); + } + if (request.getPerPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "per_page", request.getPerPage().get().toString(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CompanyList.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can create or update a company. + *

Companies will be only visible in Intercom when there is at least one associated user.

+ *

Companies are looked up via company_id in a POST request, if not found via company_id, the new company will be created, if found, that company will be updated.

+ *

{% admonition type="warning" name="Using company_id" %} + * You can set a unique company_id value when creating a company. However, it is not possible to update company_id. Be sure to set a unique value once upon creation of the company. + * {% /admonition %}

+ */ + public IntercomHttpResponse createOrUpdate() { + return createOrUpdate(CreateOrUpdateCompanyRequest.builder().build()); + } + + /** + * You can create or update a company. + *

Companies will be only visible in Intercom when there is at least one associated user.

+ *

Companies are looked up via company_id in a POST request, if not found via company_id, the new company will be created, if found, that company will be updated.

+ *

{% admonition type="warning" name="Using company_id" %} + * You can set a unique company_id value when creating a company. However, it is not possible to update company_id. Be sure to set a unique value once upon creation of the company. + * {% /admonition %}

+ */ + public IntercomHttpResponse createOrUpdate(CreateOrUpdateCompanyRequest request) { + return createOrUpdate(request, null); + } + + /** + * You can create or update a company. + *

Companies will be only visible in Intercom when there is at least one associated user.

+ *

Companies are looked up via company_id in a POST request, if not found via company_id, the new company will be created, if found, that company will be updated.

+ *

{% admonition type="warning" name="Using company_id" %} + * You can set a unique company_id value when creating a company. However, it is not possible to update company_id. Be sure to set a unique value once upon creation of the company. + * {% /admonition %}

+ */ + public IntercomHttpResponse createOrUpdate( + CreateOrUpdateCompanyRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("companies") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Company.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can fetch a single company. + */ + public IntercomHttpResponse find(FindCompanyRequest request) { + return find(request, null); + } + + /** + * You can fetch a single company. + */ + public IntercomHttpResponse find(FindCompanyRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("companies") + .addPathSegment(request.getCompanyId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Company.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can update a single company using the Intercom provisioned id. + *

{% admonition type="warning" name="Using company_id" %} + * When updating a company it is not possible to update company_id. This can only be set once upon creation of the company. + * {% /admonition %}

+ */ + public IntercomHttpResponse update(UpdateCompanyRequest request) { + return update(request, null); + } + + /** + * You can update a single company using the Intercom provisioned id. + *

{% admonition type="warning" name="Using company_id" %} + * When updating a company it is not possible to update company_id. This can only be set once upon creation of the company. + * {% /admonition %}

+ */ + public IntercomHttpResponse update(UpdateCompanyRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("companies") + .addPathSegment(request.getCompanyId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("PUT", RequestBody.create("", null)) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Company.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can delete a single company. + */ + public IntercomHttpResponse delete(DeleteCompanyRequest request) { + return delete(request, null); + } + + /** + * You can delete a single company. + */ + public IntercomHttpResponse delete( + DeleteCompanyRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("companies") + .addPathSegment(request.getCompanyId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeletedCompanyObject.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can fetch a list of all contacts that belong to a company. + */ + public IntercomHttpResponse listAttachedContacts(ListAttachedContactsRequest request) { + return listAttachedContacts(request, null); + } + + /** + * You can fetch a list of all contacts that belong to a company. + */ + public IntercomHttpResponse listAttachedContacts( + ListAttachedContactsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("companies") + .addPathSegment(request.getCompanyId()) + .addPathSegments("contacts"); + if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "page", request.getPage().get().toString(), false); + } + if (request.getPerPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "per_page", request.getPerPage().get().toString(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CompanyAttachedContacts.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can fetch a list of all segments that belong to a company. + */ + public IntercomHttpResponse listAttachedSegments( + ListSegmentsAttachedToCompanyRequest request) { + return listAttachedSegments(request, null); + } + + /** + * You can fetch a list of all segments that belong to a company. + */ + public IntercomHttpResponse listAttachedSegments( + ListSegmentsAttachedToCompanyRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("companies") + .addPathSegment(request.getCompanyId()) + .addPathSegments("segments") + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CompanyAttachedSegments.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can list companies. The company list is sorted by the last_request_at field and by default is ordered descending, most recently requested first. + *

Note that the API does not include companies who have no associated users in list responses.

+ *

When using the Companies endpoint and the pages object to iterate through the returned companies, there is a limit of 10,000 Companies that can be returned. If you need to list or iterate on more than 10,000 Companies, please use the Scroll API. + * {% admonition type="warning" name="Pagination" %} + * You can use pagination to limit the number of results returned. The default is 20 results per page. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %}

+ */ + public IntercomHttpResponse> list() { + return list(ListCompaniesRequest.builder().build()); + } + + /** + * You can list companies. The company list is sorted by the last_request_at field and by default is ordered descending, most recently requested first. + *

Note that the API does not include companies who have no associated users in list responses.

+ *

When using the Companies endpoint and the pages object to iterate through the returned companies, there is a limit of 10,000 Companies that can be returned. If you need to list or iterate on more than 10,000 Companies, please use the Scroll API. + * {% admonition type="warning" name="Pagination" %} + * You can use pagination to limit the number of results returned. The default is 20 results per page. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %}

+ */ + public IntercomHttpResponse> list(ListCompaniesRequest request) { + return list(request, null); + } + + /** + * You can list companies. The company list is sorted by the last_request_at field and by default is ordered descending, most recently requested first. + *

Note that the API does not include companies who have no associated users in list responses.

+ *

When using the Companies endpoint and the pages object to iterate through the returned companies, there is a limit of 10,000 Companies that can be returned. If you need to list or iterate on more than 10,000 Companies, please use the Scroll API. + * {% admonition type="warning" name="Pagination" %} + * You can use pagination to limit the number of results returned. The default is 20 results per page. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %}

+ */ + public IntercomHttpResponse> list( + ListCompaniesRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("companies/list"); + if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "page", request.getPage().get().toString(), false); + } + if (request.getPerPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "per_page", request.getPerPage().get().toString(), false); + } + if (request.getOrder().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "order", request.getOrder().get(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("POST", RequestBody.create("", null)) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + CompanyList parsedResponse = + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CompanyList.class); + int newPageNumber = request.getPage().map(page -> page + 1).orElse(1); + ListCompaniesRequest nextRequest = ListCompaniesRequest.builder() + .from(request) + .page(newPageNumber) + .build(); + List result = parsedResponse.getData(); + return new IntercomHttpResponse<>( + new SyncPagingIterable(true, result, () -> list(nextRequest, requestOptions) + .body()), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * The list all companies functionality does not work well for huge datasets, and can result in errors and performance problems when paging deeply. The Scroll API provides an efficient mechanism for iterating over all companies in a dataset. + *
    + *
  • Each app can only have 1 scroll open at a time. You'll get an error message if you try to have more than one open per app.
  • + *
  • If the scroll isn't used for 1 minute, it expires and calls with that scroll param will fail
  • + *
  • If the end of the scroll is reached, "companies" will be empty and the scroll parameter will expire
  • + *
+ *

{% admonition type="info" name="Scroll Parameter" %} + * You can get the first page of companies by simply sending a GET request to the scroll endpoint. + * For subsequent requests you will need to use the scroll parameter from the response. + * {% /admonition %} + * {% admonition type="danger" name="Scroll network timeouts" %} + * Since scroll is often used on large datasets network errors such as timeouts can be encountered. When this occurs you will see a HTTP 500 error with the following message: + * "Request failed due to an internal network error. Please restart the scroll operation." + * If this happens, you will need to restart your scroll query: It is not possible to continue from a specific point when using scroll. + * {% /admonition %}

+ */ + public IntercomHttpResponse> scroll() { + return scroll(ScrollCompaniesRequest.builder().build()); + } + + /** + * The list all companies functionality does not work well for huge datasets, and can result in errors and performance problems when paging deeply. The Scroll API provides an efficient mechanism for iterating over all companies in a dataset. + *
    + *
  • Each app can only have 1 scroll open at a time. You'll get an error message if you try to have more than one open per app.
  • + *
  • If the scroll isn't used for 1 minute, it expires and calls with that scroll param will fail
  • + *
  • If the end of the scroll is reached, "companies" will be empty and the scroll parameter will expire
  • + *
+ *

{% admonition type="info" name="Scroll Parameter" %} + * You can get the first page of companies by simply sending a GET request to the scroll endpoint. + * For subsequent requests you will need to use the scroll parameter from the response. + * {% /admonition %} + * {% admonition type="danger" name="Scroll network timeouts" %} + * Since scroll is often used on large datasets network errors such as timeouts can be encountered. When this occurs you will see a HTTP 500 error with the following message: + * "Request failed due to an internal network error. Please restart the scroll operation." + * If this happens, you will need to restart your scroll query: It is not possible to continue from a specific point when using scroll. + * {% /admonition %}

+ */ + public IntercomHttpResponse> scroll(ScrollCompaniesRequest request) { + return scroll(request, null); + } + + /** + * The list all companies functionality does not work well for huge datasets, and can result in errors and performance problems when paging deeply. The Scroll API provides an efficient mechanism for iterating over all companies in a dataset. + *
    + *
  • Each app can only have 1 scroll open at a time. You'll get an error message if you try to have more than one open per app.
  • + *
  • If the scroll isn't used for 1 minute, it expires and calls with that scroll param will fail
  • + *
  • If the end of the scroll is reached, "companies" will be empty and the scroll parameter will expire
  • + *
+ *

{% admonition type="info" name="Scroll Parameter" %} + * You can get the first page of companies by simply sending a GET request to the scroll endpoint. + * For subsequent requests you will need to use the scroll parameter from the response. + * {% /admonition %} + * {% admonition type="danger" name="Scroll network timeouts" %} + * Since scroll is often used on large datasets network errors such as timeouts can be encountered. When this occurs you will see a HTTP 500 error with the following message: + * "Request failed due to an internal network error. Please restart the scroll operation." + * If this happens, you will need to restart your scroll query: It is not possible to continue from a specific point when using scroll. + * {% /admonition %}

+ */ + public IntercomHttpResponse> scroll( + ScrollCompaniesRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("companies/scroll"); + if (request.getScrollParam().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "scroll_param", request.getScrollParam().get(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + CompanyScroll parsedResponse = + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CompanyScroll.class); + Optional startingAfter = parsedResponse.getScrollParam(); + ScrollCompaniesRequest nextRequest = ScrollCompaniesRequest.builder() + .from(request) + .scrollParam(startingAfter) + .build(); + List result = parsedResponse.getData(); + return new IntercomHttpResponse<>( + new SyncPagingIterable( + startingAfter.isPresent(), result, () -> scroll(nextRequest, requestOptions) + .body()), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can attach a company to a single contact. + */ + public IntercomHttpResponse attachContact(AttachContactToCompanyRequest request) { + return attachContact(request, null); + } + + /** + * You can attach a company to a single contact. + */ + public IntercomHttpResponse attachContact( + AttachContactToCompanyRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("companies") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Company.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can detach a company from a single contact. + */ + public IntercomHttpResponse detachContact(DetachContactFromCompanyRequest request) { + return detachContact(request, null); + } + + /** + * You can detach a company from a single contact. + */ + public IntercomHttpResponse detachContact( + DetachContactFromCompanyRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("companies") + .addPathSegment(request.getCompanyId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Company.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/intercom/api/resources/contacts/AsyncContactsClient.java b/src/main/java/com/intercom/api/resources/contacts/AsyncContactsClient.java index 9d09d5f..f2a70d1 100644 --- a/src/main/java/com/intercom/api/resources/contacts/AsyncContactsClient.java +++ b/src/main/java/com/intercom/api/resources/contacts/AsyncContactsClient.java @@ -3,17 +3,9 @@ */ package com.intercom.api.resources.contacts; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; -import com.intercom.api.core.QueryStringMapper; import com.intercom.api.core.RequestOptions; import com.intercom.api.core.pagination.SyncPagingIterable; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.companies.types.Company; import com.intercom.api.resources.contacts.requests.ArchiveContactRequest; import com.intercom.api.resources.contacts.requests.AttachSubscriptionToContactRequest; @@ -31,46 +23,37 @@ import com.intercom.api.resources.contacts.types.Contact; import com.intercom.api.resources.subscriptiontypes.types.SubscriptionType; import com.intercom.api.types.ContactArchived; -import com.intercom.api.types.ContactAttachedCompanies; import com.intercom.api.types.ContactDeleted; -import com.intercom.api.types.ContactList; import com.intercom.api.types.ContactSegments; import com.intercom.api.types.ContactUnarchived; import com.intercom.api.types.CreateContactRequest; -import com.intercom.api.types.CursorPages; -import com.intercom.api.types.Error; import com.intercom.api.types.SearchRequest; -import com.intercom.api.types.StartingAfterPaging; import com.intercom.api.types.SubscriptionTypeList; import com.intercom.api.types.TagList; -import java.io.IOException; -import java.util.List; -import java.util.Optional; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; public class AsyncContactsClient { protected final ClientOptions clientOptions; + private final AsyncRawContactsClient rawClient; + public AsyncContactsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new AsyncRawContactsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawContactsClient withRawResponse() { + return this.rawClient; } /** * You can fetch a list of companies that are associated to a contact. */ public CompletableFuture> listAttachedCompanies(ListAttachedCompaniesRequest request) { - return listAttachedCompanies(request, null); + return this.rawClient.listAttachedCompanies(request).thenApply(response -> response.body()); } /** @@ -78,93 +61,14 @@ public CompletableFuture> listAttachedCompanies(List */ public CompletableFuture> listAttachedCompanies( ListAttachedCompaniesRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("companies"); - if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getPerPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "per_page", request.getPerPage().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - ContactAttachedCompanies parsedResponse = ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), ContactAttachedCompanies.class); - int newPageNumber = - request.getPage().map(page -> page + 1).orElse(1); - ListAttachedCompaniesRequest nextRequest = ListAttachedCompaniesRequest.builder() - .from(request) - .page(newPageNumber) - .build(); - List result = parsedResponse.getCompanies(); - future.complete(new SyncPagingIterable(true, result, () -> { - try { - return listAttachedCompanies(nextRequest, requestOptions) - .get(); - } catch (InterruptedException | ExecutionException e) { - throw new RuntimeException(e); - } - })); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.listAttachedCompanies(request, requestOptions).thenApply(response -> response.body()); } /** * You can fetch a list of segments that are associated to a contact. */ public CompletableFuture listAttachedSegments(ListSegmentsAttachedToContactRequest request) { - return listAttachedSegments(request, null); + return this.rawClient.listAttachedSegments(request).thenApply(response -> response.body()); } /** @@ -172,64 +76,7 @@ public CompletableFuture listAttachedSegments(ListSegmentsAttac */ public CompletableFuture listAttachedSegments( ListSegmentsAttachedToContactRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("segments") - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ContactSegments.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.listAttachedSegments(request, requestOptions).thenApply(response -> response.body()); } /** @@ -240,7 +87,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { * 2.Opt-in subscription types that the user has opted-in to receiving.

*/ public CompletableFuture listAttachedSubscriptions(ListAttachedSubscriptionsRequest request) { - return listAttachedSubscriptions(request, null); + return this.rawClient.listAttachedSubscriptions(request).thenApply(response -> response.body()); } /** @@ -252,64 +99,7 @@ public CompletableFuture listAttachedSubscriptions(ListAtt */ public CompletableFuture listAttachedSubscriptions( ListAttachedSubscriptionsRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("subscriptions") - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SubscriptionTypeList.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.listAttachedSubscriptions(request, requestOptions).thenApply(response -> response.body()); } /** @@ -319,7 +109,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { *

This will return a subscription type model for the subscription type that was added to the contact.

*/ public CompletableFuture attachSubscription(AttachSubscriptionToContactRequest request) { - return attachSubscription(request, null); + return this.rawClient.attachSubscription(request).thenApply(response -> response.body()); } /** @@ -330,78 +120,14 @@ public CompletableFuture attachSubscription(AttachSubscription */ public CompletableFuture attachSubscription( AttachSubscriptionToContactRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("subscriptions") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SubscriptionType.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.attachSubscription(request, requestOptions).thenApply(response -> response.body()); } /** * You can remove a specific subscription from a contact. This will return a subscription type model for the subscription type that was removed from the contact. */ public CompletableFuture detachSubscription(DetachSubscriptionFromContactRequest request) { - return detachSubscription(request, null); + return this.rawClient.detachSubscription(request).thenApply(response -> response.body()); } /** @@ -409,72 +135,14 @@ public CompletableFuture detachSubscription(DetachSubscription */ public CompletableFuture detachSubscription( DetachSubscriptionFromContactRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("subscriptions") - .addPathSegment(request.getSubscriptionId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SubscriptionType.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.detachSubscription(request, requestOptions).thenApply(response -> response.body()); } /** * You can fetch a list of all tags that are attached to a specific contact. */ public CompletableFuture listAttachedTags(ListTagsAttachedToContactRequest request) { - return listAttachedTags(request, null); + return this.rawClient.listAttachedTags(request).thenApply(response -> response.body()); } /** @@ -482,333 +150,63 @@ public CompletableFuture listAttachedTags(ListTagsAttachedToContactRequ */ public CompletableFuture listAttachedTags( ListTagsAttachedToContactRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("tags") - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TagList.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.listAttachedTags(request, requestOptions).thenApply(response -> response.body()); } /** * You can fetch the details of a single contact. */ public CompletableFuture find(FindContactRequest request) { - return find(request, null); + return this.rawClient.find(request).thenApply(response -> response.body()); } /** * You can fetch the details of a single contact. */ public CompletableFuture find(FindContactRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Contact.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.find(request, requestOptions).thenApply(response -> response.body()); } /** * You can update an existing contact (ie. user or lead). */ public CompletableFuture update(UpdateContactRequest request) { - return update(request, null); + return this.rawClient.update(request).thenApply(response -> response.body()); } /** * You can update an existing contact (ie. user or lead). */ public CompletableFuture update(UpdateContactRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PUT", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Contact.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.update(request, requestOptions).thenApply(response -> response.body()); } /** * You can delete a single contact. */ public CompletableFuture delete(DeleteContactRequest request) { - return delete(request, null); + return this.rawClient.delete(request).thenApply(response -> response.body()); } /** * You can delete a single contact. */ public CompletableFuture delete(DeleteContactRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ContactDeleted.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.delete(request, requestOptions).thenApply(response -> response.body()); } /** * You can merge a contact with a role of lead into a contact with a role of user. */ public CompletableFuture mergeLeadInUser(MergeContactsRequest request) { - return mergeLeadInUser(request, null); + return this.rawClient.mergeLeadInUser(request).thenApply(response -> response.body()); } /** * You can merge a contact with a role of lead into a contact with a role of user. */ public CompletableFuture mergeLeadInUser(MergeContactsRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts/merge") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Contact.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.mergeLeadInUser(request, requestOptions).thenApply(response -> response.body()); } /** @@ -900,7 +298,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { * | $ | String | Ends With |

*/ public CompletableFuture> search(SearchRequest request) { - return search(request, null); + return this.rawClient.search(request).thenApply(response -> response.body()); } /** @@ -992,85 +390,7 @@ public CompletableFuture> search(SearchRequest reque * | $ | String | Ends With |

*/ public CompletableFuture> search(SearchRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts/search") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - ContactList parsedResponse = - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ContactList.class); - Optional startingAfter = parsedResponse - .getPages() - .flatMap(CursorPages::getNext) - .flatMap(StartingAfterPaging::getStartingAfter); - Optional pagination = request.getPagination() - .map(pagination_ -> StartingAfterPaging.builder() - .from(pagination_) - .startingAfter(startingAfter) - .build()); - SearchRequest nextRequest = SearchRequest.builder() - .from(request) - .pagination(pagination) - .build(); - List result = parsedResponse.getData(); - future.complete(new SyncPagingIterable(startingAfter.isPresent(), result, () -> { - try { - return search(nextRequest, requestOptions).get(); - } catch (InterruptedException | ExecutionException e) { - throw new RuntimeException(e); - } - })); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.search(request, requestOptions).thenApply(response -> response.body()); } /** @@ -1081,7 +401,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { * {% /admonition %} */ public CompletableFuture> list() { - return list(ListContactsRequest.builder().build()); + return this.rawClient.list().thenApply(response -> response.body()); } /** @@ -1092,7 +412,7 @@ public CompletableFuture> list() { * {% /admonition %} */ public CompletableFuture> list(ListContactsRequest request) { - return list(request, null); + return this.rawClient.list(request).thenApply(response -> response.body()); } /** @@ -1104,218 +424,42 @@ public CompletableFuture> list(ListContactsRequest r */ public CompletableFuture> list( ListContactsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts"); - if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getPerPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "per_page", request.getPerPage().get().toString(), false); - } - if (request.getStartingAfter().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "starting_after", request.getStartingAfter().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - ContactList parsedResponse = - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ContactList.class); - Optional startingAfter = parsedResponse - .getPages() - .flatMap(CursorPages::getNext) - .flatMap(StartingAfterPaging::getStartingAfter); - ListContactsRequest nextRequest = ListContactsRequest.builder() - .from(request) - .startingAfter(startingAfter) - .build(); - List result = parsedResponse.getData(); - future.complete(new SyncPagingIterable(startingAfter.isPresent(), result, () -> { - try { - return list(nextRequest, requestOptions).get(); - } catch (InterruptedException | ExecutionException e) { - throw new RuntimeException(e); - } - })); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.list(request, requestOptions).thenApply(response -> response.body()); } /** * You can create a new contact (ie. user or lead). */ public CompletableFuture create(CreateContactRequest request) { - return create(request, null); + return this.rawClient.create(request).thenApply(response -> response.body()); } /** * You can create a new contact (ie. user or lead). */ public CompletableFuture create(CreateContactRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Contact.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.create(request, requestOptions).thenApply(response -> response.body()); } /** * You can archive a single contact. */ public CompletableFuture archive(ArchiveContactRequest request) { - return archive(request, null); + return this.rawClient.archive(request).thenApply(response -> response.body()); } /** * You can archive a single contact. */ public CompletableFuture archive(ArchiveContactRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("archive") - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("POST", RequestBody.create("", null)) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ContactArchived.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.archive(request, requestOptions).thenApply(response -> response.body()); } /** * You can unarchive a single contact. */ public CompletableFuture unarchive(UnarchiveContactRequest request) { - return unarchive(request, null); + return this.rawClient.unarchive(request).thenApply(response -> response.body()); } /** @@ -1323,49 +467,6 @@ public CompletableFuture unarchive(UnarchiveContactRequest re */ public CompletableFuture unarchive( UnarchiveContactRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("unarchive") - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("POST", RequestBody.create("", null)) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ContactUnarchived.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.unarchive(request, requestOptions).thenApply(response -> response.body()); } } diff --git a/src/main/java/com/intercom/api/resources/contacts/AsyncRawContactsClient.java b/src/main/java/com/intercom/api/resources/contacts/AsyncRawContactsClient.java new file mode 100644 index 0000000..28dc93a --- /dev/null +++ b/src/main/java/com/intercom/api/resources/contacts/AsyncRawContactsClient.java @@ -0,0 +1,1434 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.contacts; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.QueryStringMapper; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.core.pagination.SyncPagingIterable; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.companies.types.Company; +import com.intercom.api.resources.contacts.requests.ArchiveContactRequest; +import com.intercom.api.resources.contacts.requests.AttachSubscriptionToContactRequest; +import com.intercom.api.resources.contacts.requests.DeleteContactRequest; +import com.intercom.api.resources.contacts.requests.DetachSubscriptionFromContactRequest; +import com.intercom.api.resources.contacts.requests.FindContactRequest; +import com.intercom.api.resources.contacts.requests.ListAttachedCompaniesRequest; +import com.intercom.api.resources.contacts.requests.ListAttachedSubscriptionsRequest; +import com.intercom.api.resources.contacts.requests.ListContactsRequest; +import com.intercom.api.resources.contacts.requests.ListSegmentsAttachedToContactRequest; +import com.intercom.api.resources.contacts.requests.ListTagsAttachedToContactRequest; +import com.intercom.api.resources.contacts.requests.MergeContactsRequest; +import com.intercom.api.resources.contacts.requests.UnarchiveContactRequest; +import com.intercom.api.resources.contacts.requests.UpdateContactRequest; +import com.intercom.api.resources.contacts.types.Contact; +import com.intercom.api.resources.subscriptiontypes.types.SubscriptionType; +import com.intercom.api.types.ContactArchived; +import com.intercom.api.types.ContactAttachedCompanies; +import com.intercom.api.types.ContactDeleted; +import com.intercom.api.types.ContactList; +import com.intercom.api.types.ContactSegments; +import com.intercom.api.types.ContactUnarchived; +import com.intercom.api.types.CreateContactRequest; +import com.intercom.api.types.CursorPages; +import com.intercom.api.types.Error; +import com.intercom.api.types.SearchRequest; +import com.intercom.api.types.StartingAfterPaging; +import com.intercom.api.types.SubscriptionTypeList; +import com.intercom.api.types.TagList; +import java.io.IOException; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawContactsClient { + protected final ClientOptions clientOptions; + + public AsyncRawContactsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can fetch a list of companies that are associated to a contact. + */ + public CompletableFuture>> listAttachedCompanies( + ListAttachedCompaniesRequest request) { + return listAttachedCompanies(request, null); + } + + /** + * You can fetch a list of companies that are associated to a contact. + */ + public CompletableFuture>> listAttachedCompanies( + ListAttachedCompaniesRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("companies"); + if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "page", request.getPage().get().toString(), false); + } + if (request.getPerPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "per_page", request.getPerPage().get().toString(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture>> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + ContactAttachedCompanies parsedResponse = ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), ContactAttachedCompanies.class); + int newPageNumber = + request.getPage().map(page -> page + 1).orElse(1); + ListAttachedCompaniesRequest nextRequest = ListAttachedCompaniesRequest.builder() + .from(request) + .page(newPageNumber) + .build(); + List result = parsedResponse.getCompanies(); + future.complete(new IntercomHttpResponse<>( + new SyncPagingIterable(true, result, () -> { + try { + return listAttachedCompanies(nextRequest, requestOptions) + .get() + .body(); + } catch (InterruptedException | ExecutionException e) { + throw new RuntimeException(e); + } + }), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can fetch a list of segments that are associated to a contact. + */ + public CompletableFuture> listAttachedSegments( + ListSegmentsAttachedToContactRequest request) { + return listAttachedSegments(request, null); + } + + /** + * You can fetch a list of segments that are associated to a contact. + */ + public CompletableFuture> listAttachedSegments( + ListSegmentsAttachedToContactRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("segments") + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ContactSegments.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can fetch a list of subscription types that are attached to a contact. These can be subscriptions that a user has 'opted-in' to or has 'opted-out' from, depending on the subscription type. + * This will return a list of Subscription Type objects that the contact is associated with. + *

The data property will show a combined list of:

+ *

1.Opt-out subscription types that the user has opted-out from. + * 2.Opt-in subscription types that the user has opted-in to receiving.

+ */ + public CompletableFuture> listAttachedSubscriptions( + ListAttachedSubscriptionsRequest request) { + return listAttachedSubscriptions(request, null); + } + + /** + * You can fetch a list of subscription types that are attached to a contact. These can be subscriptions that a user has 'opted-in' to or has 'opted-out' from, depending on the subscription type. + * This will return a list of Subscription Type objects that the contact is associated with. + *

The data property will show a combined list of:

+ *

1.Opt-out subscription types that the user has opted-out from. + * 2.Opt-in subscription types that the user has opted-in to receiving.

+ */ + public CompletableFuture> listAttachedSubscriptions( + ListAttachedSubscriptionsRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("subscriptions") + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SubscriptionTypeList.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can add a specific subscription to a contact. In Intercom, we have two different subscription types based on user consent - opt-out and opt-in: + *

1.Attaching a contact to an opt-out subscription type will opt that user out from receiving messages related to that subscription type.

+ *

2.Attaching a contact to an opt-in subscription type will opt that user in to receiving messages related to that subscription type.

+ *

This will return a subscription type model for the subscription type that was added to the contact.

+ */ + public CompletableFuture> attachSubscription( + AttachSubscriptionToContactRequest request) { + return attachSubscription(request, null); + } + + /** + * You can add a specific subscription to a contact. In Intercom, we have two different subscription types based on user consent - opt-out and opt-in: + *

1.Attaching a contact to an opt-out subscription type will opt that user out from receiving messages related to that subscription type.

+ *

2.Attaching a contact to an opt-in subscription type will opt that user in to receiving messages related to that subscription type.

+ *

This will return a subscription type model for the subscription type that was added to the contact.

+ */ + public CompletableFuture> attachSubscription( + AttachSubscriptionToContactRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("subscriptions") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SubscriptionType.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can remove a specific subscription from a contact. This will return a subscription type model for the subscription type that was removed from the contact. + */ + public CompletableFuture> detachSubscription( + DetachSubscriptionFromContactRequest request) { + return detachSubscription(request, null); + } + + /** + * You can remove a specific subscription from a contact. This will return a subscription type model for the subscription type that was removed from the contact. + */ + public CompletableFuture> detachSubscription( + DetachSubscriptionFromContactRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("subscriptions") + .addPathSegment(request.getSubscriptionId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SubscriptionType.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can fetch a list of all tags that are attached to a specific contact. + */ + public CompletableFuture> listAttachedTags(ListTagsAttachedToContactRequest request) { + return listAttachedTags(request, null); + } + + /** + * You can fetch a list of all tags that are attached to a specific contact. + */ + public CompletableFuture> listAttachedTags( + ListTagsAttachedToContactRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("tags") + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TagList.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can fetch the details of a single contact. + */ + public CompletableFuture> find(FindContactRequest request) { + return find(request, null); + } + + /** + * You can fetch the details of a single contact. + */ + public CompletableFuture> find( + FindContactRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Contact.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can update an existing contact (ie. user or lead). + */ + public CompletableFuture> update(UpdateContactRequest request) { + return update(request, null); + } + + /** + * You can update an existing contact (ie. user or lead). + */ + public CompletableFuture> update( + UpdateContactRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Contact.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can delete a single contact. + */ + public CompletableFuture> delete(DeleteContactRequest request) { + return delete(request, null); + } + + /** + * You can delete a single contact. + */ + public CompletableFuture> delete( + DeleteContactRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ContactDeleted.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can merge a contact with a role of lead into a contact with a role of user. + */ + public CompletableFuture> mergeLeadInUser(MergeContactsRequest request) { + return mergeLeadInUser(request, null); + } + + /** + * You can merge a contact with a role of lead into a contact with a role of user. + */ + public CompletableFuture> mergeLeadInUser( + MergeContactsRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts/merge") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Contact.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can search for multiple contacts by the value of their attributes in order to fetch exactly who you want. + *

To search for contacts, you need to send a POST request to https://api.intercom.io/contacts/search.

+ *

This will accept a query object in the body which will define your filters in order to search for contacts.

+ *

{% admonition type="warning" name="Optimizing search queries" %} + * Search queries can be complex, so optimizing them can help the performance of your search. + * Use the AND and OR operators to combine multiple filters to get the exact results you need and utilize + * pagination to limit the number of results returned. The default is 50 results per page. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %}

+ *

Contact Creation Delay

+ *

If a contact has recently been created, there is a possibility that it will not yet be available when searching. This means that it may not appear in the response. This delay can take a few minutes. If you need to be instantly notified it is recommended to use webhooks and iterate to see if they match your search filters.

+ *

Nesting & Limitations

+ *

You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4). + * There are some limitations to the amount of multiple's there can be:

+ *
    + *
  • There's a limit of max 2 nested filters
  • + *
  • There's a limit of max 15 filters for each AND or OR group
  • + *
+ *

Searching for Timestamp Fields

+ *

All timestamp fields (created_at, updated_at etc.) are indexed as Dates for Contact Search queries; Datetime queries are not currently supported. This means you can only query for timestamp fields by day - not hour, minute or second. + * For example, if you search for all Contacts with a created_at value greater (>) than 1577869200 (the UNIX timestamp for January 1st, 2020 9:00 AM), that will be interpreted as 1577836800 (January 1st, 2020 12:00 AM). The search results will then include Contacts created from January 2nd, 2020 12:00 AM onwards. + * If you'd like to get contacts created on January 1st, 2020 you should search with a created_at value equal (=) to 1577836800 (January 1st, 2020 12:00 AM). + * This behaviour applies only to timestamps used in search queries. The search results will still contain the full UNIX timestamp and be sorted accordingly.

+ *

Accepted Fields

+ *

Most key listed as part of the Contacts Model are searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as created_at accepts a date, the value cannot be a string such as "foorbar").

+ *

| Field | Type | + * | ---------------------------------- | ------------------------------ | + * | id | String | + * | role | String<br>Accepts user or lead | + * | name | String | + * | avatar | String | + * | owner_id | Integer | + * | email | String | + * | email_domain | String | + * | phone | String | + * | external_id | String | + * | created_at | Date (UNIX Timestamp) | + * | signed_up_at | Date (UNIX Timestamp) | + * | updated_at | Date (UNIX Timestamp) | + * | last_seen_at | Date (UNIX Timestamp) | + * | last_contacted_at | Date (UNIX Timestamp) | + * | last_replied_at | Date (UNIX Timestamp) | + * | last_email_opened_at | Date (UNIX Timestamp) | + * | last_email_clicked_at | Date (UNIX Timestamp) | + * | language_override | String | + * | browser | String | + * | browser_language | String | + * | os | String | + * | location.country | String | + * | location.region | String | + * | location.city | String | + * | unsubscribed_from_emails | Boolean | + * | marked_email_as_spam | Boolean | + * | has_hard_bounced | Boolean | + * | ios_last_seen_at | Date (UNIX Timestamp) | + * | ios_app_version | String | + * | ios_device | String | + * | ios_app_device | String | + * | ios_os_version | String | + * | ios_app_name | String | + * | ios_sdk_version | String | + * | android_last_seen_at | Date (UNIX Timestamp) | + * | android_app_version | String | + * | android_device | String | + * | android_app_name | String | + * | andoid_sdk_version | String | + * | segment_id | String | + * | tag_id | String | + * | custom_attributes.{attribute_name} | String |

+ *

Accepted Operators

+ *

{% admonition type="warning" name="Searching based on created_at" %} + * You cannot use the <= or >= operators to search by created_at. + * {% /admonition %}

+ *

The table below shows the operators you can use to define how you want to search for the value. The operator should be put in as a string ("="). The operator has to be compatible with the field's type (eg. you cannot search with > for a given string value as it's only compatible for integer's and dates).

+ *

| Operator | Valid Types | Description | + * | :------- | :------------------------------- | :--------------------------------------------------------------- | + * | = | All | Equals | + * | != | All | Doesn't Equal | + * | IN | All | In<br>Shortcut for OR queries<br>Values must be in Array | + * | NIN | All | Not In<br>Shortcut for OR ! queries<br>Values must be in Array | + * | > | Integer<br>Date (UNIX Timestamp) | Greater than | + * | < | Integer<br>Date (UNIX Timestamp) | Lower than | + * | ~ | String | Contains | + * | !~ | String | Doesn't Contain | + * | ^ | String | Starts With | + * | $ | String | Ends With |

+ */ + public CompletableFuture>> search(SearchRequest request) { + return search(request, null); + } + + /** + * You can search for multiple contacts by the value of their attributes in order to fetch exactly who you want. + *

To search for contacts, you need to send a POST request to https://api.intercom.io/contacts/search.

+ *

This will accept a query object in the body which will define your filters in order to search for contacts.

+ *

{% admonition type="warning" name="Optimizing search queries" %} + * Search queries can be complex, so optimizing them can help the performance of your search. + * Use the AND and OR operators to combine multiple filters to get the exact results you need and utilize + * pagination to limit the number of results returned. The default is 50 results per page. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %}

+ *

Contact Creation Delay

+ *

If a contact has recently been created, there is a possibility that it will not yet be available when searching. This means that it may not appear in the response. This delay can take a few minutes. If you need to be instantly notified it is recommended to use webhooks and iterate to see if they match your search filters.

+ *

Nesting & Limitations

+ *

You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4). + * There are some limitations to the amount of multiple's there can be:

+ *
    + *
  • There's a limit of max 2 nested filters
  • + *
  • There's a limit of max 15 filters for each AND or OR group
  • + *
+ *

Searching for Timestamp Fields

+ *

All timestamp fields (created_at, updated_at etc.) are indexed as Dates for Contact Search queries; Datetime queries are not currently supported. This means you can only query for timestamp fields by day - not hour, minute or second. + * For example, if you search for all Contacts with a created_at value greater (>) than 1577869200 (the UNIX timestamp for January 1st, 2020 9:00 AM), that will be interpreted as 1577836800 (January 1st, 2020 12:00 AM). The search results will then include Contacts created from January 2nd, 2020 12:00 AM onwards. + * If you'd like to get contacts created on January 1st, 2020 you should search with a created_at value equal (=) to 1577836800 (January 1st, 2020 12:00 AM). + * This behaviour applies only to timestamps used in search queries. The search results will still contain the full UNIX timestamp and be sorted accordingly.

+ *

Accepted Fields

+ *

Most key listed as part of the Contacts Model are searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as created_at accepts a date, the value cannot be a string such as "foorbar").

+ *

| Field | Type | + * | ---------------------------------- | ------------------------------ | + * | id | String | + * | role | String<br>Accepts user or lead | + * | name | String | + * | avatar | String | + * | owner_id | Integer | + * | email | String | + * | email_domain | String | + * | phone | String | + * | external_id | String | + * | created_at | Date (UNIX Timestamp) | + * | signed_up_at | Date (UNIX Timestamp) | + * | updated_at | Date (UNIX Timestamp) | + * | last_seen_at | Date (UNIX Timestamp) | + * | last_contacted_at | Date (UNIX Timestamp) | + * | last_replied_at | Date (UNIX Timestamp) | + * | last_email_opened_at | Date (UNIX Timestamp) | + * | last_email_clicked_at | Date (UNIX Timestamp) | + * | language_override | String | + * | browser | String | + * | browser_language | String | + * | os | String | + * | location.country | String | + * | location.region | String | + * | location.city | String | + * | unsubscribed_from_emails | Boolean | + * | marked_email_as_spam | Boolean | + * | has_hard_bounced | Boolean | + * | ios_last_seen_at | Date (UNIX Timestamp) | + * | ios_app_version | String | + * | ios_device | String | + * | ios_app_device | String | + * | ios_os_version | String | + * | ios_app_name | String | + * | ios_sdk_version | String | + * | android_last_seen_at | Date (UNIX Timestamp) | + * | android_app_version | String | + * | android_device | String | + * | android_app_name | String | + * | andoid_sdk_version | String | + * | segment_id | String | + * | tag_id | String | + * | custom_attributes.{attribute_name} | String |

+ *

Accepted Operators

+ *

{% admonition type="warning" name="Searching based on created_at" %} + * You cannot use the <= or >= operators to search by created_at. + * {% /admonition %}

+ *

The table below shows the operators you can use to define how you want to search for the value. The operator should be put in as a string ("="). The operator has to be compatible with the field's type (eg. you cannot search with > for a given string value as it's only compatible for integer's and dates).

+ *

| Operator | Valid Types | Description | + * | :------- | :------------------------------- | :--------------------------------------------------------------- | + * | = | All | Equals | + * | != | All | Doesn't Equal | + * | IN | All | In<br>Shortcut for OR queries<br>Values must be in Array | + * | NIN | All | Not In<br>Shortcut for OR ! queries<br>Values must be in Array | + * | > | Integer<br>Date (UNIX Timestamp) | Greater than | + * | < | Integer<br>Date (UNIX Timestamp) | Lower than | + * | ~ | String | Contains | + * | !~ | String | Doesn't Contain | + * | ^ | String | Starts With | + * | $ | String | Ends With |

+ */ + public CompletableFuture>> search( + SearchRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts/search") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture>> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + ContactList parsedResponse = + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ContactList.class); + Optional startingAfter = parsedResponse + .getPages() + .flatMap(CursorPages::getNext) + .flatMap(StartingAfterPaging::getStartingAfter); + Optional pagination = request.getPagination() + .map(pagination_ -> StartingAfterPaging.builder() + .from(pagination_) + .startingAfter(startingAfter) + .build()); + SearchRequest nextRequest = SearchRequest.builder() + .from(request) + .pagination(pagination) + .build(); + List result = parsedResponse.getData(); + future.complete(new IntercomHttpResponse<>( + new SyncPagingIterable(startingAfter.isPresent(), result, () -> { + try { + return search(nextRequest, requestOptions) + .get() + .body(); + } catch (InterruptedException | ExecutionException e) { + throw new RuntimeException(e); + } + }), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can fetch a list of all contacts (ie. users or leads) in your workspace. + * {% admonition type="warning" name="Pagination" %} + * You can use pagination to limit the number of results returned. The default is 50 results per page. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %} + */ + public CompletableFuture>> list() { + return list(ListContactsRequest.builder().build()); + } + + /** + * You can fetch a list of all contacts (ie. users or leads) in your workspace. + * {% admonition type="warning" name="Pagination" %} + * You can use pagination to limit the number of results returned. The default is 50 results per page. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %} + */ + public CompletableFuture>> list(ListContactsRequest request) { + return list(request, null); + } + + /** + * You can fetch a list of all contacts (ie. users or leads) in your workspace. + * {% admonition type="warning" name="Pagination" %} + * You can use pagination to limit the number of results returned. The default is 50 results per page. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %} + */ + public CompletableFuture>> list( + ListContactsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts"); + if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "page", request.getPage().get().toString(), false); + } + if (request.getPerPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "per_page", request.getPerPage().get().toString(), false); + } + if (request.getStartingAfter().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "starting_after", request.getStartingAfter().get(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture>> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + ContactList parsedResponse = + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ContactList.class); + Optional startingAfter = parsedResponse + .getPages() + .flatMap(CursorPages::getNext) + .flatMap(StartingAfterPaging::getStartingAfter); + ListContactsRequest nextRequest = ListContactsRequest.builder() + .from(request) + .startingAfter(startingAfter) + .build(); + List result = parsedResponse.getData(); + future.complete(new IntercomHttpResponse<>( + new SyncPagingIterable(startingAfter.isPresent(), result, () -> { + try { + return list(nextRequest, requestOptions) + .get() + .body(); + } catch (InterruptedException | ExecutionException e) { + throw new RuntimeException(e); + } + }), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can create a new contact (ie. user or lead). + */ + public CompletableFuture> create(CreateContactRequest request) { + return create(request, null); + } + + /** + * You can create a new contact (ie. user or lead). + */ + public CompletableFuture> create( + CreateContactRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Contact.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can archive a single contact. + */ + public CompletableFuture> archive(ArchiveContactRequest request) { + return archive(request, null); + } + + /** + * You can archive a single contact. + */ + public CompletableFuture> archive( + ArchiveContactRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("archive") + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("POST", RequestBody.create("", null)) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ContactArchived.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can unarchive a single contact. + */ + public CompletableFuture> unarchive(UnarchiveContactRequest request) { + return unarchive(request, null); + } + + /** + * You can unarchive a single contact. + */ + public CompletableFuture> unarchive( + UnarchiveContactRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("unarchive") + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("POST", RequestBody.create("", null)) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ContactUnarchived.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/intercom/api/resources/contacts/ContactsClient.java b/src/main/java/com/intercom/api/resources/contacts/ContactsClient.java index dcf93cf..dd7ed73 100644 --- a/src/main/java/com/intercom/api/resources/contacts/ContactsClient.java +++ b/src/main/java/com/intercom/api/resources/contacts/ContactsClient.java @@ -3,17 +3,9 @@ */ package com.intercom.api.resources.contacts; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; -import com.intercom.api.core.QueryStringMapper; import com.intercom.api.core.RequestOptions; import com.intercom.api.core.pagination.SyncPagingIterable; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.companies.types.Company; import com.intercom.api.resources.contacts.requests.ArchiveContactRequest; import com.intercom.api.resources.contacts.requests.AttachSubscriptionToContactRequest; @@ -31,41 +23,36 @@ import com.intercom.api.resources.contacts.types.Contact; import com.intercom.api.resources.subscriptiontypes.types.SubscriptionType; import com.intercom.api.types.ContactArchived; -import com.intercom.api.types.ContactAttachedCompanies; import com.intercom.api.types.ContactDeleted; -import com.intercom.api.types.ContactList; import com.intercom.api.types.ContactSegments; import com.intercom.api.types.ContactUnarchived; import com.intercom.api.types.CreateContactRequest; -import com.intercom.api.types.CursorPages; -import com.intercom.api.types.Error; import com.intercom.api.types.SearchRequest; -import com.intercom.api.types.StartingAfterPaging; import com.intercom.api.types.SubscriptionTypeList; import com.intercom.api.types.TagList; -import java.io.IOException; -import java.util.List; -import java.util.Optional; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; public class ContactsClient { protected final ClientOptions clientOptions; + private final RawContactsClient rawClient; + public ContactsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawContactsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawContactsClient withRawResponse() { + return this.rawClient; } /** * You can fetch a list of companies that are associated to a contact. */ public SyncPagingIterable listAttachedCompanies(ListAttachedCompaniesRequest request) { - return listAttachedCompanies(request, null); + return this.rawClient.listAttachedCompanies(request).body(); } /** @@ -73,70 +60,14 @@ public SyncPagingIterable listAttachedCompanies(ListAttachedCompaniesRe */ public SyncPagingIterable listAttachedCompanies( ListAttachedCompaniesRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("companies"); - if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getPerPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "per_page", request.getPerPage().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - ContactAttachedCompanies parsedResponse = - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ContactAttachedCompanies.class); - int newPageNumber = request.getPage().map(page -> page + 1).orElse(1); - ListAttachedCompaniesRequest nextRequest = ListAttachedCompaniesRequest.builder() - .from(request) - .page(newPageNumber) - .build(); - List result = parsedResponse.getCompanies(); - return new SyncPagingIterable( - true, result, () -> listAttachedCompanies(nextRequest, requestOptions)); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.listAttachedCompanies(request, requestOptions).body(); } /** * You can fetch a list of segments that are associated to a contact. */ public ContactSegments listAttachedSegments(ListSegmentsAttachedToContactRequest request) { - return listAttachedSegments(request, null); + return this.rawClient.listAttachedSegments(request).body(); } /** @@ -144,47 +75,7 @@ public ContactSegments listAttachedSegments(ListSegmentsAttachedToContactRequest */ public ContactSegments listAttachedSegments( ListSegmentsAttachedToContactRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("segments") - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ContactSegments.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.listAttachedSegments(request, requestOptions).body(); } /** @@ -195,7 +86,7 @@ public ContactSegments listAttachedSegments( * 2.Opt-in subscription types that the user has opted-in to receiving.

*/ public SubscriptionTypeList listAttachedSubscriptions(ListAttachedSubscriptionsRequest request) { - return listAttachedSubscriptions(request, null); + return this.rawClient.listAttachedSubscriptions(request).body(); } /** @@ -207,47 +98,7 @@ public SubscriptionTypeList listAttachedSubscriptions(ListAttachedSubscriptionsR */ public SubscriptionTypeList listAttachedSubscriptions( ListAttachedSubscriptionsRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("subscriptions") - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SubscriptionTypeList.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.listAttachedSubscriptions(request, requestOptions).body(); } /** @@ -257,7 +108,7 @@ public SubscriptionTypeList listAttachedSubscriptions( *

This will return a subscription type model for the subscription type that was added to the contact.

*/ public SubscriptionType attachSubscription(AttachSubscriptionToContactRequest request) { - return attachSubscription(request, null); + return this.rawClient.attachSubscription(request).body(); } /** @@ -268,61 +119,14 @@ public SubscriptionType attachSubscription(AttachSubscriptionToContactRequest re */ public SubscriptionType attachSubscription( AttachSubscriptionToContactRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("subscriptions") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SubscriptionType.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.attachSubscription(request, requestOptions).body(); } /** * You can remove a specific subscription from a contact. This will return a subscription type model for the subscription type that was removed from the contact. */ public SubscriptionType detachSubscription(DetachSubscriptionFromContactRequest request) { - return detachSubscription(request, null); + return this.rawClient.detachSubscription(request).body(); } /** @@ -330,311 +134,77 @@ public SubscriptionType detachSubscription(DetachSubscriptionFromContactRequest */ public SubscriptionType detachSubscription( DetachSubscriptionFromContactRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("subscriptions") - .addPathSegment(request.getSubscriptionId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SubscriptionType.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.detachSubscription(request, requestOptions).body(); } /** * You can fetch a list of all tags that are attached to a specific contact. */ public TagList listAttachedTags(ListTagsAttachedToContactRequest request) { - return listAttachedTags(request, null); + return this.rawClient.listAttachedTags(request).body(); } /** * You can fetch a list of all tags that are attached to a specific contact. */ public TagList listAttachedTags(ListTagsAttachedToContactRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("tags") - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TagList.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.listAttachedTags(request, requestOptions).body(); } /** * You can fetch the details of a single contact. */ public Contact find(FindContactRequest request) { - return find(request, null); + return this.rawClient.find(request).body(); } /** * You can fetch the details of a single contact. */ public Contact find(FindContactRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Contact.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.find(request, requestOptions).body(); } /** * You can update an existing contact (ie. user or lead). */ public Contact update(UpdateContactRequest request) { - return update(request, null); + return this.rawClient.update(request).body(); } /** * You can update an existing contact (ie. user or lead). */ public Contact update(UpdateContactRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PUT", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Contact.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.update(request, requestOptions).body(); } /** * You can delete a single contact. */ public ContactDeleted delete(DeleteContactRequest request) { - return delete(request, null); + return this.rawClient.delete(request).body(); } /** * You can delete a single contact. */ public ContactDeleted delete(DeleteContactRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ContactDeleted.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.delete(request, requestOptions).body(); } /** * You can merge a contact with a role of lead into a contact with a role of user. */ public Contact mergeLeadInUser(MergeContactsRequest request) { - return mergeLeadInUser(request, null); + return this.rawClient.mergeLeadInUser(request).body(); } /** * You can merge a contact with a role of lead into a contact with a role of user. */ public Contact mergeLeadInUser(MergeContactsRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts/merge") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Contact.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.mergeLeadInUser(request, requestOptions).body(); } /** @@ -726,7 +296,7 @@ public Contact mergeLeadInUser(MergeContactsRequest request, RequestOptions requ * | $ | String | Ends With |

*/ public SyncPagingIterable search(SearchRequest request) { - return search(request, null); + return this.rawClient.search(request).body(); } /** @@ -818,65 +388,7 @@ public SyncPagingIterable search(SearchRequest request) { * | $ | String | Ends With |

*/ public SyncPagingIterable search(SearchRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts/search") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - ContactList parsedResponse = - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ContactList.class); - Optional startingAfter = parsedResponse - .getPages() - .flatMap(CursorPages::getNext) - .flatMap(StartingAfterPaging::getStartingAfter); - Optional pagination = request.getPagination() - .map(pagination_ -> StartingAfterPaging.builder() - .from(pagination_) - .startingAfter(startingAfter) - .build()); - SearchRequest nextRequest = SearchRequest.builder() - .from(request) - .pagination(pagination) - .build(); - List result = parsedResponse.getData(); - return new SyncPagingIterable( - startingAfter.isPresent(), result, () -> search(nextRequest, requestOptions)); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.search(request, requestOptions).body(); } /** @@ -887,7 +399,7 @@ public SyncPagingIterable search(SearchRequest request, RequestOptions * {% /admonition %} */ public SyncPagingIterable list() { - return list(ListContactsRequest.builder().build()); + return this.rawClient.list().body(); } /** @@ -898,7 +410,7 @@ public SyncPagingIterable list() { * {% /admonition %} */ public SyncPagingIterable list(ListContactsRequest request) { - return list(request, null); + return this.rawClient.list(request).body(); } /** @@ -909,204 +421,48 @@ public SyncPagingIterable list(ListContactsRequest request) { * {% /admonition %} */ public SyncPagingIterable list(ListContactsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts"); - if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getPerPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "per_page", request.getPerPage().get().toString(), false); - } - if (request.getStartingAfter().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "starting_after", request.getStartingAfter().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - ContactList parsedResponse = - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ContactList.class); - Optional startingAfter = parsedResponse - .getPages() - .flatMap(CursorPages::getNext) - .flatMap(StartingAfterPaging::getStartingAfter); - ListContactsRequest nextRequest = ListContactsRequest.builder() - .from(request) - .startingAfter(startingAfter) - .build(); - List result = parsedResponse.getData(); - return new SyncPagingIterable( - startingAfter.isPresent(), result, () -> list(nextRequest, requestOptions)); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.list(request, requestOptions).body(); } /** * You can create a new contact (ie. user or lead). */ public Contact create(CreateContactRequest request) { - return create(request, null); + return this.rawClient.create(request).body(); } /** * You can create a new contact (ie. user or lead). */ public Contact create(CreateContactRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Contact.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.create(request, requestOptions).body(); } /** * You can archive a single contact. */ public ContactArchived archive(ArchiveContactRequest request) { - return archive(request, null); + return this.rawClient.archive(request).body(); } /** * You can archive a single contact. */ public ContactArchived archive(ArchiveContactRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("archive") - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("POST", RequestBody.create("", null)) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ContactArchived.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.archive(request, requestOptions).body(); } /** * You can unarchive a single contact. */ public ContactUnarchived unarchive(UnarchiveContactRequest request) { - return unarchive(request, null); + return this.rawClient.unarchive(request).body(); } /** * You can unarchive a single contact. */ public ContactUnarchived unarchive(UnarchiveContactRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("unarchive") - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("POST", RequestBody.create("", null)) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ContactUnarchived.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.unarchive(request, requestOptions).body(); } } diff --git a/src/main/java/com/intercom/api/resources/contacts/RawContactsClient.java b/src/main/java/com/intercom/api/resources/contacts/RawContactsClient.java new file mode 100644 index 0000000..e9000a9 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/contacts/RawContactsClient.java @@ -0,0 +1,1169 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.contacts; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.QueryStringMapper; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.core.pagination.SyncPagingIterable; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.companies.types.Company; +import com.intercom.api.resources.contacts.requests.ArchiveContactRequest; +import com.intercom.api.resources.contacts.requests.AttachSubscriptionToContactRequest; +import com.intercom.api.resources.contacts.requests.DeleteContactRequest; +import com.intercom.api.resources.contacts.requests.DetachSubscriptionFromContactRequest; +import com.intercom.api.resources.contacts.requests.FindContactRequest; +import com.intercom.api.resources.contacts.requests.ListAttachedCompaniesRequest; +import com.intercom.api.resources.contacts.requests.ListAttachedSubscriptionsRequest; +import com.intercom.api.resources.contacts.requests.ListContactsRequest; +import com.intercom.api.resources.contacts.requests.ListSegmentsAttachedToContactRequest; +import com.intercom.api.resources.contacts.requests.ListTagsAttachedToContactRequest; +import com.intercom.api.resources.contacts.requests.MergeContactsRequest; +import com.intercom.api.resources.contacts.requests.UnarchiveContactRequest; +import com.intercom.api.resources.contacts.requests.UpdateContactRequest; +import com.intercom.api.resources.contacts.types.Contact; +import com.intercom.api.resources.subscriptiontypes.types.SubscriptionType; +import com.intercom.api.types.ContactArchived; +import com.intercom.api.types.ContactAttachedCompanies; +import com.intercom.api.types.ContactDeleted; +import com.intercom.api.types.ContactList; +import com.intercom.api.types.ContactSegments; +import com.intercom.api.types.ContactUnarchived; +import com.intercom.api.types.CreateContactRequest; +import com.intercom.api.types.CursorPages; +import com.intercom.api.types.Error; +import com.intercom.api.types.SearchRequest; +import com.intercom.api.types.StartingAfterPaging; +import com.intercom.api.types.SubscriptionTypeList; +import com.intercom.api.types.TagList; +import java.io.IOException; +import java.util.List; +import java.util.Optional; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawContactsClient { + protected final ClientOptions clientOptions; + + public RawContactsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can fetch a list of companies that are associated to a contact. + */ + public IntercomHttpResponse> listAttachedCompanies( + ListAttachedCompaniesRequest request) { + return listAttachedCompanies(request, null); + } + + /** + * You can fetch a list of companies that are associated to a contact. + */ + public IntercomHttpResponse> listAttachedCompanies( + ListAttachedCompaniesRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("companies"); + if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "page", request.getPage().get().toString(), false); + } + if (request.getPerPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "per_page", request.getPerPage().get().toString(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + ContactAttachedCompanies parsedResponse = + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ContactAttachedCompanies.class); + int newPageNumber = request.getPage().map(page -> page + 1).orElse(1); + ListAttachedCompaniesRequest nextRequest = ListAttachedCompaniesRequest.builder() + .from(request) + .page(newPageNumber) + .build(); + List result = parsedResponse.getCompanies(); + return new IntercomHttpResponse<>( + new SyncPagingIterable( + true, result, () -> listAttachedCompanies(nextRequest, requestOptions) + .body()), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can fetch a list of segments that are associated to a contact. + */ + public IntercomHttpResponse listAttachedSegments(ListSegmentsAttachedToContactRequest request) { + return listAttachedSegments(request, null); + } + + /** + * You can fetch a list of segments that are associated to a contact. + */ + public IntercomHttpResponse listAttachedSegments( + ListSegmentsAttachedToContactRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("segments") + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ContactSegments.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can fetch a list of subscription types that are attached to a contact. These can be subscriptions that a user has 'opted-in' to or has 'opted-out' from, depending on the subscription type. + * This will return a list of Subscription Type objects that the contact is associated with. + *

The data property will show a combined list of:

+ *

1.Opt-out subscription types that the user has opted-out from. + * 2.Opt-in subscription types that the user has opted-in to receiving.

+ */ + public IntercomHttpResponse listAttachedSubscriptions( + ListAttachedSubscriptionsRequest request) { + return listAttachedSubscriptions(request, null); + } + + /** + * You can fetch a list of subscription types that are attached to a contact. These can be subscriptions that a user has 'opted-in' to or has 'opted-out' from, depending on the subscription type. + * This will return a list of Subscription Type objects that the contact is associated with. + *

The data property will show a combined list of:

+ *

1.Opt-out subscription types that the user has opted-out from. + * 2.Opt-in subscription types that the user has opted-in to receiving.

+ */ + public IntercomHttpResponse listAttachedSubscriptions( + ListAttachedSubscriptionsRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("subscriptions") + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SubscriptionTypeList.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can add a specific subscription to a contact. In Intercom, we have two different subscription types based on user consent - opt-out and opt-in: + *

1.Attaching a contact to an opt-out subscription type will opt that user out from receiving messages related to that subscription type.

+ *

2.Attaching a contact to an opt-in subscription type will opt that user in to receiving messages related to that subscription type.

+ *

This will return a subscription type model for the subscription type that was added to the contact.

+ */ + public IntercomHttpResponse attachSubscription(AttachSubscriptionToContactRequest request) { + return attachSubscription(request, null); + } + + /** + * You can add a specific subscription to a contact. In Intercom, we have two different subscription types based on user consent - opt-out and opt-in: + *

1.Attaching a contact to an opt-out subscription type will opt that user out from receiving messages related to that subscription type.

+ *

2.Attaching a contact to an opt-in subscription type will opt that user in to receiving messages related to that subscription type.

+ *

This will return a subscription type model for the subscription type that was added to the contact.

+ */ + public IntercomHttpResponse attachSubscription( + AttachSubscriptionToContactRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("subscriptions") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SubscriptionType.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can remove a specific subscription from a contact. This will return a subscription type model for the subscription type that was removed from the contact. + */ + public IntercomHttpResponse detachSubscription(DetachSubscriptionFromContactRequest request) { + return detachSubscription(request, null); + } + + /** + * You can remove a specific subscription from a contact. This will return a subscription type model for the subscription type that was removed from the contact. + */ + public IntercomHttpResponse detachSubscription( + DetachSubscriptionFromContactRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("subscriptions") + .addPathSegment(request.getSubscriptionId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SubscriptionType.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can fetch a list of all tags that are attached to a specific contact. + */ + public IntercomHttpResponse listAttachedTags(ListTagsAttachedToContactRequest request) { + return listAttachedTags(request, null); + } + + /** + * You can fetch a list of all tags that are attached to a specific contact. + */ + public IntercomHttpResponse listAttachedTags( + ListTagsAttachedToContactRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("tags") + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TagList.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can fetch the details of a single contact. + */ + public IntercomHttpResponse find(FindContactRequest request) { + return find(request, null); + } + + /** + * You can fetch the details of a single contact. + */ + public IntercomHttpResponse find(FindContactRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Contact.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can update an existing contact (ie. user or lead). + */ + public IntercomHttpResponse update(UpdateContactRequest request) { + return update(request, null); + } + + /** + * You can update an existing contact (ie. user or lead). + */ + public IntercomHttpResponse update(UpdateContactRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Contact.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can delete a single contact. + */ + public IntercomHttpResponse delete(DeleteContactRequest request) { + return delete(request, null); + } + + /** + * You can delete a single contact. + */ + public IntercomHttpResponse delete(DeleteContactRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ContactDeleted.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can merge a contact with a role of lead into a contact with a role of user. + */ + public IntercomHttpResponse mergeLeadInUser(MergeContactsRequest request) { + return mergeLeadInUser(request, null); + } + + /** + * You can merge a contact with a role of lead into a contact with a role of user. + */ + public IntercomHttpResponse mergeLeadInUser(MergeContactsRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts/merge") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Contact.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can search for multiple contacts by the value of their attributes in order to fetch exactly who you want. + *

To search for contacts, you need to send a POST request to https://api.intercom.io/contacts/search.

+ *

This will accept a query object in the body which will define your filters in order to search for contacts.

+ *

{% admonition type="warning" name="Optimizing search queries" %} + * Search queries can be complex, so optimizing them can help the performance of your search. + * Use the AND and OR operators to combine multiple filters to get the exact results you need and utilize + * pagination to limit the number of results returned. The default is 50 results per page. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %}

+ *

Contact Creation Delay

+ *

If a contact has recently been created, there is a possibility that it will not yet be available when searching. This means that it may not appear in the response. This delay can take a few minutes. If you need to be instantly notified it is recommended to use webhooks and iterate to see if they match your search filters.

+ *

Nesting & Limitations

+ *

You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4). + * There are some limitations to the amount of multiple's there can be:

+ *
    + *
  • There's a limit of max 2 nested filters
  • + *
  • There's a limit of max 15 filters for each AND or OR group
  • + *
+ *

Searching for Timestamp Fields

+ *

All timestamp fields (created_at, updated_at etc.) are indexed as Dates for Contact Search queries; Datetime queries are not currently supported. This means you can only query for timestamp fields by day - not hour, minute or second. + * For example, if you search for all Contacts with a created_at value greater (>) than 1577869200 (the UNIX timestamp for January 1st, 2020 9:00 AM), that will be interpreted as 1577836800 (January 1st, 2020 12:00 AM). The search results will then include Contacts created from January 2nd, 2020 12:00 AM onwards. + * If you'd like to get contacts created on January 1st, 2020 you should search with a created_at value equal (=) to 1577836800 (January 1st, 2020 12:00 AM). + * This behaviour applies only to timestamps used in search queries. The search results will still contain the full UNIX timestamp and be sorted accordingly.

+ *

Accepted Fields

+ *

Most key listed as part of the Contacts Model are searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as created_at accepts a date, the value cannot be a string such as "foorbar").

+ *

| Field | Type | + * | ---------------------------------- | ------------------------------ | + * | id | String | + * | role | String<br>Accepts user or lead | + * | name | String | + * | avatar | String | + * | owner_id | Integer | + * | email | String | + * | email_domain | String | + * | phone | String | + * | external_id | String | + * | created_at | Date (UNIX Timestamp) | + * | signed_up_at | Date (UNIX Timestamp) | + * | updated_at | Date (UNIX Timestamp) | + * | last_seen_at | Date (UNIX Timestamp) | + * | last_contacted_at | Date (UNIX Timestamp) | + * | last_replied_at | Date (UNIX Timestamp) | + * | last_email_opened_at | Date (UNIX Timestamp) | + * | last_email_clicked_at | Date (UNIX Timestamp) | + * | language_override | String | + * | browser | String | + * | browser_language | String | + * | os | String | + * | location.country | String | + * | location.region | String | + * | location.city | String | + * | unsubscribed_from_emails | Boolean | + * | marked_email_as_spam | Boolean | + * | has_hard_bounced | Boolean | + * | ios_last_seen_at | Date (UNIX Timestamp) | + * | ios_app_version | String | + * | ios_device | String | + * | ios_app_device | String | + * | ios_os_version | String | + * | ios_app_name | String | + * | ios_sdk_version | String | + * | android_last_seen_at | Date (UNIX Timestamp) | + * | android_app_version | String | + * | android_device | String | + * | android_app_name | String | + * | andoid_sdk_version | String | + * | segment_id | String | + * | tag_id | String | + * | custom_attributes.{attribute_name} | String |

+ *

Accepted Operators

+ *

{% admonition type="warning" name="Searching based on created_at" %} + * You cannot use the <= or >= operators to search by created_at. + * {% /admonition %}

+ *

The table below shows the operators you can use to define how you want to search for the value. The operator should be put in as a string ("="). The operator has to be compatible with the field's type (eg. you cannot search with > for a given string value as it's only compatible for integer's and dates).

+ *

| Operator | Valid Types | Description | + * | :------- | :------------------------------- | :--------------------------------------------------------------- | + * | = | All | Equals | + * | != | All | Doesn't Equal | + * | IN | All | In<br>Shortcut for OR queries<br>Values must be in Array | + * | NIN | All | Not In<br>Shortcut for OR ! queries<br>Values must be in Array | + * | > | Integer<br>Date (UNIX Timestamp) | Greater than | + * | < | Integer<br>Date (UNIX Timestamp) | Lower than | + * | ~ | String | Contains | + * | !~ | String | Doesn't Contain | + * | ^ | String | Starts With | + * | $ | String | Ends With |

+ */ + public IntercomHttpResponse> search(SearchRequest request) { + return search(request, null); + } + + /** + * You can search for multiple contacts by the value of their attributes in order to fetch exactly who you want. + *

To search for contacts, you need to send a POST request to https://api.intercom.io/contacts/search.

+ *

This will accept a query object in the body which will define your filters in order to search for contacts.

+ *

{% admonition type="warning" name="Optimizing search queries" %} + * Search queries can be complex, so optimizing them can help the performance of your search. + * Use the AND and OR operators to combine multiple filters to get the exact results you need and utilize + * pagination to limit the number of results returned. The default is 50 results per page. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %}

+ *

Contact Creation Delay

+ *

If a contact has recently been created, there is a possibility that it will not yet be available when searching. This means that it may not appear in the response. This delay can take a few minutes. If you need to be instantly notified it is recommended to use webhooks and iterate to see if they match your search filters.

+ *

Nesting & Limitations

+ *

You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4). + * There are some limitations to the amount of multiple's there can be:

+ *
    + *
  • There's a limit of max 2 nested filters
  • + *
  • There's a limit of max 15 filters for each AND or OR group
  • + *
+ *

Searching for Timestamp Fields

+ *

All timestamp fields (created_at, updated_at etc.) are indexed as Dates for Contact Search queries; Datetime queries are not currently supported. This means you can only query for timestamp fields by day - not hour, minute or second. + * For example, if you search for all Contacts with a created_at value greater (>) than 1577869200 (the UNIX timestamp for January 1st, 2020 9:00 AM), that will be interpreted as 1577836800 (January 1st, 2020 12:00 AM). The search results will then include Contacts created from January 2nd, 2020 12:00 AM onwards. + * If you'd like to get contacts created on January 1st, 2020 you should search with a created_at value equal (=) to 1577836800 (January 1st, 2020 12:00 AM). + * This behaviour applies only to timestamps used in search queries. The search results will still contain the full UNIX timestamp and be sorted accordingly.

+ *

Accepted Fields

+ *

Most key listed as part of the Contacts Model are searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as created_at accepts a date, the value cannot be a string such as "foorbar").

+ *

| Field | Type | + * | ---------------------------------- | ------------------------------ | + * | id | String | + * | role | String<br>Accepts user or lead | + * | name | String | + * | avatar | String | + * | owner_id | Integer | + * | email | String | + * | email_domain | String | + * | phone | String | + * | external_id | String | + * | created_at | Date (UNIX Timestamp) | + * | signed_up_at | Date (UNIX Timestamp) | + * | updated_at | Date (UNIX Timestamp) | + * | last_seen_at | Date (UNIX Timestamp) | + * | last_contacted_at | Date (UNIX Timestamp) | + * | last_replied_at | Date (UNIX Timestamp) | + * | last_email_opened_at | Date (UNIX Timestamp) | + * | last_email_clicked_at | Date (UNIX Timestamp) | + * | language_override | String | + * | browser | String | + * | browser_language | String | + * | os | String | + * | location.country | String | + * | location.region | String | + * | location.city | String | + * | unsubscribed_from_emails | Boolean | + * | marked_email_as_spam | Boolean | + * | has_hard_bounced | Boolean | + * | ios_last_seen_at | Date (UNIX Timestamp) | + * | ios_app_version | String | + * | ios_device | String | + * | ios_app_device | String | + * | ios_os_version | String | + * | ios_app_name | String | + * | ios_sdk_version | String | + * | android_last_seen_at | Date (UNIX Timestamp) | + * | android_app_version | String | + * | android_device | String | + * | android_app_name | String | + * | andoid_sdk_version | String | + * | segment_id | String | + * | tag_id | String | + * | custom_attributes.{attribute_name} | String |

+ *

Accepted Operators

+ *

{% admonition type="warning" name="Searching based on created_at" %} + * You cannot use the <= or >= operators to search by created_at. + * {% /admonition %}

+ *

The table below shows the operators you can use to define how you want to search for the value. The operator should be put in as a string ("="). The operator has to be compatible with the field's type (eg. you cannot search with > for a given string value as it's only compatible for integer's and dates).

+ *

| Operator | Valid Types | Description | + * | :------- | :------------------------------- | :--------------------------------------------------------------- | + * | = | All | Equals | + * | != | All | Doesn't Equal | + * | IN | All | In<br>Shortcut for OR queries<br>Values must be in Array | + * | NIN | All | Not In<br>Shortcut for OR ! queries<br>Values must be in Array | + * | > | Integer<br>Date (UNIX Timestamp) | Greater than | + * | < | Integer<br>Date (UNIX Timestamp) | Lower than | + * | ~ | String | Contains | + * | !~ | String | Doesn't Contain | + * | ^ | String | Starts With | + * | $ | String | Ends With |

+ */ + public IntercomHttpResponse> search( + SearchRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts/search") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + ContactList parsedResponse = + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ContactList.class); + Optional startingAfter = parsedResponse + .getPages() + .flatMap(CursorPages::getNext) + .flatMap(StartingAfterPaging::getStartingAfter); + Optional pagination = request.getPagination() + .map(pagination_ -> StartingAfterPaging.builder() + .from(pagination_) + .startingAfter(startingAfter) + .build()); + SearchRequest nextRequest = SearchRequest.builder() + .from(request) + .pagination(pagination) + .build(); + List result = parsedResponse.getData(); + return new IntercomHttpResponse<>( + new SyncPagingIterable( + startingAfter.isPresent(), result, () -> search(nextRequest, requestOptions) + .body()), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can fetch a list of all contacts (ie. users or leads) in your workspace. + * {% admonition type="warning" name="Pagination" %} + * You can use pagination to limit the number of results returned. The default is 50 results per page. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %} + */ + public IntercomHttpResponse> list() { + return list(ListContactsRequest.builder().build()); + } + + /** + * You can fetch a list of all contacts (ie. users or leads) in your workspace. + * {% admonition type="warning" name="Pagination" %} + * You can use pagination to limit the number of results returned. The default is 50 results per page. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %} + */ + public IntercomHttpResponse> list(ListContactsRequest request) { + return list(request, null); + } + + /** + * You can fetch a list of all contacts (ie. users or leads) in your workspace. + * {% admonition type="warning" name="Pagination" %} + * You can use pagination to limit the number of results returned. The default is 50 results per page. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %} + */ + public IntercomHttpResponse> list( + ListContactsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts"); + if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "page", request.getPage().get().toString(), false); + } + if (request.getPerPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "per_page", request.getPerPage().get().toString(), false); + } + if (request.getStartingAfter().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "starting_after", request.getStartingAfter().get(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + ContactList parsedResponse = + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ContactList.class); + Optional startingAfter = parsedResponse + .getPages() + .flatMap(CursorPages::getNext) + .flatMap(StartingAfterPaging::getStartingAfter); + ListContactsRequest nextRequest = ListContactsRequest.builder() + .from(request) + .startingAfter(startingAfter) + .build(); + List result = parsedResponse.getData(); + return new IntercomHttpResponse<>( + new SyncPagingIterable( + startingAfter.isPresent(), result, () -> list(nextRequest, requestOptions) + .body()), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can create a new contact (ie. user or lead). + */ + public IntercomHttpResponse create(CreateContactRequest request) { + return create(request, null); + } + + /** + * You can create a new contact (ie. user or lead). + */ + public IntercomHttpResponse create(CreateContactRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Contact.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can archive a single contact. + */ + public IntercomHttpResponse archive(ArchiveContactRequest request) { + return archive(request, null); + } + + /** + * You can archive a single contact. + */ + public IntercomHttpResponse archive(ArchiveContactRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("archive") + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("POST", RequestBody.create("", null)) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ContactArchived.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can unarchive a single contact. + */ + public IntercomHttpResponse unarchive(UnarchiveContactRequest request) { + return unarchive(request, null); + } + + /** + * You can unarchive a single contact. + */ + public IntercomHttpResponse unarchive( + UnarchiveContactRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("unarchive") + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("POST", RequestBody.create("", null)) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ContactUnarchived.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/intercom/api/resources/conversations/AsyncConversationsClient.java b/src/main/java/com/intercom/api/resources/conversations/AsyncConversationsClient.java index 17a5f98..034671b 100644 --- a/src/main/java/com/intercom/api/resources/conversations/AsyncConversationsClient.java +++ b/src/main/java/com/intercom/api/resources/conversations/AsyncConversationsClient.java @@ -3,20 +3,9 @@ */ package com.intercom.api.resources.conversations; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; -import com.intercom.api.core.QueryStringMapper; import com.intercom.api.core.RequestOptions; import com.intercom.api.core.pagination.SyncPagingIterable; -import com.intercom.api.errors.BadRequestError; -import com.intercom.api.errors.ForbiddenError; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; -import com.intercom.api.errors.UnprocessableEntityError; import com.intercom.api.resources.conversations.requests.AttachContactToConversationRequest; import com.intercom.api.resources.conversations.requests.AutoAssignConversationRequest; import com.intercom.api.resources.conversations.requests.ConvertConversationToTicketRequest; @@ -30,35 +19,25 @@ import com.intercom.api.resources.conversations.types.Conversation; import com.intercom.api.resources.messages.types.Message; import com.intercom.api.resources.tickets.types.Ticket; -import com.intercom.api.types.CursorPages; -import com.intercom.api.types.Error; -import com.intercom.api.types.PaginatedConversationResponse; import com.intercom.api.types.RedactConversationRequest; import com.intercom.api.types.SearchRequest; -import com.intercom.api.types.StartingAfterPaging; -import java.io.IOException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; public class AsyncConversationsClient { protected final ClientOptions clientOptions; + private final AsyncRawConversationsClient rawClient; + public AsyncConversationsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new AsyncRawConversationsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawConversationsClient withRawResponse() { + return this.rawClient; } /** @@ -70,7 +49,7 @@ public AsyncConversationsClient(ClientOptions clientOptions) { * {% /admonition %}

*/ public CompletableFuture> list() { - return list(ListConversationsRequest.builder().build()); + return this.rawClient.list().thenApply(response -> response.body()); } /** @@ -82,7 +61,7 @@ public CompletableFuture> list() { * {% /admonition %}

*/ public CompletableFuture> list(ListConversationsRequest request) { - return list(request, null); + return this.rawClient.list(request).thenApply(response -> response.body()); } /** @@ -95,85 +74,7 @@ public CompletableFuture> list(ListConversation */ public CompletableFuture> list( ListConversationsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations"); - if (request.getPerPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "per_page", request.getPerPage().get().toString(), false); - } - if (request.getStartingAfter().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "starting_after", request.getStartingAfter().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - PaginatedConversationResponse parsedResponse = ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), PaginatedConversationResponse.class); - Optional startingAfter = parsedResponse - .getPages() - .flatMap(CursorPages::getNext) - .flatMap(StartingAfterPaging::getStartingAfter); - ListConversationsRequest nextRequest = ListConversationsRequest.builder() - .from(request) - .startingAfter(startingAfter) - .build(); - List result = parsedResponse.getConversations(); - future.complete(new SyncPagingIterable(startingAfter.isPresent(), result, () -> { - try { - return list(nextRequest, requestOptions).get(); - } catch (InterruptedException | ExecutionException e) { - throw new RuntimeException(e); - } - })); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.list(request, requestOptions).thenApply(response -> response.body()); } /** @@ -186,7 +87,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { *

This will return the Message model that has been created.

*/ public CompletableFuture create(CreateConversationRequest request) { - return create(request, null); + return this.rawClient.create(request).thenApply(response -> response.body()); } /** @@ -199,72 +100,7 @@ public CompletableFuture create(CreateConversationRequest request) { *

This will return the Message model that has been created.

*/ public CompletableFuture create(CreateConversationRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Message.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.create(request, requestOptions).thenApply(response -> response.body()); } /** @@ -276,7 +112,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { *

For AI agent conversation metadata, please note that you need to have the agent enabled in your workspace, which is a paid feature.

*/ public CompletableFuture find(FindConversationRequest request) { - return find(request, null); + return this.rawClient.find(request).thenApply(response -> response.body()); } /** @@ -288,69 +124,7 @@ public CompletableFuture find(FindConversationRequest request) { *

For AI agent conversation metadata, please note that you need to have the agent enabled in your workspace, which is a paid feature.

*/ public CompletableFuture find(FindConversationRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations") - .addPathSegment(request.getConversationId()); - if (request.getDisplayAs().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "display_as", request.getDisplayAs().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.find(request, requestOptions).thenApply(response -> response.body()); } /** @@ -360,7 +134,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { * {% /admonition %}

*/ public CompletableFuture update(UpdateConversationRequest request) { - return update(request, null); + return this.rawClient.update(request).thenApply(response -> response.body()); } /** @@ -370,83 +144,7 @@ public CompletableFuture update(UpdateConversationRequest request) * {% /admonition %}

*/ public CompletableFuture update(UpdateConversationRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations") - .addPathSegment(request.getConversationId()); - if (request.getDisplayAs().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "display_as", request.getDisplayAs().get(), false); - } - Map properties = new HashMap<>(); - if (request.getRead().isPresent()) { - properties.put("read", request.getRead()); - } - if (request.getCustomAttributes().isPresent()) { - properties.put("custom_attributes", request.getCustomAttributes()); - } - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(properties), MediaTypes.APPLICATION_JSON); - } catch (Exception e) { - throw new RuntimeException(e); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("PUT", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.update(request, requestOptions).thenApply(response -> response.body()); } /** @@ -543,7 +241,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { * | $ | String | Ends With |

*/ public CompletableFuture> search(SearchRequest request) { - return search(request, null); + return this.rawClient.search(request).thenApply(response -> response.body()); } /** @@ -641,157 +339,21 @@ public CompletableFuture> search(SearchRequest */ public CompletableFuture> search( SearchRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations/search") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - PaginatedConversationResponse parsedResponse = ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), PaginatedConversationResponse.class); - Optional startingAfter = parsedResponse - .getPages() - .flatMap(CursorPages::getNext) - .flatMap(StartingAfterPaging::getStartingAfter); - Optional pagination = request.getPagination() - .map(pagination_ -> StartingAfterPaging.builder() - .from(pagination_) - .startingAfter(startingAfter) - .build()); - SearchRequest nextRequest = SearchRequest.builder() - .from(request) - .pagination(pagination) - .build(); - List result = parsedResponse.getConversations(); - future.complete(new SyncPagingIterable(startingAfter.isPresent(), result, () -> { - try { - return search(nextRequest, requestOptions).get(); - } catch (InterruptedException | ExecutionException e) { - throw new RuntimeException(e); - } - })); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.search(request, requestOptions).thenApply(response -> response.body()); } /** * You can reply to a conversation with a message from an admin or on behalf of a contact, or with a note for admins. */ public CompletableFuture reply(ReplyToConversationRequest request) { - return reply(request, null); + return this.rawClient.reply(request).thenApply(response -> response.body()); } /** * You can reply to a conversation with a message from an admin or on behalf of a contact, or with a note for admins. */ public CompletableFuture reply(ReplyToConversationRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations") - .addPathSegment(request.getConversationId()) - .addPathSegments("reply") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request.getBody()), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.reply(request, requestOptions).thenApply(response -> response.body()); } /** @@ -804,7 +366,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { * */ public CompletableFuture manage(ManageConversationPartsRequest request) { - return manage(request, null); + return this.rawClient.manage(request).thenApply(response -> response.body()); } /** @@ -818,74 +380,7 @@ public CompletableFuture manage(ManageConversationPartsRequest req */ public CompletableFuture manage( ManageConversationPartsRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations") - .addPathSegment(request.getConversationId()) - .addPathSegments("parts") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request.getBody()), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.manage(request, requestOptions).thenApply(response -> response.body()); } /** @@ -898,7 +393,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { * {% /admonition %} */ public CompletableFuture runAssignmentRules(AutoAssignConversationRequest request) { - return runAssignmentRules(request, null); + return this.rawClient.runAssignmentRules(request).thenApply(response -> response.body()); } /** @@ -912,67 +407,7 @@ public CompletableFuture runAssignmentRules(AutoAssignConversation */ public CompletableFuture runAssignmentRules( AutoAssignConversationRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations") - .addPathSegment(request.getConversationId()) - .addPathSegments("run_assignment_rules") - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("POST", RequestBody.create("", null)) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.runAssignmentRules(request, requestOptions).thenApply(response -> response.body()); } /** @@ -982,7 +417,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { * {% /admonition %}

*/ public CompletableFuture attachContactAsAdmin(AttachContactToConversationRequest request) { - return attachContactAsAdmin(request, null); + return this.rawClient.attachContactAsAdmin(request).thenApply(response -> response.body()); } /** @@ -993,74 +428,7 @@ public CompletableFuture attachContactAsAdmin(AttachContactToConve */ public CompletableFuture attachContactAsAdmin( AttachContactToConversationRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations") - .addPathSegment(request.getConversationId()) - .addPathSegments("customers") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.attachContactAsAdmin(request, requestOptions).thenApply(response -> response.body()); } /** @@ -1070,7 +438,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { * {% /admonition %}

*/ public CompletableFuture detachContactAsAdmin(DetachContactFromConversationRequest request) { - return detachContactAsAdmin(request, null); + return this.rawClient.detachContactAsAdmin(request).thenApply(response -> response.body()); } /** @@ -1081,79 +449,7 @@ public CompletableFuture detachContactAsAdmin(DetachContactFromCon */ public CompletableFuture detachContactAsAdmin( DetachContactFromConversationRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations") - .addPathSegment(request.getConversationId()) - .addPathSegments("customers") - .addPathSegment(request.getContactId()) - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.detachContactAsAdmin(request, requestOptions).thenApply(response -> response.body()); } /** @@ -1163,7 +459,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { * {% /admonition %}

*/ public CompletableFuture redactConversationPart(RedactConversationRequest request) { - return redactConversationPart(request, null); + return this.rawClient.redactConversationPart(request).thenApply(response -> response.body()); } /** @@ -1174,75 +470,14 @@ public CompletableFuture redactConversationPart(RedactConversation */ public CompletableFuture redactConversationPart( RedactConversationRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations/redact") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.redactConversationPart(request, requestOptions).thenApply(response -> response.body()); } /** * You can convert a conversation to a ticket. */ public CompletableFuture convertToTicket(ConvertConversationToTicketRequest request) { - return convertToTicket(request, null); + return this.rawClient.convertToTicket(request).thenApply(response -> response.body()); } /** @@ -1250,64 +485,6 @@ public CompletableFuture convertToTicket(ConvertConversationToTicketRequ */ public CompletableFuture convertToTicket( ConvertConversationToTicketRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations") - .addPathSegment(request.getConversationId()) - .addPathSegments("convert") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Ticket.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 400) { - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.convertToTicket(request, requestOptions).thenApply(response -> response.body()); } } diff --git a/src/main/java/com/intercom/api/resources/conversations/AsyncRawConversationsClient.java b/src/main/java/com/intercom/api/resources/conversations/AsyncRawConversationsClient.java new file mode 100644 index 0000000..436f2a3 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/conversations/AsyncRawConversationsClient.java @@ -0,0 +1,1390 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.conversations; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.QueryStringMapper; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.core.pagination.SyncPagingIterable; +import com.intercom.api.errors.BadRequestError; +import com.intercom.api.errors.ForbiddenError; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.errors.UnprocessableEntityError; +import com.intercom.api.resources.conversations.requests.AttachContactToConversationRequest; +import com.intercom.api.resources.conversations.requests.AutoAssignConversationRequest; +import com.intercom.api.resources.conversations.requests.ConvertConversationToTicketRequest; +import com.intercom.api.resources.conversations.requests.CreateConversationRequest; +import com.intercom.api.resources.conversations.requests.DetachContactFromConversationRequest; +import com.intercom.api.resources.conversations.requests.FindConversationRequest; +import com.intercom.api.resources.conversations.requests.ListConversationsRequest; +import com.intercom.api.resources.conversations.requests.ManageConversationPartsRequest; +import com.intercom.api.resources.conversations.requests.ReplyToConversationRequest; +import com.intercom.api.resources.conversations.requests.UpdateConversationRequest; +import com.intercom.api.resources.conversations.types.Conversation; +import com.intercom.api.resources.messages.types.Message; +import com.intercom.api.resources.tickets.types.Ticket; +import com.intercom.api.types.CursorPages; +import com.intercom.api.types.Error; +import com.intercom.api.types.PaginatedConversationResponse; +import com.intercom.api.types.RedactConversationRequest; +import com.intercom.api.types.SearchRequest; +import com.intercom.api.types.StartingAfterPaging; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawConversationsClient { + protected final ClientOptions clientOptions; + + public AsyncRawConversationsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can fetch a list of all conversations. + *

You can optionally request the result page size and the cursor to start after to fetch the result. + * {% admonition type="warning" name="Pagination" %} + * You can use pagination to limit the number of results returned. The default is 20 results per page. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %}

+ */ + public CompletableFuture>> list() { + return list(ListConversationsRequest.builder().build()); + } + + /** + * You can fetch a list of all conversations. + *

You can optionally request the result page size and the cursor to start after to fetch the result. + * {% admonition type="warning" name="Pagination" %} + * You can use pagination to limit the number of results returned. The default is 20 results per page. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %}

+ */ + public CompletableFuture>> list( + ListConversationsRequest request) { + return list(request, null); + } + + /** + * You can fetch a list of all conversations. + *

You can optionally request the result page size and the cursor to start after to fetch the result. + * {% admonition type="warning" name="Pagination" %} + * You can use pagination to limit the number of results returned. The default is 20 results per page. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %}

+ */ + public CompletableFuture>> list( + ListConversationsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations"); + if (request.getPerPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "per_page", request.getPerPage().get().toString(), false); + } + if (request.getStartingAfter().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "starting_after", request.getStartingAfter().get(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture>> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + PaginatedConversationResponse parsedResponse = ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), PaginatedConversationResponse.class); + Optional startingAfter = parsedResponse + .getPages() + .flatMap(CursorPages::getNext) + .flatMap(StartingAfterPaging::getStartingAfter); + ListConversationsRequest nextRequest = ListConversationsRequest.builder() + .from(request) + .startingAfter(startingAfter) + .build(); + List result = parsedResponse.getConversations(); + future.complete(new IntercomHttpResponse<>( + new SyncPagingIterable(startingAfter.isPresent(), result, () -> { + try { + return list(nextRequest, requestOptions) + .get() + .body(); + } catch (InterruptedException | ExecutionException e) { + throw new RuntimeException(e); + } + }), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 403: + future.completeExceptionally(new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can create a conversation that has been initiated by a contact (ie. user or lead). + * The conversation can be an in-app message only. + *

{% admonition type="info" name="Sending for visitors" %} + * You can also send a message from a visitor by specifying their user_id or id value in the from field, along with a type field value of contact. + * This visitor will be automatically converted to a contact with a lead role once the conversation is created. + * {% /admonition %}

+ *

This will return the Message model that has been created.

+ */ + public CompletableFuture> create(CreateConversationRequest request) { + return create(request, null); + } + + /** + * You can create a conversation that has been initiated by a contact (ie. user or lead). + * The conversation can be an in-app message only. + *

{% admonition type="info" name="Sending for visitors" %} + * You can also send a message from a visitor by specifying their user_id or id value in the from field, along with a type field value of contact. + * This visitor will be automatically converted to a contact with a lead role once the conversation is created. + * {% /admonition %}

+ *

This will return the Message model that has been created.

+ */ + public CompletableFuture> create( + CreateConversationRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Message.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 403: + future.completeExceptionally(new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can fetch the details of a single conversation. + *

This will return a single Conversation model with all its conversation parts.

+ *

{% admonition type="warning" name="Hard limit of 500 parts" %} + * The maximum number of conversation parts that can be returned via the API is 500. If you have more than that we will return the 500 most recent conversation parts. + * {% /admonition %}

+ *

For AI agent conversation metadata, please note that you need to have the agent enabled in your workspace, which is a paid feature.

+ */ + public CompletableFuture> find(FindConversationRequest request) { + return find(request, null); + } + + /** + * You can fetch the details of a single conversation. + *

This will return a single Conversation model with all its conversation parts.

+ *

{% admonition type="warning" name="Hard limit of 500 parts" %} + * The maximum number of conversation parts that can be returned via the API is 500. If you have more than that we will return the 500 most recent conversation parts. + * {% /admonition %}

+ *

For AI agent conversation metadata, please note that you need to have the agent enabled in your workspace, which is a paid feature.

+ */ + public CompletableFuture> find( + FindConversationRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations") + .addPathSegment(request.getConversationId()); + if (request.getDisplayAs().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "display_as", request.getDisplayAs().get(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 403: + future.completeExceptionally(new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can update an existing conversation. + *

{% admonition type="info" name="Replying and other actions" %} + * If you want to reply to a coveration or take an action such as assign, unassign, open, close or snooze, take a look at the reply and manage endpoints. + * {% /admonition %}

+ */ + public CompletableFuture> update(UpdateConversationRequest request) { + return update(request, null); + } + + /** + * You can update an existing conversation. + *

{% admonition type="info" name="Replying and other actions" %} + * If you want to reply to a coveration or take an action such as assign, unassign, open, close or snooze, take a look at the reply and manage endpoints. + * {% /admonition %}

+ */ + public CompletableFuture> update( + UpdateConversationRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations") + .addPathSegment(request.getConversationId()); + if (request.getDisplayAs().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "display_as", request.getDisplayAs().get(), false); + } + Map properties = new HashMap<>(); + if (request.getRead().isPresent()) { + properties.put("read", request.getRead()); + } + if (request.getCustomAttributes().isPresent()) { + properties.put("custom_attributes", request.getCustomAttributes()); + } + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(properties), MediaTypes.APPLICATION_JSON); + } catch (Exception e) { + throw new RuntimeException(e); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 403: + future.completeExceptionally(new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can search for multiple conversations by the value of their attributes in order to fetch exactly which ones you want. + *

To search for conversations, you need to send a POST request to https://api.intercom.io/conversations/search.

+ *

This will accept a query object in the body which will define your filters in order to search for conversations. + * {% admonition type="warning" name="Optimizing search queries" %} + * Search queries can be complex, so optimizing them can help the performance of your search. + * Use the AND and OR operators to combine multiple filters to get the exact results you need and utilize + * pagination to limit the number of results returned. The default is 20 results per page and maximum is 150. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %}

+ *

Nesting & Limitations

+ *

You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4). + * There are some limitations to the amount of multiple's there can be:

+ *
    + *
  • There's a limit of max 2 nested filters
  • + *
  • There's a limit of max 15 filters for each AND or OR group
  • + *
+ *

Accepted Fields

+ *

Most keys listed as part of the The conversation model is searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as created_at accepts a date, the value cannot be a string such as "foorbar"). + * The source.body field is unique as the search will not be performed against the entire value, but instead against every element of the value separately. For example, when searching for a conversation with a "I need support" body - the query should contain a = operator with the value "support" for such conversation to be returned. A query with a = operator and a "need support" value will not yield a result.

+ *

| Field | Type | + * | :---------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- | + * | id | String | + * | created_at | Date (UNIX timestamp) | + * | updated_at | Date (UNIX timestamp) | + * | source.type | String<br>Accepted fields are conversation, email, facebook, instagram, phone_call, phone_switch, push, sms, twitter and whatsapp. | + * | source.id | String | + * | source.delivered_as | String | + * | source.subject | String | + * | source.body | String | + * | source.author.id | String | + * | source.author.type | String | + * | source.author.name | String | + * | source.author.email | String | + * | source.url | String | + * | contact_ids | String | + * | teammate_ids | String | + * | admin_assignee_id | String | + * | team_assignee_id | String | + * | channel_initiated | String | + * | open | Boolean | + * | read | Boolean | + * | state | String | + * | waiting_since | Date (UNIX timestamp) | + * | snoozed_until | Date (UNIX timestamp) | + * | tag_ids | String | + * | priority | String | + * | statistics.time_to_assignment | Integer | + * | statistics.time_to_admin_reply | Integer | + * | statistics.time_to_first_close | Integer | + * | statistics.time_to_last_close | Integer | + * | statistics.median_time_to_reply | Integer | + * | statistics.first_contact_reply_at | Date (UNIX timestamp) | + * | statistics.first_assignment_at | Date (UNIX timestamp) | + * | statistics.first_admin_reply_at | Date (UNIX timestamp) | + * | statistics.first_close_at | Date (UNIX timestamp) | + * | statistics.last_assignment_at | Date (UNIX timestamp) | + * | statistics.last_assignment_admin_reply_at | Date (UNIX timestamp) | + * | statistics.last_contact_reply_at | Date (UNIX timestamp) | + * | statistics.last_admin_reply_at | Date (UNIX timestamp) | + * | statistics.last_close_at | Date (UNIX timestamp) | + * | statistics.last_closed_by_id | String | + * | statistics.count_reopens | Integer | + * | statistics.count_assignments | Integer | + * | statistics.count_conversation_parts | Integer | + * | conversation_rating.requested_at | Date (UNIX timestamp) | + * | conversation_rating.replied_at | Date (UNIX timestamp) | + * | conversation_rating.score | Integer | + * | conversation_rating.remark | String | + * | conversation_rating.contact_id | String | + * | conversation_rating.admin_d | String | + * | ai_agent_participated | Boolean | + * | ai_agent.resolution_state | String | + * | ai_agent.last_answer_type | String | + * | ai_agent.rating | Integer | + * | ai_agent.rating_remark | String | + * | ai_agent.source_type | String | + * | ai_agent.source_title | String |

+ *

Accepted Operators

+ *

The table below shows the operators you can use to define how you want to search for the value. The operator should be put in as a string ("="). The operator has to be compatible with the field's type (eg. you cannot search with > for a given string value as it's only compatible for integer's and dates).

+ *

| Operator | Valid Types | Description | + * | :------- | :----------------------------- | :----------------------------------------------------------- | + * | = | All | Equals | + * | != | All | Doesn't Equal | + * | IN | All | In Shortcut for OR queries Values most be in Array | + * | NIN | All | Not In Shortcut for OR ! queries Values must be in Array | + * | > | Integer Date (UNIX Timestamp) | Greater (or equal) than | + * | < | Integer Date (UNIX Timestamp) | Lower (or equal) than | + * | ~ | String | Contains | + * | !~ | String | Doesn't Contain | + * | ^ | String | Starts With | + * | $ | String | Ends With |

+ */ + public CompletableFuture>> search(SearchRequest request) { + return search(request, null); + } + + /** + * You can search for multiple conversations by the value of their attributes in order to fetch exactly which ones you want. + *

To search for conversations, you need to send a POST request to https://api.intercom.io/conversations/search.

+ *

This will accept a query object in the body which will define your filters in order to search for conversations. + * {% admonition type="warning" name="Optimizing search queries" %} + * Search queries can be complex, so optimizing them can help the performance of your search. + * Use the AND and OR operators to combine multiple filters to get the exact results you need and utilize + * pagination to limit the number of results returned. The default is 20 results per page and maximum is 150. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %}

+ *

Nesting & Limitations

+ *

You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4). + * There are some limitations to the amount of multiple's there can be:

+ *
    + *
  • There's a limit of max 2 nested filters
  • + *
  • There's a limit of max 15 filters for each AND or OR group
  • + *
+ *

Accepted Fields

+ *

Most keys listed as part of the The conversation model is searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as created_at accepts a date, the value cannot be a string such as "foorbar"). + * The source.body field is unique as the search will not be performed against the entire value, but instead against every element of the value separately. For example, when searching for a conversation with a "I need support" body - the query should contain a = operator with the value "support" for such conversation to be returned. A query with a = operator and a "need support" value will not yield a result.

+ *

| Field | Type | + * | :---------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- | + * | id | String | + * | created_at | Date (UNIX timestamp) | + * | updated_at | Date (UNIX timestamp) | + * | source.type | String<br>Accepted fields are conversation, email, facebook, instagram, phone_call, phone_switch, push, sms, twitter and whatsapp. | + * | source.id | String | + * | source.delivered_as | String | + * | source.subject | String | + * | source.body | String | + * | source.author.id | String | + * | source.author.type | String | + * | source.author.name | String | + * | source.author.email | String | + * | source.url | String | + * | contact_ids | String | + * | teammate_ids | String | + * | admin_assignee_id | String | + * | team_assignee_id | String | + * | channel_initiated | String | + * | open | Boolean | + * | read | Boolean | + * | state | String | + * | waiting_since | Date (UNIX timestamp) | + * | snoozed_until | Date (UNIX timestamp) | + * | tag_ids | String | + * | priority | String | + * | statistics.time_to_assignment | Integer | + * | statistics.time_to_admin_reply | Integer | + * | statistics.time_to_first_close | Integer | + * | statistics.time_to_last_close | Integer | + * | statistics.median_time_to_reply | Integer | + * | statistics.first_contact_reply_at | Date (UNIX timestamp) | + * | statistics.first_assignment_at | Date (UNIX timestamp) | + * | statistics.first_admin_reply_at | Date (UNIX timestamp) | + * | statistics.first_close_at | Date (UNIX timestamp) | + * | statistics.last_assignment_at | Date (UNIX timestamp) | + * | statistics.last_assignment_admin_reply_at | Date (UNIX timestamp) | + * | statistics.last_contact_reply_at | Date (UNIX timestamp) | + * | statistics.last_admin_reply_at | Date (UNIX timestamp) | + * | statistics.last_close_at | Date (UNIX timestamp) | + * | statistics.last_closed_by_id | String | + * | statistics.count_reopens | Integer | + * | statistics.count_assignments | Integer | + * | statistics.count_conversation_parts | Integer | + * | conversation_rating.requested_at | Date (UNIX timestamp) | + * | conversation_rating.replied_at | Date (UNIX timestamp) | + * | conversation_rating.score | Integer | + * | conversation_rating.remark | String | + * | conversation_rating.contact_id | String | + * | conversation_rating.admin_d | String | + * | ai_agent_participated | Boolean | + * | ai_agent.resolution_state | String | + * | ai_agent.last_answer_type | String | + * | ai_agent.rating | Integer | + * | ai_agent.rating_remark | String | + * | ai_agent.source_type | String | + * | ai_agent.source_title | String |

+ *

Accepted Operators

+ *

The table below shows the operators you can use to define how you want to search for the value. The operator should be put in as a string ("="). The operator has to be compatible with the field's type (eg. you cannot search with > for a given string value as it's only compatible for integer's and dates).

+ *

| Operator | Valid Types | Description | + * | :------- | :----------------------------- | :----------------------------------------------------------- | + * | = | All | Equals | + * | != | All | Doesn't Equal | + * | IN | All | In Shortcut for OR queries Values most be in Array | + * | NIN | All | Not In Shortcut for OR ! queries Values must be in Array | + * | > | Integer Date (UNIX Timestamp) | Greater (or equal) than | + * | < | Integer Date (UNIX Timestamp) | Lower (or equal) than | + * | ~ | String | Contains | + * | !~ | String | Doesn't Contain | + * | ^ | String | Starts With | + * | $ | String | Ends With |

+ */ + public CompletableFuture>> search( + SearchRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations/search") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture>> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + PaginatedConversationResponse parsedResponse = ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), PaginatedConversationResponse.class); + Optional startingAfter = parsedResponse + .getPages() + .flatMap(CursorPages::getNext) + .flatMap(StartingAfterPaging::getStartingAfter); + Optional pagination = request.getPagination() + .map(pagination_ -> StartingAfterPaging.builder() + .from(pagination_) + .startingAfter(startingAfter) + .build()); + SearchRequest nextRequest = SearchRequest.builder() + .from(request) + .pagination(pagination) + .build(); + List result = parsedResponse.getConversations(); + future.complete(new IntercomHttpResponse<>( + new SyncPagingIterable(startingAfter.isPresent(), result, () -> { + try { + return search(nextRequest, requestOptions) + .get() + .body(); + } catch (InterruptedException | ExecutionException e) { + throw new RuntimeException(e); + } + }), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can reply to a conversation with a message from an admin or on behalf of a contact, or with a note for admins. + */ + public CompletableFuture> reply(ReplyToConversationRequest request) { + return reply(request, null); + } + + /** + * You can reply to a conversation with a message from an admin or on behalf of a contact, or with a note for admins. + */ + public CompletableFuture> reply( + ReplyToConversationRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations") + .addPathSegment(request.getConversationId()) + .addPathSegments("reply") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request.getBody()), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 403: + future.completeExceptionally(new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * For managing conversations you can: + *
    + *
  • Close a conversation
  • + *
  • Snooze a conversation to reopen on a future date
  • + *
  • Open a conversation which is snoozed or closed
  • + *
  • Assign a conversation to an admin and/or team.
  • + *
+ */ + public CompletableFuture> manage(ManageConversationPartsRequest request) { + return manage(request, null); + } + + /** + * For managing conversations you can: + *
    + *
  • Close a conversation
  • + *
  • Snooze a conversation to reopen on a future date
  • + *
  • Open a conversation which is snoozed or closed
  • + *
  • Assign a conversation to an admin and/or team.
  • + *
+ */ + public CompletableFuture> manage( + ManageConversationPartsRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations") + .addPathSegment(request.getConversationId()) + .addPathSegments("parts") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request.getBody()), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 403: + future.completeExceptionally(new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * {% admonition type="danger" name="Deprecation of Run Assignment Rules" %} + * Run assignment rules is now deprecated in version 2.12 and future versions and will be permanently removed on December 31, 2026. After this date, any requests made to this endpoint will fail. + * {% /admonition %} + * You can let a conversation be automatically assigned following assignment rules. + * {% admonition type="warning" name="When using workflows" %} + * It is not possible to use this endpoint with Workflows. + * {% /admonition %} + */ + public CompletableFuture> runAssignmentRules( + AutoAssignConversationRequest request) { + return runAssignmentRules(request, null); + } + + /** + * {% admonition type="danger" name="Deprecation of Run Assignment Rules" %} + * Run assignment rules is now deprecated in version 2.12 and future versions and will be permanently removed on December 31, 2026. After this date, any requests made to this endpoint will fail. + * {% /admonition %} + * You can let a conversation be automatically assigned following assignment rules. + * {% admonition type="warning" name="When using workflows" %} + * It is not possible to use this endpoint with Workflows. + * {% /admonition %} + */ + public CompletableFuture> runAssignmentRules( + AutoAssignConversationRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations") + .addPathSegment(request.getConversationId()) + .addPathSegments("run_assignment_rules") + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("POST", RequestBody.create("", null)) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 403: + future.completeExceptionally(new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can add participants who are contacts to a conversation, on behalf of either another contact or an admin. + *

{% admonition type="warning" name="Contacts without an email" %} + * If you add a contact via the email parameter and there is no user/lead found on that workspace with he given email, then we will create a new contact with role set to lead. + * {% /admonition %}

+ */ + public CompletableFuture> attachContactAsAdmin( + AttachContactToConversationRequest request) { + return attachContactAsAdmin(request, null); + } + + /** + * You can add participants who are contacts to a conversation, on behalf of either another contact or an admin. + *

{% admonition type="warning" name="Contacts without an email" %} + * If you add a contact via the email parameter and there is no user/lead found on that workspace with he given email, then we will create a new contact with role set to lead. + * {% /admonition %}

+ */ + public CompletableFuture> attachContactAsAdmin( + AttachContactToConversationRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations") + .addPathSegment(request.getConversationId()) + .addPathSegments("customers") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 403: + future.completeExceptionally(new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can add participants who are contacts to a conversation, on behalf of either another contact or an admin. + *

{% admonition type="warning" name="Contacts without an email" %} + * If you add a contact via the email parameter and there is no user/lead found on that workspace with he given email, then we will create a new contact with role set to lead. + * {% /admonition %}

+ */ + public CompletableFuture> detachContactAsAdmin( + DetachContactFromConversationRequest request) { + return detachContactAsAdmin(request, null); + } + + /** + * You can add participants who are contacts to a conversation, on behalf of either another contact or an admin. + *

{% admonition type="warning" name="Contacts without an email" %} + * If you add a contact via the email parameter and there is no user/lead found on that workspace with he given email, then we will create a new contact with role set to lead. + * {% /admonition %}

+ */ + public CompletableFuture> detachContactAsAdmin( + DetachContactFromConversationRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations") + .addPathSegment(request.getConversationId()) + .addPathSegments("customers") + .addPathSegment(request.getContactId()) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("DELETE", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 403: + future.completeExceptionally(new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 422: + future.completeExceptionally(new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can redact a conversation part or the source message of a conversation (as seen in the source object). + *

{% admonition type="info" name="Redacting parts and messages" %} + * If you are redacting a conversation part, it must have a body. If you are redacting a source message, it must have been created by a contact. We will return a conversation_part_not_redactable error if these criteria are not met. + * {% /admonition %}

+ */ + public CompletableFuture> redactConversationPart( + RedactConversationRequest request) { + return redactConversationPart(request, null); + } + + /** + * You can redact a conversation part or the source message of a conversation (as seen in the source object). + *

{% admonition type="info" name="Redacting parts and messages" %} + * If you are redacting a conversation part, it must have a body. If you are redacting a source message, it must have been created by a contact. We will return a conversation_part_not_redactable error if these criteria are not met. + * {% /admonition %}

+ */ + public CompletableFuture> redactConversationPart( + RedactConversationRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations/redact") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can convert a conversation to a ticket. + */ + public CompletableFuture> convertToTicket(ConvertConversationToTicketRequest request) { + return convertToTicket(request, null); + } + + /** + * You can convert a conversation to a ticket. + */ + public CompletableFuture> convertToTicket( + ConvertConversationToTicketRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations") + .addPathSegment(request.getConversationId()) + .addPathSegments("convert") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Ticket.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 400) { + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/intercom/api/resources/conversations/ConversationsClient.java b/src/main/java/com/intercom/api/resources/conversations/ConversationsClient.java index 080adce..df1b33f 100644 --- a/src/main/java/com/intercom/api/resources/conversations/ConversationsClient.java +++ b/src/main/java/com/intercom/api/resources/conversations/ConversationsClient.java @@ -3,20 +3,9 @@ */ package com.intercom.api.resources.conversations; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; -import com.intercom.api.core.QueryStringMapper; import com.intercom.api.core.RequestOptions; import com.intercom.api.core.pagination.SyncPagingIterable; -import com.intercom.api.errors.BadRequestError; -import com.intercom.api.errors.ForbiddenError; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; -import com.intercom.api.errors.UnprocessableEntityError; import com.intercom.api.resources.conversations.requests.AttachContactToConversationRequest; import com.intercom.api.resources.conversations.requests.AutoAssignConversationRequest; import com.intercom.api.resources.conversations.requests.ConvertConversationToTicketRequest; @@ -30,30 +19,24 @@ import com.intercom.api.resources.conversations.types.Conversation; import com.intercom.api.resources.messages.types.Message; import com.intercom.api.resources.tickets.types.Ticket; -import com.intercom.api.types.CursorPages; -import com.intercom.api.types.Error; -import com.intercom.api.types.PaginatedConversationResponse; import com.intercom.api.types.RedactConversationRequest; import com.intercom.api.types.SearchRequest; -import com.intercom.api.types.StartingAfterPaging; -import java.io.IOException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; public class ConversationsClient { protected final ClientOptions clientOptions; + private final RawConversationsClient rawClient; + public ConversationsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawConversationsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawConversationsClient withRawResponse() { + return this.rawClient; } /** @@ -65,7 +48,7 @@ public ConversationsClient(ClientOptions clientOptions) { * {% /admonition %}

*/ public SyncPagingIterable list() { - return list(ListConversationsRequest.builder().build()); + return this.rawClient.list().body(); } /** @@ -77,7 +60,7 @@ public SyncPagingIterable list() { * {% /admonition %}

*/ public SyncPagingIterable list(ListConversationsRequest request) { - return list(request, null); + return this.rawClient.list(request).body(); } /** @@ -89,64 +72,7 @@ public SyncPagingIterable list(ListConversationsRequest request) { * {% /admonition %}

*/ public SyncPagingIterable list(ListConversationsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations"); - if (request.getPerPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "per_page", request.getPerPage().get().toString(), false); - } - if (request.getStartingAfter().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "starting_after", request.getStartingAfter().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - PaginatedConversationResponse parsedResponse = - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), PaginatedConversationResponse.class); - Optional startingAfter = parsedResponse - .getPages() - .flatMap(CursorPages::getNext) - .flatMap(StartingAfterPaging::getStartingAfter); - ListConversationsRequest nextRequest = ListConversationsRequest.builder() - .from(request) - .startingAfter(startingAfter) - .build(); - List result = parsedResponse.getConversations(); - return new SyncPagingIterable( - startingAfter.isPresent(), result, () -> list(nextRequest, requestOptions)); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 403: - throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.list(request, requestOptions).body(); } /** @@ -159,7 +85,7 @@ public SyncPagingIterable list(ListConversationsRequest request, R *

This will return the Message model that has been created.

*/ public Message create(CreateConversationRequest request) { - return create(request, null); + return this.rawClient.create(request).body(); } /** @@ -172,54 +98,7 @@ public Message create(CreateConversationRequest request) { *

This will return the Message model that has been created.

*/ public Message create(CreateConversationRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Message.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 403: - throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.create(request, requestOptions).body(); } /** @@ -231,7 +110,7 @@ public Message create(CreateConversationRequest request, RequestOptions requestO *

For AI agent conversation metadata, please note that you need to have the agent enabled in your workspace, which is a paid feature.

*/ public Conversation find(FindConversationRequest request) { - return find(request, null); + return this.rawClient.find(request).body(); } /** @@ -243,51 +122,7 @@ public Conversation find(FindConversationRequest request) { *

For AI agent conversation metadata, please note that you need to have the agent enabled in your workspace, which is a paid feature.

*/ public Conversation find(FindConversationRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations") - .addPathSegment(request.getConversationId()); - if (request.getDisplayAs().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "display_as", request.getDisplayAs().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 403: - throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.find(request, requestOptions).body(); } /** @@ -297,7 +132,7 @@ public Conversation find(FindConversationRequest request, RequestOptions request * {% /admonition %}

*/ public Conversation update(UpdateConversationRequest request) { - return update(request, null); + return this.rawClient.update(request).body(); } /** @@ -307,65 +142,7 @@ public Conversation update(UpdateConversationRequest request) { * {% /admonition %}

*/ public Conversation update(UpdateConversationRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations") - .addPathSegment(request.getConversationId()); - if (request.getDisplayAs().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "display_as", request.getDisplayAs().get(), false); - } - Map properties = new HashMap<>(); - if (request.getRead().isPresent()) { - properties.put("read", request.getRead()); - } - if (request.getCustomAttributes().isPresent()) { - properties.put("custom_attributes", request.getCustomAttributes()); - } - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(properties), MediaTypes.APPLICATION_JSON); - } catch (Exception e) { - throw new RuntimeException(e); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("PUT", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 403: - throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.update(request, requestOptions).body(); } /** @@ -462,7 +239,7 @@ public Conversation update(UpdateConversationRequest request, RequestOptions req * | $ | String | Ends With |

*/ public SyncPagingIterable search(SearchRequest request) { - return search(request, null); + return this.rawClient.search(request).body(); } /** @@ -559,121 +336,21 @@ public SyncPagingIterable search(SearchRequest request) { * | $ | String | Ends With |

*/ public SyncPagingIterable search(SearchRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations/search") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - PaginatedConversationResponse parsedResponse = - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), PaginatedConversationResponse.class); - Optional startingAfter = parsedResponse - .getPages() - .flatMap(CursorPages::getNext) - .flatMap(StartingAfterPaging::getStartingAfter); - Optional pagination = request.getPagination() - .map(pagination_ -> StartingAfterPaging.builder() - .from(pagination_) - .startingAfter(startingAfter) - .build()); - SearchRequest nextRequest = SearchRequest.builder() - .from(request) - .pagination(pagination) - .build(); - List result = parsedResponse.getConversations(); - return new SyncPagingIterable( - startingAfter.isPresent(), result, () -> search(nextRequest, requestOptions)); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.search(request, requestOptions).body(); } /** * You can reply to a conversation with a message from an admin or on behalf of a contact, or with a note for admins. */ public Conversation reply(ReplyToConversationRequest request) { - return reply(request, null); + return this.rawClient.reply(request).body(); } /** * You can reply to a conversation with a message from an admin or on behalf of a contact, or with a note for admins. */ public Conversation reply(ReplyToConversationRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations") - .addPathSegment(request.getConversationId()) - .addPathSegments("reply") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request.getBody()), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 403: - throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.reply(request, requestOptions).body(); } /** @@ -686,7 +363,7 @@ public Conversation reply(ReplyToConversationRequest request, RequestOptions req * */ public Conversation manage(ManageConversationPartsRequest request) { - return manage(request, null); + return this.rawClient.manage(request).body(); } /** @@ -699,56 +376,7 @@ public Conversation manage(ManageConversationPartsRequest request) { * */ public Conversation manage(ManageConversationPartsRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations") - .addPathSegment(request.getConversationId()) - .addPathSegments("parts") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request.getBody()), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 403: - throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.manage(request, requestOptions).body(); } /** @@ -761,7 +389,7 @@ public Conversation manage(ManageConversationPartsRequest request, RequestOption * {% /admonition %} */ public Conversation runAssignmentRules(AutoAssignConversationRequest request) { - return runAssignmentRules(request, null); + return this.rawClient.runAssignmentRules(request).body(); } /** @@ -774,49 +402,7 @@ public Conversation runAssignmentRules(AutoAssignConversationRequest request) { * {% /admonition %} */ public Conversation runAssignmentRules(AutoAssignConversationRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations") - .addPathSegment(request.getConversationId()) - .addPathSegments("run_assignment_rules") - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("POST", RequestBody.create("", null)) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 403: - throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.runAssignmentRules(request, requestOptions).body(); } /** @@ -826,7 +412,7 @@ public Conversation runAssignmentRules(AutoAssignConversationRequest request, Re * {% /admonition %}

*/ public Conversation attachContactAsAdmin(AttachContactToConversationRequest request) { - return attachContactAsAdmin(request, null); + return this.rawClient.attachContactAsAdmin(request).body(); } /** @@ -837,56 +423,7 @@ public Conversation attachContactAsAdmin(AttachContactToConversationRequest requ */ public Conversation attachContactAsAdmin( AttachContactToConversationRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations") - .addPathSegment(request.getConversationId()) - .addPathSegments("customers") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 403: - throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.attachContactAsAdmin(request, requestOptions).body(); } /** @@ -896,7 +433,7 @@ public Conversation attachContactAsAdmin( * {% /admonition %}

*/ public Conversation detachContactAsAdmin(DetachContactFromConversationRequest request) { - return detachContactAsAdmin(request, null); + return this.rawClient.detachContactAsAdmin(request).body(); } /** @@ -907,60 +444,7 @@ public Conversation detachContactAsAdmin(DetachContactFromConversationRequest re */ public Conversation detachContactAsAdmin( DetachContactFromConversationRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations") - .addPathSegment(request.getConversationId()) - .addPathSegments("customers") - .addPathSegment(request.getContactId()) - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 403: - throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.detachContactAsAdmin(request, requestOptions).body(); } /** @@ -970,7 +454,7 @@ public Conversation detachContactAsAdmin( * {% /admonition %}

*/ public Conversation redactConversationPart(RedactConversationRequest request) { - return redactConversationPart(request, null); + return this.rawClient.redactConversationPart(request).body(); } /** @@ -980,108 +464,20 @@ public Conversation redactConversationPart(RedactConversationRequest request) { * {% /admonition %}

*/ public Conversation redactConversationPart(RedactConversationRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations/redact") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.redactConversationPart(request, requestOptions).body(); } /** * You can convert a conversation to a ticket. */ public Ticket convertToTicket(ConvertConversationToTicketRequest request) { - return convertToTicket(request, null); + return this.rawClient.convertToTicket(request).body(); } /** * You can convert a conversation to a ticket. */ public Ticket convertToTicket(ConvertConversationToTicketRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations") - .addPathSegment(request.getConversationId()) - .addPathSegments("convert") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Ticket.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 400) { - throw new BadRequestError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.convertToTicket(request, requestOptions).body(); } } diff --git a/src/main/java/com/intercom/api/resources/conversations/RawConversationsClient.java b/src/main/java/com/intercom/api/resources/conversations/RawConversationsClient.java new file mode 100644 index 0000000..5016dba --- /dev/null +++ b/src/main/java/com/intercom/api/resources/conversations/RawConversationsClient.java @@ -0,0 +1,1141 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.conversations; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.QueryStringMapper; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.core.pagination.SyncPagingIterable; +import com.intercom.api.errors.BadRequestError; +import com.intercom.api.errors.ForbiddenError; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.errors.UnprocessableEntityError; +import com.intercom.api.resources.conversations.requests.AttachContactToConversationRequest; +import com.intercom.api.resources.conversations.requests.AutoAssignConversationRequest; +import com.intercom.api.resources.conversations.requests.ConvertConversationToTicketRequest; +import com.intercom.api.resources.conversations.requests.CreateConversationRequest; +import com.intercom.api.resources.conversations.requests.DetachContactFromConversationRequest; +import com.intercom.api.resources.conversations.requests.FindConversationRequest; +import com.intercom.api.resources.conversations.requests.ListConversationsRequest; +import com.intercom.api.resources.conversations.requests.ManageConversationPartsRequest; +import com.intercom.api.resources.conversations.requests.ReplyToConversationRequest; +import com.intercom.api.resources.conversations.requests.UpdateConversationRequest; +import com.intercom.api.resources.conversations.types.Conversation; +import com.intercom.api.resources.messages.types.Message; +import com.intercom.api.resources.tickets.types.Ticket; +import com.intercom.api.types.CursorPages; +import com.intercom.api.types.Error; +import com.intercom.api.types.PaginatedConversationResponse; +import com.intercom.api.types.RedactConversationRequest; +import com.intercom.api.types.SearchRequest; +import com.intercom.api.types.StartingAfterPaging; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawConversationsClient { + protected final ClientOptions clientOptions; + + public RawConversationsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can fetch a list of all conversations. + *

You can optionally request the result page size and the cursor to start after to fetch the result. + * {% admonition type="warning" name="Pagination" %} + * You can use pagination to limit the number of results returned. The default is 20 results per page. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %}

+ */ + public IntercomHttpResponse> list() { + return list(ListConversationsRequest.builder().build()); + } + + /** + * You can fetch a list of all conversations. + *

You can optionally request the result page size and the cursor to start after to fetch the result. + * {% admonition type="warning" name="Pagination" %} + * You can use pagination to limit the number of results returned. The default is 20 results per page. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %}

+ */ + public IntercomHttpResponse> list(ListConversationsRequest request) { + return list(request, null); + } + + /** + * You can fetch a list of all conversations. + *

You can optionally request the result page size and the cursor to start after to fetch the result. + * {% admonition type="warning" name="Pagination" %} + * You can use pagination to limit the number of results returned. The default is 20 results per page. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %}

+ */ + public IntercomHttpResponse> list( + ListConversationsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations"); + if (request.getPerPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "per_page", request.getPerPage().get().toString(), false); + } + if (request.getStartingAfter().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "starting_after", request.getStartingAfter().get(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + PaginatedConversationResponse parsedResponse = + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), PaginatedConversationResponse.class); + Optional startingAfter = parsedResponse + .getPages() + .flatMap(CursorPages::getNext) + .flatMap(StartingAfterPaging::getStartingAfter); + ListConversationsRequest nextRequest = ListConversationsRequest.builder() + .from(request) + .startingAfter(startingAfter) + .build(); + List result = parsedResponse.getConversations(); + return new IntercomHttpResponse<>( + new SyncPagingIterable( + startingAfter.isPresent(), result, () -> list(nextRequest, requestOptions) + .body()), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 403: + throw new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can create a conversation that has been initiated by a contact (ie. user or lead). + * The conversation can be an in-app message only. + *

{% admonition type="info" name="Sending for visitors" %} + * You can also send a message from a visitor by specifying their user_id or id value in the from field, along with a type field value of contact. + * This visitor will be automatically converted to a contact with a lead role once the conversation is created. + * {% /admonition %}

+ *

This will return the Message model that has been created.

+ */ + public IntercomHttpResponse create(CreateConversationRequest request) { + return create(request, null); + } + + /** + * You can create a conversation that has been initiated by a contact (ie. user or lead). + * The conversation can be an in-app message only. + *

{% admonition type="info" name="Sending for visitors" %} + * You can also send a message from a visitor by specifying their user_id or id value in the from field, along with a type field value of contact. + * This visitor will be automatically converted to a contact with a lead role once the conversation is created. + * {% /admonition %}

+ *

This will return the Message model that has been created.

+ */ + public IntercomHttpResponse create(CreateConversationRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Message.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 403: + throw new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can fetch the details of a single conversation. + *

This will return a single Conversation model with all its conversation parts.

+ *

{% admonition type="warning" name="Hard limit of 500 parts" %} + * The maximum number of conversation parts that can be returned via the API is 500. If you have more than that we will return the 500 most recent conversation parts. + * {% /admonition %}

+ *

For AI agent conversation metadata, please note that you need to have the agent enabled in your workspace, which is a paid feature.

+ */ + public IntercomHttpResponse find(FindConversationRequest request) { + return find(request, null); + } + + /** + * You can fetch the details of a single conversation. + *

This will return a single Conversation model with all its conversation parts.

+ *

{% admonition type="warning" name="Hard limit of 500 parts" %} + * The maximum number of conversation parts that can be returned via the API is 500. If you have more than that we will return the 500 most recent conversation parts. + * {% /admonition %}

+ *

For AI agent conversation metadata, please note that you need to have the agent enabled in your workspace, which is a paid feature.

+ */ + public IntercomHttpResponse find(FindConversationRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations") + .addPathSegment(request.getConversationId()); + if (request.getDisplayAs().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "display_as", request.getDisplayAs().get(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 403: + throw new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can update an existing conversation. + *

{% admonition type="info" name="Replying and other actions" %} + * If you want to reply to a coveration or take an action such as assign, unassign, open, close or snooze, take a look at the reply and manage endpoints. + * {% /admonition %}

+ */ + public IntercomHttpResponse update(UpdateConversationRequest request) { + return update(request, null); + } + + /** + * You can update an existing conversation. + *

{% admonition type="info" name="Replying and other actions" %} + * If you want to reply to a coveration or take an action such as assign, unassign, open, close or snooze, take a look at the reply and manage endpoints. + * {% /admonition %}

+ */ + public IntercomHttpResponse update(UpdateConversationRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations") + .addPathSegment(request.getConversationId()); + if (request.getDisplayAs().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "display_as", request.getDisplayAs().get(), false); + } + Map properties = new HashMap<>(); + if (request.getRead().isPresent()) { + properties.put("read", request.getRead()); + } + if (request.getCustomAttributes().isPresent()) { + properties.put("custom_attributes", request.getCustomAttributes()); + } + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(properties), MediaTypes.APPLICATION_JSON); + } catch (Exception e) { + throw new RuntimeException(e); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 403: + throw new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can search for multiple conversations by the value of their attributes in order to fetch exactly which ones you want. + *

To search for conversations, you need to send a POST request to https://api.intercom.io/conversations/search.

+ *

This will accept a query object in the body which will define your filters in order to search for conversations. + * {% admonition type="warning" name="Optimizing search queries" %} + * Search queries can be complex, so optimizing them can help the performance of your search. + * Use the AND and OR operators to combine multiple filters to get the exact results you need and utilize + * pagination to limit the number of results returned. The default is 20 results per page and maximum is 150. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %}

+ *

Nesting & Limitations

+ *

You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4). + * There are some limitations to the amount of multiple's there can be:

+ *
    + *
  • There's a limit of max 2 nested filters
  • + *
  • There's a limit of max 15 filters for each AND or OR group
  • + *
+ *

Accepted Fields

+ *

Most keys listed as part of the The conversation model is searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as created_at accepts a date, the value cannot be a string such as "foorbar"). + * The source.body field is unique as the search will not be performed against the entire value, but instead against every element of the value separately. For example, when searching for a conversation with a "I need support" body - the query should contain a = operator with the value "support" for such conversation to be returned. A query with a = operator and a "need support" value will not yield a result.

+ *

| Field | Type | + * | :---------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- | + * | id | String | + * | created_at | Date (UNIX timestamp) | + * | updated_at | Date (UNIX timestamp) | + * | source.type | String<br>Accepted fields are conversation, email, facebook, instagram, phone_call, phone_switch, push, sms, twitter and whatsapp. | + * | source.id | String | + * | source.delivered_as | String | + * | source.subject | String | + * | source.body | String | + * | source.author.id | String | + * | source.author.type | String | + * | source.author.name | String | + * | source.author.email | String | + * | source.url | String | + * | contact_ids | String | + * | teammate_ids | String | + * | admin_assignee_id | String | + * | team_assignee_id | String | + * | channel_initiated | String | + * | open | Boolean | + * | read | Boolean | + * | state | String | + * | waiting_since | Date (UNIX timestamp) | + * | snoozed_until | Date (UNIX timestamp) | + * | tag_ids | String | + * | priority | String | + * | statistics.time_to_assignment | Integer | + * | statistics.time_to_admin_reply | Integer | + * | statistics.time_to_first_close | Integer | + * | statistics.time_to_last_close | Integer | + * | statistics.median_time_to_reply | Integer | + * | statistics.first_contact_reply_at | Date (UNIX timestamp) | + * | statistics.first_assignment_at | Date (UNIX timestamp) | + * | statistics.first_admin_reply_at | Date (UNIX timestamp) | + * | statistics.first_close_at | Date (UNIX timestamp) | + * | statistics.last_assignment_at | Date (UNIX timestamp) | + * | statistics.last_assignment_admin_reply_at | Date (UNIX timestamp) | + * | statistics.last_contact_reply_at | Date (UNIX timestamp) | + * | statistics.last_admin_reply_at | Date (UNIX timestamp) | + * | statistics.last_close_at | Date (UNIX timestamp) | + * | statistics.last_closed_by_id | String | + * | statistics.count_reopens | Integer | + * | statistics.count_assignments | Integer | + * | statistics.count_conversation_parts | Integer | + * | conversation_rating.requested_at | Date (UNIX timestamp) | + * | conversation_rating.replied_at | Date (UNIX timestamp) | + * | conversation_rating.score | Integer | + * | conversation_rating.remark | String | + * | conversation_rating.contact_id | String | + * | conversation_rating.admin_d | String | + * | ai_agent_participated | Boolean | + * | ai_agent.resolution_state | String | + * | ai_agent.last_answer_type | String | + * | ai_agent.rating | Integer | + * | ai_agent.rating_remark | String | + * | ai_agent.source_type | String | + * | ai_agent.source_title | String |

+ *

Accepted Operators

+ *

The table below shows the operators you can use to define how you want to search for the value. The operator should be put in as a string ("="). The operator has to be compatible with the field's type (eg. you cannot search with > for a given string value as it's only compatible for integer's and dates).

+ *

| Operator | Valid Types | Description | + * | :------- | :----------------------------- | :----------------------------------------------------------- | + * | = | All | Equals | + * | != | All | Doesn't Equal | + * | IN | All | In Shortcut for OR queries Values most be in Array | + * | NIN | All | Not In Shortcut for OR ! queries Values must be in Array | + * | > | Integer Date (UNIX Timestamp) | Greater (or equal) than | + * | < | Integer Date (UNIX Timestamp) | Lower (or equal) than | + * | ~ | String | Contains | + * | !~ | String | Doesn't Contain | + * | ^ | String | Starts With | + * | $ | String | Ends With |

+ */ + public IntercomHttpResponse> search(SearchRequest request) { + return search(request, null); + } + + /** + * You can search for multiple conversations by the value of their attributes in order to fetch exactly which ones you want. + *

To search for conversations, you need to send a POST request to https://api.intercom.io/conversations/search.

+ *

This will accept a query object in the body which will define your filters in order to search for conversations. + * {% admonition type="warning" name="Optimizing search queries" %} + * Search queries can be complex, so optimizing them can help the performance of your search. + * Use the AND and OR operators to combine multiple filters to get the exact results you need and utilize + * pagination to limit the number of results returned. The default is 20 results per page and maximum is 150. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %}

+ *

Nesting & Limitations

+ *

You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4). + * There are some limitations to the amount of multiple's there can be:

+ *
    + *
  • There's a limit of max 2 nested filters
  • + *
  • There's a limit of max 15 filters for each AND or OR group
  • + *
+ *

Accepted Fields

+ *

Most keys listed as part of the The conversation model is searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as created_at accepts a date, the value cannot be a string such as "foorbar"). + * The source.body field is unique as the search will not be performed against the entire value, but instead against every element of the value separately. For example, when searching for a conversation with a "I need support" body - the query should contain a = operator with the value "support" for such conversation to be returned. A query with a = operator and a "need support" value will not yield a result.

+ *

| Field | Type | + * | :---------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- | + * | id | String | + * | created_at | Date (UNIX timestamp) | + * | updated_at | Date (UNIX timestamp) | + * | source.type | String<br>Accepted fields are conversation, email, facebook, instagram, phone_call, phone_switch, push, sms, twitter and whatsapp. | + * | source.id | String | + * | source.delivered_as | String | + * | source.subject | String | + * | source.body | String | + * | source.author.id | String | + * | source.author.type | String | + * | source.author.name | String | + * | source.author.email | String | + * | source.url | String | + * | contact_ids | String | + * | teammate_ids | String | + * | admin_assignee_id | String | + * | team_assignee_id | String | + * | channel_initiated | String | + * | open | Boolean | + * | read | Boolean | + * | state | String | + * | waiting_since | Date (UNIX timestamp) | + * | snoozed_until | Date (UNIX timestamp) | + * | tag_ids | String | + * | priority | String | + * | statistics.time_to_assignment | Integer | + * | statistics.time_to_admin_reply | Integer | + * | statistics.time_to_first_close | Integer | + * | statistics.time_to_last_close | Integer | + * | statistics.median_time_to_reply | Integer | + * | statistics.first_contact_reply_at | Date (UNIX timestamp) | + * | statistics.first_assignment_at | Date (UNIX timestamp) | + * | statistics.first_admin_reply_at | Date (UNIX timestamp) | + * | statistics.first_close_at | Date (UNIX timestamp) | + * | statistics.last_assignment_at | Date (UNIX timestamp) | + * | statistics.last_assignment_admin_reply_at | Date (UNIX timestamp) | + * | statistics.last_contact_reply_at | Date (UNIX timestamp) | + * | statistics.last_admin_reply_at | Date (UNIX timestamp) | + * | statistics.last_close_at | Date (UNIX timestamp) | + * | statistics.last_closed_by_id | String | + * | statistics.count_reopens | Integer | + * | statistics.count_assignments | Integer | + * | statistics.count_conversation_parts | Integer | + * | conversation_rating.requested_at | Date (UNIX timestamp) | + * | conversation_rating.replied_at | Date (UNIX timestamp) | + * | conversation_rating.score | Integer | + * | conversation_rating.remark | String | + * | conversation_rating.contact_id | String | + * | conversation_rating.admin_d | String | + * | ai_agent_participated | Boolean | + * | ai_agent.resolution_state | String | + * | ai_agent.last_answer_type | String | + * | ai_agent.rating | Integer | + * | ai_agent.rating_remark | String | + * | ai_agent.source_type | String | + * | ai_agent.source_title | String |

+ *

Accepted Operators

+ *

The table below shows the operators you can use to define how you want to search for the value. The operator should be put in as a string ("="). The operator has to be compatible with the field's type (eg. you cannot search with > for a given string value as it's only compatible for integer's and dates).

+ *

| Operator | Valid Types | Description | + * | :------- | :----------------------------- | :----------------------------------------------------------- | + * | = | All | Equals | + * | != | All | Doesn't Equal | + * | IN | All | In Shortcut for OR queries Values most be in Array | + * | NIN | All | Not In Shortcut for OR ! queries Values must be in Array | + * | > | Integer Date (UNIX Timestamp) | Greater (or equal) than | + * | < | Integer Date (UNIX Timestamp) | Lower (or equal) than | + * | ~ | String | Contains | + * | !~ | String | Doesn't Contain | + * | ^ | String | Starts With | + * | $ | String | Ends With |

+ */ + public IntercomHttpResponse> search( + SearchRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations/search") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + PaginatedConversationResponse parsedResponse = + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), PaginatedConversationResponse.class); + Optional startingAfter = parsedResponse + .getPages() + .flatMap(CursorPages::getNext) + .flatMap(StartingAfterPaging::getStartingAfter); + Optional pagination = request.getPagination() + .map(pagination_ -> StartingAfterPaging.builder() + .from(pagination_) + .startingAfter(startingAfter) + .build()); + SearchRequest nextRequest = SearchRequest.builder() + .from(request) + .pagination(pagination) + .build(); + List result = parsedResponse.getConversations(); + return new IntercomHttpResponse<>( + new SyncPagingIterable( + startingAfter.isPresent(), result, () -> search(nextRequest, requestOptions) + .body()), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can reply to a conversation with a message from an admin or on behalf of a contact, or with a note for admins. + */ + public IntercomHttpResponse reply(ReplyToConversationRequest request) { + return reply(request, null); + } + + /** + * You can reply to a conversation with a message from an admin or on behalf of a contact, or with a note for admins. + */ + public IntercomHttpResponse reply(ReplyToConversationRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations") + .addPathSegment(request.getConversationId()) + .addPathSegments("reply") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request.getBody()), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 403: + throw new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * For managing conversations you can: + *
    + *
  • Close a conversation
  • + *
  • Snooze a conversation to reopen on a future date
  • + *
  • Open a conversation which is snoozed or closed
  • + *
  • Assign a conversation to an admin and/or team.
  • + *
+ */ + public IntercomHttpResponse manage(ManageConversationPartsRequest request) { + return manage(request, null); + } + + /** + * For managing conversations you can: + *
    + *
  • Close a conversation
  • + *
  • Snooze a conversation to reopen on a future date
  • + *
  • Open a conversation which is snoozed or closed
  • + *
  • Assign a conversation to an admin and/or team.
  • + *
+ */ + public IntercomHttpResponse manage( + ManageConversationPartsRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations") + .addPathSegment(request.getConversationId()) + .addPathSegments("parts") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request.getBody()), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 403: + throw new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * {% admonition type="danger" name="Deprecation of Run Assignment Rules" %} + * Run assignment rules is now deprecated in version 2.12 and future versions and will be permanently removed on December 31, 2026. After this date, any requests made to this endpoint will fail. + * {% /admonition %} + * You can let a conversation be automatically assigned following assignment rules. + * {% admonition type="warning" name="When using workflows" %} + * It is not possible to use this endpoint with Workflows. + * {% /admonition %} + */ + public IntercomHttpResponse runAssignmentRules(AutoAssignConversationRequest request) { + return runAssignmentRules(request, null); + } + + /** + * {% admonition type="danger" name="Deprecation of Run Assignment Rules" %} + * Run assignment rules is now deprecated in version 2.12 and future versions and will be permanently removed on December 31, 2026. After this date, any requests made to this endpoint will fail. + * {% /admonition %} + * You can let a conversation be automatically assigned following assignment rules. + * {% admonition type="warning" name="When using workflows" %} + * It is not possible to use this endpoint with Workflows. + * {% /admonition %} + */ + public IntercomHttpResponse runAssignmentRules( + AutoAssignConversationRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations") + .addPathSegment(request.getConversationId()) + .addPathSegments("run_assignment_rules") + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("POST", RequestBody.create("", null)) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 403: + throw new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can add participants who are contacts to a conversation, on behalf of either another contact or an admin. + *

{% admonition type="warning" name="Contacts without an email" %} + * If you add a contact via the email parameter and there is no user/lead found on that workspace with he given email, then we will create a new contact with role set to lead. + * {% /admonition %}

+ */ + public IntercomHttpResponse attachContactAsAdmin(AttachContactToConversationRequest request) { + return attachContactAsAdmin(request, null); + } + + /** + * You can add participants who are contacts to a conversation, on behalf of either another contact or an admin. + *

{% admonition type="warning" name="Contacts without an email" %} + * If you add a contact via the email parameter and there is no user/lead found on that workspace with he given email, then we will create a new contact with role set to lead. + * {% /admonition %}

+ */ + public IntercomHttpResponse attachContactAsAdmin( + AttachContactToConversationRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations") + .addPathSegment(request.getConversationId()) + .addPathSegments("customers") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 403: + throw new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can add participants who are contacts to a conversation, on behalf of either another contact or an admin. + *

{% admonition type="warning" name="Contacts without an email" %} + * If you add a contact via the email parameter and there is no user/lead found on that workspace with he given email, then we will create a new contact with role set to lead. + * {% /admonition %}

+ */ + public IntercomHttpResponse detachContactAsAdmin(DetachContactFromConversationRequest request) { + return detachContactAsAdmin(request, null); + } + + /** + * You can add participants who are contacts to a conversation, on behalf of either another contact or an admin. + *

{% admonition type="warning" name="Contacts without an email" %} + * If you add a contact via the email parameter and there is no user/lead found on that workspace with he given email, then we will create a new contact with role set to lead. + * {% /admonition %}

+ */ + public IntercomHttpResponse detachContactAsAdmin( + DetachContactFromConversationRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations") + .addPathSegment(request.getConversationId()) + .addPathSegments("customers") + .addPathSegment(request.getContactId()) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("DELETE", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 403: + throw new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can redact a conversation part or the source message of a conversation (as seen in the source object). + *

{% admonition type="info" name="Redacting parts and messages" %} + * If you are redacting a conversation part, it must have a body. If you are redacting a source message, it must have been created by a contact. We will return a conversation_part_not_redactable error if these criteria are not met. + * {% /admonition %}

+ */ + public IntercomHttpResponse redactConversationPart(RedactConversationRequest request) { + return redactConversationPart(request, null); + } + + /** + * You can redact a conversation part or the source message of a conversation (as seen in the source object). + *

{% admonition type="info" name="Redacting parts and messages" %} + * If you are redacting a conversation part, it must have a body. If you are redacting a source message, it must have been created by a contact. We will return a conversation_part_not_redactable error if these criteria are not met. + * {% /admonition %}

+ */ + public IntercomHttpResponse redactConversationPart( + RedactConversationRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations/redact") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Conversation.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can convert a conversation to a ticket. + */ + public IntercomHttpResponse convertToTicket(ConvertConversationToTicketRequest request) { + return convertToTicket(request, null); + } + + /** + * You can convert a conversation to a ticket. + */ + public IntercomHttpResponse convertToTicket( + ConvertConversationToTicketRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations") + .addPathSegment(request.getConversationId()) + .addPathSegments("convert") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Ticket.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 400) { + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/intercom/api/resources/dataattributes/AsyncDataAttributesClient.java b/src/main/java/com/intercom/api/resources/dataattributes/AsyncDataAttributesClient.java index 07add2c..175bcf9 100644 --- a/src/main/java/com/intercom/api/resources/dataattributes/AsyncDataAttributesClient.java +++ b/src/main/java/com/intercom/api/resources/dataattributes/AsyncDataAttributesClient.java @@ -3,199 +3,65 @@ */ package com.intercom.api.resources.dataattributes; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; -import com.intercom.api.core.QueryStringMapper; import com.intercom.api.core.RequestOptions; -import com.intercom.api.errors.BadRequestError; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; -import com.intercom.api.errors.UnprocessableEntityError; import com.intercom.api.resources.dataattributes.requests.CreateDataAttributeRequest; import com.intercom.api.resources.dataattributes.requests.ListDataAttributesRequest; import com.intercom.api.resources.dataattributes.requests.UpdateDataAttributeRequest; import com.intercom.api.resources.dataattributes.types.DataAttribute; import com.intercom.api.types.DataAttributeList; -import com.intercom.api.types.Error; -import java.io.IOException; import java.util.concurrent.CompletableFuture; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; public class AsyncDataAttributesClient { protected final ClientOptions clientOptions; + private final AsyncRawDataAttributesClient rawClient; + public AsyncDataAttributesClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new AsyncRawDataAttributesClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawDataAttributesClient withRawResponse() { + return this.rawClient; } /** * You can fetch a list of all data attributes belonging to a workspace for contacts, companies or conversations. */ public CompletableFuture list() { - return list(ListDataAttributesRequest.builder().build()); + return this.rawClient.list().thenApply(response -> response.body()); } /** * You can fetch a list of all data attributes belonging to a workspace for contacts, companies or conversations. */ public CompletableFuture list(ListDataAttributesRequest request) { - return list(request, null); + return this.rawClient.list(request).thenApply(response -> response.body()); } /** * You can fetch a list of all data attributes belonging to a workspace for contacts, companies or conversations. */ public CompletableFuture list(ListDataAttributesRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("data_attributes"); - if (request.getModel().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "model", request.getModel().get().toString(), false); - } - if (request.getIncludeArchived().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "include_archived", - request.getIncludeArchived().get().toString(), - false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataAttributeList.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.list(request, requestOptions).thenApply(response -> response.body()); } /** * You can create a data attributes for a contact or a company. */ public CompletableFuture create(CreateDataAttributeRequest request) { - return create(request, null); + return this.rawClient.create(request).thenApply(response -> response.body()); } /** * You can create a data attributes for a contact or a company. */ public CompletableFuture create(CreateDataAttributeRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("data_attributes") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataAttribute.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.create(request, requestOptions).thenApply(response -> response.body()); } /** @@ -206,7 +72,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { * */ public CompletableFuture update(UpdateDataAttributeRequest request) { - return update(request, null); + return this.rawClient.update(request).thenApply(response -> response.body()); } /** @@ -217,77 +83,6 @@ public CompletableFuture update(UpdateDataAttributeRequest reques * */ public CompletableFuture update(UpdateDataAttributeRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("data_attributes") - .addPathSegment(request.getDataAttributeId()) - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PUT", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataAttribute.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.update(request, requestOptions).thenApply(response -> response.body()); } } diff --git a/src/main/java/com/intercom/api/resources/dataattributes/AsyncRawDataAttributesClient.java b/src/main/java/com/intercom/api/resources/dataattributes/AsyncRawDataAttributesClient.java new file mode 100644 index 0000000..aa9b3e6 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/dataattributes/AsyncRawDataAttributesClient.java @@ -0,0 +1,309 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.dataattributes; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.QueryStringMapper; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.BadRequestError; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.errors.UnprocessableEntityError; +import com.intercom.api.resources.dataattributes.requests.CreateDataAttributeRequest; +import com.intercom.api.resources.dataattributes.requests.ListDataAttributesRequest; +import com.intercom.api.resources.dataattributes.requests.UpdateDataAttributeRequest; +import com.intercom.api.resources.dataattributes.types.DataAttribute; +import com.intercom.api.types.DataAttributeList; +import com.intercom.api.types.Error; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawDataAttributesClient { + protected final ClientOptions clientOptions; + + public AsyncRawDataAttributesClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can fetch a list of all data attributes belonging to a workspace for contacts, companies or conversations. + */ + public CompletableFuture> list() { + return list(ListDataAttributesRequest.builder().build()); + } + + /** + * You can fetch a list of all data attributes belonging to a workspace for contacts, companies or conversations. + */ + public CompletableFuture> list(ListDataAttributesRequest request) { + return list(request, null); + } + + /** + * You can fetch a list of all data attributes belonging to a workspace for contacts, companies or conversations. + */ + public CompletableFuture> list( + ListDataAttributesRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("data_attributes"); + if (request.getModel().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "model", request.getModel().get().toString(), false); + } + if (request.getIncludeArchived().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "include_archived", + request.getIncludeArchived().get().toString(), + false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataAttributeList.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can create a data attributes for a contact or a company. + */ + public CompletableFuture> create(CreateDataAttributeRequest request) { + return create(request, null); + } + + /** + * You can create a data attributes for a contact or a company. + */ + public CompletableFuture> create( + CreateDataAttributeRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("data_attributes") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataAttribute.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can update a data attribute. + *
+ *

🚧 Updating the data type is not possible

+ *

It is currently a dangerous action to execute changing a data attribute's type via the API. You will need to update the type via the UI instead.

+ *
+ */ + public CompletableFuture> update(UpdateDataAttributeRequest request) { + return update(request, null); + } + + /** + * You can update a data attribute. + *
+ *

🚧 Updating the data type is not possible

+ *

It is currently a dangerous action to execute changing a data attribute's type via the API. You will need to update the type via the UI instead.

+ *
+ */ + public CompletableFuture> update( + UpdateDataAttributeRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("data_attributes") + .addPathSegment(request.getDataAttributeId()) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataAttribute.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 422: + future.completeExceptionally(new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/intercom/api/resources/dataattributes/DataAttributesClient.java b/src/main/java/com/intercom/api/resources/dataattributes/DataAttributesClient.java index 2e411c9..22e4648 100644 --- a/src/main/java/com/intercom/api/resources/dataattributes/DataAttributesClient.java +++ b/src/main/java/com/intercom/api/resources/dataattributes/DataAttributesClient.java @@ -3,163 +3,64 @@ */ package com.intercom.api.resources.dataattributes; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; -import com.intercom.api.core.QueryStringMapper; import com.intercom.api.core.RequestOptions; -import com.intercom.api.errors.BadRequestError; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; -import com.intercom.api.errors.UnprocessableEntityError; import com.intercom.api.resources.dataattributes.requests.CreateDataAttributeRequest; import com.intercom.api.resources.dataattributes.requests.ListDataAttributesRequest; import com.intercom.api.resources.dataattributes.requests.UpdateDataAttributeRequest; import com.intercom.api.resources.dataattributes.types.DataAttribute; import com.intercom.api.types.DataAttributeList; -import com.intercom.api.types.Error; -import java.io.IOException; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; public class DataAttributesClient { protected final ClientOptions clientOptions; + private final RawDataAttributesClient rawClient; + public DataAttributesClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawDataAttributesClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawDataAttributesClient withRawResponse() { + return this.rawClient; } /** * You can fetch a list of all data attributes belonging to a workspace for contacts, companies or conversations. */ public DataAttributeList list() { - return list(ListDataAttributesRequest.builder().build()); + return this.rawClient.list().body(); } /** * You can fetch a list of all data attributes belonging to a workspace for contacts, companies or conversations. */ public DataAttributeList list(ListDataAttributesRequest request) { - return list(request, null); + return this.rawClient.list(request).body(); } /** * You can fetch a list of all data attributes belonging to a workspace for contacts, companies or conversations. */ public DataAttributeList list(ListDataAttributesRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("data_attributes"); - if (request.getModel().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "model", request.getModel().get().toString(), false); - } - if (request.getIncludeArchived().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "include_archived", - request.getIncludeArchived().get().toString(), - false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataAttributeList.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.list(request, requestOptions).body(); } /** * You can create a data attributes for a contact or a company. */ public DataAttribute create(CreateDataAttributeRequest request) { - return create(request, null); + return this.rawClient.create(request).body(); } /** * You can create a data attributes for a contact or a company. */ public DataAttribute create(CreateDataAttributeRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("data_attributes") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataAttribute.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.create(request, requestOptions).body(); } /** @@ -170,7 +71,7 @@ public DataAttribute create(CreateDataAttributeRequest request, RequestOptions r * */ public DataAttribute update(UpdateDataAttributeRequest request) { - return update(request, null); + return this.rawClient.update(request).body(); } /** @@ -181,58 +82,6 @@ public DataAttribute update(UpdateDataAttributeRequest request) { * */ public DataAttribute update(UpdateDataAttributeRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("data_attributes") - .addPathSegment(request.getDataAttributeId()) - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PUT", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataAttribute.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.update(request, requestOptions).body(); } } diff --git a/src/main/java/com/intercom/api/resources/dataattributes/RawDataAttributesClient.java b/src/main/java/com/intercom/api/resources/dataattributes/RawDataAttributesClient.java new file mode 100644 index 0000000..3116f21 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/dataattributes/RawDataAttributesClient.java @@ -0,0 +1,250 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.dataattributes; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.QueryStringMapper; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.BadRequestError; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.errors.UnprocessableEntityError; +import com.intercom.api.resources.dataattributes.requests.CreateDataAttributeRequest; +import com.intercom.api.resources.dataattributes.requests.ListDataAttributesRequest; +import com.intercom.api.resources.dataattributes.requests.UpdateDataAttributeRequest; +import com.intercom.api.resources.dataattributes.types.DataAttribute; +import com.intercom.api.types.DataAttributeList; +import com.intercom.api.types.Error; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawDataAttributesClient { + protected final ClientOptions clientOptions; + + public RawDataAttributesClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can fetch a list of all data attributes belonging to a workspace for contacts, companies or conversations. + */ + public IntercomHttpResponse list() { + return list(ListDataAttributesRequest.builder().build()); + } + + /** + * You can fetch a list of all data attributes belonging to a workspace for contacts, companies or conversations. + */ + public IntercomHttpResponse list(ListDataAttributesRequest request) { + return list(request, null); + } + + /** + * You can fetch a list of all data attributes belonging to a workspace for contacts, companies or conversations. + */ + public IntercomHttpResponse list( + ListDataAttributesRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("data_attributes"); + if (request.getModel().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "model", request.getModel().get().toString(), false); + } + if (request.getIncludeArchived().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "include_archived", + request.getIncludeArchived().get().toString(), + false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataAttributeList.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can create a data attributes for a contact or a company. + */ + public IntercomHttpResponse create(CreateDataAttributeRequest request) { + return create(request, null); + } + + /** + * You can create a data attributes for a contact or a company. + */ + public IntercomHttpResponse create( + CreateDataAttributeRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("data_attributes") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataAttribute.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can update a data attribute. + *
+ *

🚧 Updating the data type is not possible

+ *

It is currently a dangerous action to execute changing a data attribute's type via the API. You will need to update the type via the UI instead.

+ *
+ */ + public IntercomHttpResponse update(UpdateDataAttributeRequest request) { + return update(request, null); + } + + /** + * You can update a data attribute. + *
+ *

🚧 Updating the data type is not possible

+ *

It is currently a dangerous action to execute changing a data attribute's type via the API. You will need to update the type via the UI instead.

+ *
+ */ + public IntercomHttpResponse update( + UpdateDataAttributeRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("data_attributes") + .addPathSegment(request.getDataAttributeId()) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataAttribute.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/intercom/api/resources/dataexport/AsyncDataExportClient.java b/src/main/java/com/intercom/api/resources/dataexport/AsyncDataExportClient.java index 2d094d9..a64e7a7 100644 --- a/src/main/java/com/intercom/api/resources/dataexport/AsyncDataExportClient.java +++ b/src/main/java/com/intercom/api/resources/dataexport/AsyncDataExportClient.java @@ -3,36 +3,30 @@ */ package com.intercom.api.resources.dataexport; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; import com.intercom.api.core.RequestOptions; import com.intercom.api.resources.dataexport.requests.CancelDataExportRequest; import com.intercom.api.resources.dataexport.requests.CreateDataExportRequest; import com.intercom.api.resources.dataexport.requests.DownloadDataExportRequest; import com.intercom.api.resources.dataexport.requests.FindDataExportRequest; import com.intercom.api.resources.dataexport.types.DataExport; -import java.io.IOException; import java.util.concurrent.CompletableFuture; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; public class AsyncDataExportClient { protected final ClientOptions clientOptions; + private final AsyncRawDataExportClient rawClient; + public AsyncDataExportClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new AsyncRawDataExportClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawDataExportClient withRawResponse() { + return this.rawClient; } /** @@ -52,7 +46,7 @@ public AsyncDataExportClient(ClientOptions clientOptions) { * */ public CompletableFuture create(CreateDataExportRequest request) { - return create(request, null); + return this.rawClient.create(request).thenApply(response -> response.body()); } /** @@ -72,54 +66,7 @@ public CompletableFuture create(CreateDataExportRequest request) { * */ public CompletableFuture create(CreateDataExportRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("export/content/data") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataExport.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.create(request, requestOptions).thenApply(response -> response.body()); } /** @@ -131,7 +78,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { * */ public CompletableFuture find(FindDataExportRequest request) { - return find(request, null); + return this.rawClient.find(request).thenApply(response -> response.body()); } /** @@ -143,103 +90,21 @@ public CompletableFuture find(FindDataExportRequest request) { * */ public CompletableFuture find(FindDataExportRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("export/content/data") - .addPathSegment(request.getJobIdentifier()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataExport.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.find(request, requestOptions).thenApply(response -> response.body()); } /** * You can cancel your job */ public CompletableFuture cancel(CancelDataExportRequest request) { - return cancel(request, null); + return this.rawClient.cancel(request).thenApply(response -> response.body()); } /** * You can cancel your job */ public CompletableFuture cancel(CancelDataExportRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("export/cancel") - .addPathSegment(request.getJobIdentifier()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("POST", RequestBody.create("", null)) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataExport.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.cancel(request, requestOptions).thenApply(response -> response.body()); } /** @@ -251,7 +116,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { * */ public CompletableFuture download(DownloadDataExportRequest request) { - return download(request, null); + return this.rawClient.download(request).thenApply(response -> response.body()); } /** @@ -263,45 +128,6 @@ public CompletableFuture download(DownloadDataExportRequest request) { * */ public CompletableFuture download(DownloadDataExportRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("download/content/data") - .addPathSegment(request.getJobIdentifier()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(null); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.download(request, requestOptions).thenApply(response -> response.body()); } } diff --git a/src/main/java/com/intercom/api/resources/dataexport/AsyncRawDataExportClient.java b/src/main/java/com/intercom/api/resources/dataexport/AsyncRawDataExportClient.java new file mode 100644 index 0000000..7ce121e --- /dev/null +++ b/src/main/java/com/intercom/api/resources/dataexport/AsyncRawDataExportClient.java @@ -0,0 +1,322 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.dataexport; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.resources.dataexport.requests.CancelDataExportRequest; +import com.intercom.api.resources.dataexport.requests.CreateDataExportRequest; +import com.intercom.api.resources.dataexport.requests.DownloadDataExportRequest; +import com.intercom.api.resources.dataexport.requests.FindDataExportRequest; +import com.intercom.api.resources.dataexport.types.DataExport; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawDataExportClient { + protected final ClientOptions clientOptions; + + public AsyncRawDataExportClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * To create your export job, you need to send a POST request to the export endpoint https://api.intercom.io/export/content/data. + *

The only parameters you need to provide are the range of dates that you want exported.

+ *
+ *

🚧 Limit of one active job

+ *

You can only have one active job per workspace. You will receive a HTTP status code of 429 with the message Exceeded rate limit of 1 pending message data export jobs if you attempt to create a second concurrent job.

+ *
+ *
+ *

❗️ Updated_at not included

+ *

It should be noted that the timeframe only includes messages sent during the time period and not messages that were only updated during this period. For example, if a message was updated yesterday but sent two days ago, you would need to set the created_at_after date before the message was sent to include that in your retrieval job.

+ *
+ *
+ *

📘 Date ranges are inclusive

+ *

Requesting data for 2018-06-01 until 2018-06-30 will get all data for those days including those specified - e.g. 2018-06-01 00:00:00 until 2018-06-30 23:59:99.

+ *
+ */ + public CompletableFuture> create(CreateDataExportRequest request) { + return create(request, null); + } + + /** + * To create your export job, you need to send a POST request to the export endpoint https://api.intercom.io/export/content/data. + *

The only parameters you need to provide are the range of dates that you want exported.

+ *
+ *

🚧 Limit of one active job

+ *

You can only have one active job per workspace. You will receive a HTTP status code of 429 with the message Exceeded rate limit of 1 pending message data export jobs if you attempt to create a second concurrent job.

+ *
+ *
+ *

❗️ Updated_at not included

+ *

It should be noted that the timeframe only includes messages sent during the time period and not messages that were only updated during this period. For example, if a message was updated yesterday but sent two days ago, you would need to set the created_at_after date before the message was sent to include that in your retrieval job.

+ *
+ *
+ *

📘 Date ranges are inclusive

+ *

Requesting data for 2018-06-01 until 2018-06-30 will get all data for those days including those specified - e.g. 2018-06-01 00:00:00 until 2018-06-30 23:59:99.

+ *
+ */ + public CompletableFuture> create( + CreateDataExportRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("export/content/data") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataExport.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can view the status of your job by sending a GET request to the URL + * https://api.intercom.io/export/content/data/{job_identifier} - the {job_identifier} is the value returned in the response when you first created the export job. More on it can be seen in the Export Job Model. + *
+ *

🚧 Jobs expire after two days + * All jobs that have completed processing (and are thus available to download from the provided URL) will have an expiry limit of two days from when the export ob completed. After this, the data will no longer be available.

+ *
+ */ + public CompletableFuture> find(FindDataExportRequest request) { + return find(request, null); + } + + /** + * You can view the status of your job by sending a GET request to the URL + * https://api.intercom.io/export/content/data/{job_identifier} - the {job_identifier} is the value returned in the response when you first created the export job. More on it can be seen in the Export Job Model. + *
+ *

🚧 Jobs expire after two days + * All jobs that have completed processing (and are thus available to download from the provided URL) will have an expiry limit of two days from when the export ob completed. After this, the data will no longer be available.

+ *
+ */ + public CompletableFuture> find( + FindDataExportRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("export/content/data") + .addPathSegment(request.getJobIdentifier()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataExport.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can cancel your job + */ + public CompletableFuture> cancel(CancelDataExportRequest request) { + return cancel(request, null); + } + + /** + * You can cancel your job + */ + public CompletableFuture> cancel( + CancelDataExportRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("export/cancel") + .addPathSegment(request.getJobIdentifier()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("POST", RequestBody.create("", null)) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataExport.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * When a job has a status of complete, and thus a filled download_url, you can download your data by hitting that provided URL, formatted like so: https://api.intercom.io/download/content/data/xyz1234. + *

Your exported message data will be streamed continuously back down to you in a gzipped CSV format.

+ *
+ *

📘 Octet header required

+ *

You will have to specify the header Accept: application/octet-stream when hitting this endpoint.

+ *
+ */ + public CompletableFuture> download(DownloadDataExportRequest request) { + return download(request, null); + } + + /** + * When a job has a status of complete, and thus a filled download_url, you can download your data by hitting that provided URL, formatted like so: https://api.intercom.io/download/content/data/xyz1234. + *

Your exported message data will be streamed continuously back down to you in a gzipped CSV format.

+ *
+ *

📘 Octet header required

+ *

You will have to specify the header Accept: application/octet-stream when hitting this endpoint.

+ *
+ */ + public CompletableFuture> download( + DownloadDataExportRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("download/content/data") + .addPathSegment(request.getJobIdentifier()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>(null, response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/intercom/api/resources/dataexport/DataExportClient.java b/src/main/java/com/intercom/api/resources/dataexport/DataExportClient.java index d628ae4..0237d41 100644 --- a/src/main/java/com/intercom/api/resources/dataexport/DataExportClient.java +++ b/src/main/java/com/intercom/api/resources/dataexport/DataExportClient.java @@ -3,32 +3,29 @@ */ package com.intercom.api.resources.dataexport; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; import com.intercom.api.core.RequestOptions; import com.intercom.api.resources.dataexport.requests.CancelDataExportRequest; import com.intercom.api.resources.dataexport.requests.CreateDataExportRequest; import com.intercom.api.resources.dataexport.requests.DownloadDataExportRequest; import com.intercom.api.resources.dataexport.requests.FindDataExportRequest; import com.intercom.api.resources.dataexport.types.DataExport; -import java.io.IOException; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; public class DataExportClient { protected final ClientOptions clientOptions; + private final RawDataExportClient rawClient; + public DataExportClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawDataExportClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawDataExportClient withRawResponse() { + return this.rawClient; } /** @@ -48,7 +45,7 @@ public DataExportClient(ClientOptions clientOptions) { * */ public DataExport create(CreateDataExportRequest request) { - return create(request, null); + return this.rawClient.create(request).body(); } /** @@ -68,41 +65,7 @@ public DataExport create(CreateDataExportRequest request) { * */ public DataExport create(CreateDataExportRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("export/content/data") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataExport.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.create(request, requestOptions).body(); } /** @@ -114,7 +77,7 @@ public DataExport create(CreateDataExportRequest request, RequestOptions request * */ public DataExport find(FindDataExportRequest request) { - return find(request, null); + return this.rawClient.find(request).body(); } /** @@ -126,77 +89,21 @@ public DataExport find(FindDataExportRequest request) { * */ public DataExport find(FindDataExportRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("export/content/data") - .addPathSegment(request.getJobIdentifier()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataExport.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.find(request, requestOptions).body(); } /** * You can cancel your job */ public DataExport cancel(CancelDataExportRequest request) { - return cancel(request, null); + return this.rawClient.cancel(request).body(); } /** * You can cancel your job */ public DataExport cancel(CancelDataExportRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("export/cancel") - .addPathSegment(request.getJobIdentifier()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("POST", RequestBody.create("", null)) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataExport.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.cancel(request, requestOptions).body(); } /** @@ -208,7 +115,7 @@ public DataExport cancel(CancelDataExportRequest request, RequestOptions request * */ public void download(DownloadDataExportRequest request) { - download(request, null); + this.rawClient.download(request).body(); } /** @@ -220,32 +127,6 @@ public void download(DownloadDataExportRequest request) { * */ public void download(DownloadDataExportRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("download/content/data") - .addPathSegment(request.getJobIdentifier()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + this.rawClient.download(request, requestOptions).body(); } } diff --git a/src/main/java/com/intercom/api/resources/dataexport/RawDataExportClient.java b/src/main/java/com/intercom/api/resources/dataexport/RawDataExportClient.java new file mode 100644 index 0000000..701b488 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/dataexport/RawDataExportClient.java @@ -0,0 +1,259 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.dataexport; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.resources.dataexport.requests.CancelDataExportRequest; +import com.intercom.api.resources.dataexport.requests.CreateDataExportRequest; +import com.intercom.api.resources.dataexport.requests.DownloadDataExportRequest; +import com.intercom.api.resources.dataexport.requests.FindDataExportRequest; +import com.intercom.api.resources.dataexport.types.DataExport; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawDataExportClient { + protected final ClientOptions clientOptions; + + public RawDataExportClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * To create your export job, you need to send a POST request to the export endpoint https://api.intercom.io/export/content/data. + *

The only parameters you need to provide are the range of dates that you want exported.

+ *
+ *

🚧 Limit of one active job

+ *

You can only have one active job per workspace. You will receive a HTTP status code of 429 with the message Exceeded rate limit of 1 pending message data export jobs if you attempt to create a second concurrent job.

+ *
+ *
+ *

❗️ Updated_at not included

+ *

It should be noted that the timeframe only includes messages sent during the time period and not messages that were only updated during this period. For example, if a message was updated yesterday but sent two days ago, you would need to set the created_at_after date before the message was sent to include that in your retrieval job.

+ *
+ *
+ *

📘 Date ranges are inclusive

+ *

Requesting data for 2018-06-01 until 2018-06-30 will get all data for those days including those specified - e.g. 2018-06-01 00:00:00 until 2018-06-30 23:59:99.

+ *
+ */ + public IntercomHttpResponse create(CreateDataExportRequest request) { + return create(request, null); + } + + /** + * To create your export job, you need to send a POST request to the export endpoint https://api.intercom.io/export/content/data. + *

The only parameters you need to provide are the range of dates that you want exported.

+ *
+ *

🚧 Limit of one active job

+ *

You can only have one active job per workspace. You will receive a HTTP status code of 429 with the message Exceeded rate limit of 1 pending message data export jobs if you attempt to create a second concurrent job.

+ *
+ *
+ *

❗️ Updated_at not included

+ *

It should be noted that the timeframe only includes messages sent during the time period and not messages that were only updated during this period. For example, if a message was updated yesterday but sent two days ago, you would need to set the created_at_after date before the message was sent to include that in your retrieval job.

+ *
+ *
+ *

📘 Date ranges are inclusive

+ *

Requesting data for 2018-06-01 until 2018-06-30 will get all data for those days including those specified - e.g. 2018-06-01 00:00:00 until 2018-06-30 23:59:99.

+ *
+ */ + public IntercomHttpResponse create(CreateDataExportRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("export/content/data") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataExport.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can view the status of your job by sending a GET request to the URL + * https://api.intercom.io/export/content/data/{job_identifier} - the {job_identifier} is the value returned in the response when you first created the export job. More on it can be seen in the Export Job Model. + *
+ *

🚧 Jobs expire after two days + * All jobs that have completed processing (and are thus available to download from the provided URL) will have an expiry limit of two days from when the export ob completed. After this, the data will no longer be available.

+ *
+ */ + public IntercomHttpResponse find(FindDataExportRequest request) { + return find(request, null); + } + + /** + * You can view the status of your job by sending a GET request to the URL + * https://api.intercom.io/export/content/data/{job_identifier} - the {job_identifier} is the value returned in the response when you first created the export job. More on it can be seen in the Export Job Model. + *
+ *

🚧 Jobs expire after two days + * All jobs that have completed processing (and are thus available to download from the provided URL) will have an expiry limit of two days from when the export ob completed. After this, the data will no longer be available.

+ *
+ */ + public IntercomHttpResponse find(FindDataExportRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("export/content/data") + .addPathSegment(request.getJobIdentifier()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataExport.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can cancel your job + */ + public IntercomHttpResponse cancel(CancelDataExportRequest request) { + return cancel(request, null); + } + + /** + * You can cancel your job + */ + public IntercomHttpResponse cancel(CancelDataExportRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("export/cancel") + .addPathSegment(request.getJobIdentifier()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("POST", RequestBody.create("", null)) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataExport.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * When a job has a status of complete, and thus a filled download_url, you can download your data by hitting that provided URL, formatted like so: https://api.intercom.io/download/content/data/xyz1234. + *

Your exported message data will be streamed continuously back down to you in a gzipped CSV format.

+ *
+ *

📘 Octet header required

+ *

You will have to specify the header Accept: application/octet-stream when hitting this endpoint.

+ *
+ */ + public IntercomHttpResponse download(DownloadDataExportRequest request) { + return download(request, null); + } + + /** + * When a job has a status of complete, and thus a filled download_url, you can download your data by hitting that provided URL, formatted like so: https://api.intercom.io/download/content/data/xyz1234. + *

Your exported message data will be streamed continuously back down to you in a gzipped CSV format.

+ *
+ *

📘 Octet header required

+ *

You will have to specify the header Accept: application/octet-stream when hitting this endpoint.

+ *
+ */ + public IntercomHttpResponse download(DownloadDataExportRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("download/content/data") + .addPathSegment(request.getJobIdentifier()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>(null, response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/intercom/api/resources/events/AsyncEventsClient.java b/src/main/java/com/intercom/api/resources/events/AsyncEventsClient.java index 8ff61c6..b1e060e 100644 --- a/src/main/java/com/intercom/api/resources/events/AsyncEventsClient.java +++ b/src/main/java/com/intercom/api/resources/events/AsyncEventsClient.java @@ -3,38 +3,29 @@ */ package com.intercom.api.resources.events; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; -import com.intercom.api.core.QueryStringMapper; import com.intercom.api.core.RequestOptions; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.events.requests.ListEventSummariesRequest; import com.intercom.api.resources.events.requests.ListEventsRequest; import com.intercom.api.types.CreateDataEventRequest; import com.intercom.api.types.DataEventSummary; -import com.intercom.api.types.Error; -import java.io.IOException; import java.util.concurrent.CompletableFuture; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; public class AsyncEventsClient { protected final ClientOptions clientOptions; + private final AsyncRawEventsClient rawClient; + public AsyncEventsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new AsyncRawEventsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawEventsClient withRawResponse() { + return this.rawClient; } /** @@ -52,7 +43,7 @@ public AsyncEventsClient(ClientOptions clientOptions) { *

You can optionally define the result page size as well with the per_page parameter.

*/ public CompletableFuture list(ListEventsRequest request) { - return list(request, null); + return this.rawClient.list(request).thenApply(response -> response.body()); } /** @@ -70,77 +61,7 @@ public CompletableFuture list(ListEventsRequest request) { *

You can optionally define the result page size as well with the per_page parameter.

*/ public CompletableFuture list(ListEventsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("events"); - if (request.getUserId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "user_id", request.getUserId().get(), false); - } - if (request.getIntercomUserId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "intercom_user_id", request.getIntercomUserId().get(), false); - } - if (request.getEmail().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "email", request.getEmail().get(), false); - } - QueryStringMapper.addQueryParameter(httpUrl, "type", request.getType(), false); - if (request.getSummary().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "summary", request.getSummary().get().toString(), false); - } - if (request.getPerPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "per_page", request.getPerPage().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataEventSummary.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.list(request, requestOptions).thenApply(response -> response.body()); } /** @@ -177,7 +98,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { * */ public CompletableFuture create(CreateDataEventRequest request) { - return create(request, null); + return this.rawClient.create(request).thenApply(response -> response.body()); } /** @@ -214,139 +135,27 @@ public CompletableFuture create(CreateDataEventRequest request) { * */ public CompletableFuture create(CreateDataEventRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("events") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(null); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.create(request, requestOptions).thenApply(response -> response.body()); } /** * Create event summaries for a user. Event summaries are used to track the number of times an event has occurred, the first time it occurred and the last time it occurred. */ public CompletableFuture summaries() { - return summaries(ListEventSummariesRequest.builder().build()); + return this.rawClient.summaries().thenApply(response -> response.body()); } /** * Create event summaries for a user. Event summaries are used to track the number of times an event has occurred, the first time it occurred and the last time it occurred. */ public CompletableFuture summaries(ListEventSummariesRequest request) { - return summaries(request, null); + return this.rawClient.summaries(request).thenApply(response -> response.body()); } /** * Create event summaries for a user. Event summaries are used to track the number of times an event has occurred, the first time it occurred and the last time it occurred. */ public CompletableFuture summaries(ListEventSummariesRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("events/summaries") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(null); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.summaries(request, requestOptions).thenApply(response -> response.body()); } } diff --git a/src/main/java/com/intercom/api/resources/events/AsyncRawEventsClient.java b/src/main/java/com/intercom/api/resources/events/AsyncRawEventsClient.java new file mode 100644 index 0000000..b30e691 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/events/AsyncRawEventsClient.java @@ -0,0 +1,360 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.events; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.QueryStringMapper; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.events.requests.ListEventSummariesRequest; +import com.intercom.api.resources.events.requests.ListEventsRequest; +import com.intercom.api.types.CreateDataEventRequest; +import com.intercom.api.types.DataEventSummary; +import com.intercom.api.types.Error; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawEventsClient { + protected final ClientOptions clientOptions; + + public AsyncRawEventsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + *
+ * 🚧 + *

Please note that you can only 'list' events that are less than 90 days old. Event counts and summaries will still include your events older than 90 days but you cannot 'list' these events individually if they are older than 90 days

+ *
+ *

The events belonging to a customer can be listed by sending a GET request to https://api.intercom.io/events with a user or lead identifier along with a type parameter. The identifier parameter can be one of user_id, email or intercom_user_id. The type parameter value must be user.

+ *
    + *
  • https://api.intercom.io/events?type=user&user_id={user_id}
  • + *
  • https://api.intercom.io/events?type=user&email={email}
  • + *
  • https://api.intercom.io/events?type=user&intercom_user_id={id} (this call can be used to list leads)
  • + *
+ *

The email parameter value should be url encoded when sending.

+ *

You can optionally define the result page size as well with the per_page parameter.

+ */ + public CompletableFuture> list(ListEventsRequest request) { + return list(request, null); + } + + /** + *
+ * 🚧 + *

Please note that you can only 'list' events that are less than 90 days old. Event counts and summaries will still include your events older than 90 days but you cannot 'list' these events individually if they are older than 90 days

+ *
+ *

The events belonging to a customer can be listed by sending a GET request to https://api.intercom.io/events with a user or lead identifier along with a type parameter. The identifier parameter can be one of user_id, email or intercom_user_id. The type parameter value must be user.

+ *
    + *
  • https://api.intercom.io/events?type=user&user_id={user_id}
  • + *
  • https://api.intercom.io/events?type=user&email={email}
  • + *
  • https://api.intercom.io/events?type=user&intercom_user_id={id} (this call can be used to list leads)
  • + *
+ *

The email parameter value should be url encoded when sending.

+ *

You can optionally define the result page size as well with the per_page parameter.

+ */ + public CompletableFuture> list( + ListEventsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("events"); + if (request.getUserId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "user_id", request.getUserId().get(), false); + } + if (request.getIntercomUserId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "intercom_user_id", request.getIntercomUserId().get(), false); + } + if (request.getEmail().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "email", request.getEmail().get(), false); + } + QueryStringMapper.addQueryParameter(httpUrl, "type", request.getType(), false); + if (request.getSummary().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "summary", request.getSummary().get().toString(), false); + } + if (request.getPerPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "per_page", request.getPerPage().get().toString(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataEventSummary.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You will need an Access Token that has write permissions to send Events. Once you have a key you can submit events via POST to the Events resource, which is located at https://api.intercom.io/events, or you can send events using one of the client libraries. When working with the HTTP API directly a client should send the event with a Content-Type of application/json. + *

When using the JavaScript API, adding the code to your app makes the Events API available. Once added, you can submit an event using the trackEvent method. This will associate the event with the Lead or currently logged-in user or logged-out visitor/lead and send it to Intercom. The final parameter is a map that can be used to send optional metadata about the event.

+ *

With the Ruby client you pass a hash describing the event to Intercom::Event.create, or call the track_user method directly on the current user object (e.g. user.track_event).

+ *

NB: For the JSON object types, please note that we do not currently support nested JSON structure.

+ *

| Type | Description | Example | + * | :-------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------- | + * | String | The value is a JSON String | "source":"desktop" | + * | Number | The value is a JSON Number | "load": 3.67 | + * | Date | The key ends with the String _date and the value is a Unix timestamp, assumed to be in the UTC timezone. | "contact_date": 1392036272 | + * | Link | The value is a HTTP or HTTPS URI. | "article": "https://example.org/ab1de.html" | + * | Rich Link | The value is a JSON object that contains url and value keys. | "article": {"url": "https://example.org/ab1de.html", "value":"the dude abides"} | + * | Monetary Amount | The value is a JSON object that contains amount and currency keys. The amount key is a positive integer representing the amount in cents. The price in the example to the right denotes €349.99. | "price": {"amount": 34999, "currency": "eur"} |

+ *

Lead Events

+ *

When submitting events for Leads, you will need to specify the Lead's id.

+ *

Metadata behaviour

+ *
    + *
  • We currently limit the number of tracked metadata keys to 10 per event. Once the quota is reached, we ignore any further keys we receive. The first 10 metadata keys are determined by the order in which they are sent in with the event.
  • + *
  • It is not possible to change the metadata keys once the event has been sent. A new event will need to be created with the new keys and you can archive the old one.
  • + *
  • There might be up to 24 hrs delay when you send a new metadata for an existing event.
  • + *
+ *

Event de-duplication

+ *

The API may detect and ignore duplicate events. Each event is uniquely identified as a combination of the following data - the Workspace identifier, the Contact external identifier, the Data Event name and the Data Event created time. As a result, it is strongly recommended to send a second granularity Unix timestamp in the created_at field.

+ *

Duplicated events are responded to using the normal 202 Accepted code - an error is not thrown, however repeat requests will be counted against any rate limit that is in place.

+ *

HTTP API Responses

+ *
    + *
  • Successful responses to submitted events return 202 Accepted with an empty body.
  • + *
  • Unauthorised access will be rejected with a 401 Unauthorized or 403 Forbidden response code.
  • + *
  • Events sent about users that cannot be found will return a 404 Not Found.
  • + *
  • Event lists containing duplicate events will have those duplicates ignored.
  • + *
  • Server errors will return a 500 response code and may contain an error message in the body.
  • + *
+ */ + public CompletableFuture> create(CreateDataEventRequest request) { + return create(request, null); + } + + /** + * You will need an Access Token that has write permissions to send Events. Once you have a key you can submit events via POST to the Events resource, which is located at https://api.intercom.io/events, or you can send events using one of the client libraries. When working with the HTTP API directly a client should send the event with a Content-Type of application/json. + *

When using the JavaScript API, adding the code to your app makes the Events API available. Once added, you can submit an event using the trackEvent method. This will associate the event with the Lead or currently logged-in user or logged-out visitor/lead and send it to Intercom. The final parameter is a map that can be used to send optional metadata about the event.

+ *

With the Ruby client you pass a hash describing the event to Intercom::Event.create, or call the track_user method directly on the current user object (e.g. user.track_event).

+ *

NB: For the JSON object types, please note that we do not currently support nested JSON structure.

+ *

| Type | Description | Example | + * | :-------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------- | + * | String | The value is a JSON String | "source":"desktop" | + * | Number | The value is a JSON Number | "load": 3.67 | + * | Date | The key ends with the String _date and the value is a Unix timestamp, assumed to be in the UTC timezone. | "contact_date": 1392036272 | + * | Link | The value is a HTTP or HTTPS URI. | "article": "https://example.org/ab1de.html" | + * | Rich Link | The value is a JSON object that contains url and value keys. | "article": {"url": "https://example.org/ab1de.html", "value":"the dude abides"} | + * | Monetary Amount | The value is a JSON object that contains amount and currency keys. The amount key is a positive integer representing the amount in cents. The price in the example to the right denotes €349.99. | "price": {"amount": 34999, "currency": "eur"} |

+ *

Lead Events

+ *

When submitting events for Leads, you will need to specify the Lead's id.

+ *

Metadata behaviour

+ *
    + *
  • We currently limit the number of tracked metadata keys to 10 per event. Once the quota is reached, we ignore any further keys we receive. The first 10 metadata keys are determined by the order in which they are sent in with the event.
  • + *
  • It is not possible to change the metadata keys once the event has been sent. A new event will need to be created with the new keys and you can archive the old one.
  • + *
  • There might be up to 24 hrs delay when you send a new metadata for an existing event.
  • + *
+ *

Event de-duplication

+ *

The API may detect and ignore duplicate events. Each event is uniquely identified as a combination of the following data - the Workspace identifier, the Contact external identifier, the Data Event name and the Data Event created time. As a result, it is strongly recommended to send a second granularity Unix timestamp in the created_at field.

+ *

Duplicated events are responded to using the normal 202 Accepted code - an error is not thrown, however repeat requests will be counted against any rate limit that is in place.

+ *

HTTP API Responses

+ *
    + *
  • Successful responses to submitted events return 202 Accepted with an empty body.
  • + *
  • Unauthorised access will be rejected with a 401 Unauthorized or 403 Forbidden response code.
  • + *
  • Events sent about users that cannot be found will return a 404 Not Found.
  • + *
  • Event lists containing duplicate events will have those duplicates ignored.
  • + *
  • Server errors will return a 500 response code and may contain an error message in the body.
  • + *
+ */ + public CompletableFuture> create( + CreateDataEventRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("events") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>(null, response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Create event summaries for a user. Event summaries are used to track the number of times an event has occurred, the first time it occurred and the last time it occurred. + */ + public CompletableFuture> summaries() { + return summaries(ListEventSummariesRequest.builder().build()); + } + + /** + * Create event summaries for a user. Event summaries are used to track the number of times an event has occurred, the first time it occurred and the last time it occurred. + */ + public CompletableFuture> summaries(ListEventSummariesRequest request) { + return summaries(request, null); + } + + /** + * Create event summaries for a user. Event summaries are used to track the number of times an event has occurred, the first time it occurred and the last time it occurred. + */ + public CompletableFuture> summaries( + ListEventSummariesRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("events/summaries") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>(null, response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/intercom/api/resources/events/EventsClient.java b/src/main/java/com/intercom/api/resources/events/EventsClient.java index fe42161..79318e6 100644 --- a/src/main/java/com/intercom/api/resources/events/EventsClient.java +++ b/src/main/java/com/intercom/api/resources/events/EventsClient.java @@ -3,34 +3,28 @@ */ package com.intercom.api.resources.events; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; -import com.intercom.api.core.QueryStringMapper; import com.intercom.api.core.RequestOptions; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.events.requests.ListEventSummariesRequest; import com.intercom.api.resources.events.requests.ListEventsRequest; import com.intercom.api.types.CreateDataEventRequest; import com.intercom.api.types.DataEventSummary; -import com.intercom.api.types.Error; -import java.io.IOException; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; public class EventsClient { protected final ClientOptions clientOptions; + private final RawEventsClient rawClient; + public EventsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawEventsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawEventsClient withRawResponse() { + return this.rawClient; } /** @@ -48,7 +42,7 @@ public EventsClient(ClientOptions clientOptions) { *

You can optionally define the result page size as well with the per_page parameter.

*/ public DataEventSummary list(ListEventsRequest request) { - return list(request, null); + return this.rawClient.list(request).body(); } /** @@ -66,61 +60,7 @@ public DataEventSummary list(ListEventsRequest request) { *

You can optionally define the result page size as well with the per_page parameter.

*/ public DataEventSummary list(ListEventsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("events"); - if (request.getUserId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "user_id", request.getUserId().get(), false); - } - if (request.getIntercomUserId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "intercom_user_id", request.getIntercomUserId().get(), false); - } - if (request.getEmail().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "email", request.getEmail().get(), false); - } - QueryStringMapper.addQueryParameter(httpUrl, "type", request.getType(), false); - if (request.getSummary().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "summary", request.getSummary().get().toString(), false); - } - if (request.getPerPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "per_page", request.getPerPage().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataEventSummary.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.list(request, requestOptions).body(); } /** @@ -157,7 +97,7 @@ public DataEventSummary list(ListEventsRequest request, RequestOptions requestOp * */ public void create(CreateDataEventRequest request) { - create(request, null); + this.rawClient.create(request).body(); } /** @@ -194,109 +134,27 @@ public void create(CreateDataEventRequest request) { * */ public void create(CreateDataEventRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("events") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + this.rawClient.create(request, requestOptions).body(); } /** * Create event summaries for a user. Event summaries are used to track the number of times an event has occurred, the first time it occurred and the last time it occurred. */ public void summaries() { - summaries(ListEventSummariesRequest.builder().build()); + this.rawClient.summaries().body(); } /** * Create event summaries for a user. Event summaries are used to track the number of times an event has occurred, the first time it occurred and the last time it occurred. */ public void summaries(ListEventSummariesRequest request) { - summaries(request, null); + this.rawClient.summaries(request).body(); } /** * Create event summaries for a user. Event summaries are used to track the number of times an event has occurred, the first time it occurred and the last time it occurred. */ public void summaries(ListEventSummariesRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("events/summaries") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + this.rawClient.summaries(request, requestOptions).body(); } } diff --git a/src/main/java/com/intercom/api/resources/events/RawEventsClient.java b/src/main/java/com/intercom/api/resources/events/RawEventsClient.java new file mode 100644 index 0000000..edf2a4e --- /dev/null +++ b/src/main/java/com/intercom/api/resources/events/RawEventsClient.java @@ -0,0 +1,310 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.events; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.QueryStringMapper; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.events.requests.ListEventSummariesRequest; +import com.intercom.api.resources.events.requests.ListEventsRequest; +import com.intercom.api.types.CreateDataEventRequest; +import com.intercom.api.types.DataEventSummary; +import com.intercom.api.types.Error; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawEventsClient { + protected final ClientOptions clientOptions; + + public RawEventsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + *
+ * 🚧 + *

Please note that you can only 'list' events that are less than 90 days old. Event counts and summaries will still include your events older than 90 days but you cannot 'list' these events individually if they are older than 90 days

+ *
+ *

The events belonging to a customer can be listed by sending a GET request to https://api.intercom.io/events with a user or lead identifier along with a type parameter. The identifier parameter can be one of user_id, email or intercom_user_id. The type parameter value must be user.

+ *
    + *
  • https://api.intercom.io/events?type=user&user_id={user_id}
  • + *
  • https://api.intercom.io/events?type=user&email={email}
  • + *
  • https://api.intercom.io/events?type=user&intercom_user_id={id} (this call can be used to list leads)
  • + *
+ *

The email parameter value should be url encoded when sending.

+ *

You can optionally define the result page size as well with the per_page parameter.

+ */ + public IntercomHttpResponse list(ListEventsRequest request) { + return list(request, null); + } + + /** + *
+ * 🚧 + *

Please note that you can only 'list' events that are less than 90 days old. Event counts and summaries will still include your events older than 90 days but you cannot 'list' these events individually if they are older than 90 days

+ *
+ *

The events belonging to a customer can be listed by sending a GET request to https://api.intercom.io/events with a user or lead identifier along with a type parameter. The identifier parameter can be one of user_id, email or intercom_user_id. The type parameter value must be user.

+ *
    + *
  • https://api.intercom.io/events?type=user&user_id={user_id}
  • + *
  • https://api.intercom.io/events?type=user&email={email}
  • + *
  • https://api.intercom.io/events?type=user&intercom_user_id={id} (this call can be used to list leads)
  • + *
+ *

The email parameter value should be url encoded when sending.

+ *

You can optionally define the result page size as well with the per_page parameter.

+ */ + public IntercomHttpResponse list(ListEventsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("events"); + if (request.getUserId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "user_id", request.getUserId().get(), false); + } + if (request.getIntercomUserId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "intercom_user_id", request.getIntercomUserId().get(), false); + } + if (request.getEmail().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "email", request.getEmail().get(), false); + } + QueryStringMapper.addQueryParameter(httpUrl, "type", request.getType(), false); + if (request.getSummary().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "summary", request.getSummary().get().toString(), false); + } + if (request.getPerPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "per_page", request.getPerPage().get().toString(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DataEventSummary.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You will need an Access Token that has write permissions to send Events. Once you have a key you can submit events via POST to the Events resource, which is located at https://api.intercom.io/events, or you can send events using one of the client libraries. When working with the HTTP API directly a client should send the event with a Content-Type of application/json. + *

When using the JavaScript API, adding the code to your app makes the Events API available. Once added, you can submit an event using the trackEvent method. This will associate the event with the Lead or currently logged-in user or logged-out visitor/lead and send it to Intercom. The final parameter is a map that can be used to send optional metadata about the event.

+ *

With the Ruby client you pass a hash describing the event to Intercom::Event.create, or call the track_user method directly on the current user object (e.g. user.track_event).

+ *

NB: For the JSON object types, please note that we do not currently support nested JSON structure.

+ *

| Type | Description | Example | + * | :-------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------- | + * | String | The value is a JSON String | "source":"desktop" | + * | Number | The value is a JSON Number | "load": 3.67 | + * | Date | The key ends with the String _date and the value is a Unix timestamp, assumed to be in the UTC timezone. | "contact_date": 1392036272 | + * | Link | The value is a HTTP or HTTPS URI. | "article": "https://example.org/ab1de.html" | + * | Rich Link | The value is a JSON object that contains url and value keys. | "article": {"url": "https://example.org/ab1de.html", "value":"the dude abides"} | + * | Monetary Amount | The value is a JSON object that contains amount and currency keys. The amount key is a positive integer representing the amount in cents. The price in the example to the right denotes €349.99. | "price": {"amount": 34999, "currency": "eur"} |

+ *

Lead Events

+ *

When submitting events for Leads, you will need to specify the Lead's id.

+ *

Metadata behaviour

+ *
    + *
  • We currently limit the number of tracked metadata keys to 10 per event. Once the quota is reached, we ignore any further keys we receive. The first 10 metadata keys are determined by the order in which they are sent in with the event.
  • + *
  • It is not possible to change the metadata keys once the event has been sent. A new event will need to be created with the new keys and you can archive the old one.
  • + *
  • There might be up to 24 hrs delay when you send a new metadata for an existing event.
  • + *
+ *

Event de-duplication

+ *

The API may detect and ignore duplicate events. Each event is uniquely identified as a combination of the following data - the Workspace identifier, the Contact external identifier, the Data Event name and the Data Event created time. As a result, it is strongly recommended to send a second granularity Unix timestamp in the created_at field.

+ *

Duplicated events are responded to using the normal 202 Accepted code - an error is not thrown, however repeat requests will be counted against any rate limit that is in place.

+ *

HTTP API Responses

+ *
    + *
  • Successful responses to submitted events return 202 Accepted with an empty body.
  • + *
  • Unauthorised access will be rejected with a 401 Unauthorized or 403 Forbidden response code.
  • + *
  • Events sent about users that cannot be found will return a 404 Not Found.
  • + *
  • Event lists containing duplicate events will have those duplicates ignored.
  • + *
  • Server errors will return a 500 response code and may contain an error message in the body.
  • + *
+ */ + public IntercomHttpResponse create(CreateDataEventRequest request) { + return create(request, null); + } + + /** + * You will need an Access Token that has write permissions to send Events. Once you have a key you can submit events via POST to the Events resource, which is located at https://api.intercom.io/events, or you can send events using one of the client libraries. When working with the HTTP API directly a client should send the event with a Content-Type of application/json. + *

When using the JavaScript API, adding the code to your app makes the Events API available. Once added, you can submit an event using the trackEvent method. This will associate the event with the Lead or currently logged-in user or logged-out visitor/lead and send it to Intercom. The final parameter is a map that can be used to send optional metadata about the event.

+ *

With the Ruby client you pass a hash describing the event to Intercom::Event.create, or call the track_user method directly on the current user object (e.g. user.track_event).

+ *

NB: For the JSON object types, please note that we do not currently support nested JSON structure.

+ *

| Type | Description | Example | + * | :-------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------- | + * | String | The value is a JSON String | "source":"desktop" | + * | Number | The value is a JSON Number | "load": 3.67 | + * | Date | The key ends with the String _date and the value is a Unix timestamp, assumed to be in the UTC timezone. | "contact_date": 1392036272 | + * | Link | The value is a HTTP or HTTPS URI. | "article": "https://example.org/ab1de.html" | + * | Rich Link | The value is a JSON object that contains url and value keys. | "article": {"url": "https://example.org/ab1de.html", "value":"the dude abides"} | + * | Monetary Amount | The value is a JSON object that contains amount and currency keys. The amount key is a positive integer representing the amount in cents. The price in the example to the right denotes €349.99. | "price": {"amount": 34999, "currency": "eur"} |

+ *

Lead Events

+ *

When submitting events for Leads, you will need to specify the Lead's id.

+ *

Metadata behaviour

+ *
    + *
  • We currently limit the number of tracked metadata keys to 10 per event. Once the quota is reached, we ignore any further keys we receive. The first 10 metadata keys are determined by the order in which they are sent in with the event.
  • + *
  • It is not possible to change the metadata keys once the event has been sent. A new event will need to be created with the new keys and you can archive the old one.
  • + *
  • There might be up to 24 hrs delay when you send a new metadata for an existing event.
  • + *
+ *

Event de-duplication

+ *

The API may detect and ignore duplicate events. Each event is uniquely identified as a combination of the following data - the Workspace identifier, the Contact external identifier, the Data Event name and the Data Event created time. As a result, it is strongly recommended to send a second granularity Unix timestamp in the created_at field.

+ *

Duplicated events are responded to using the normal 202 Accepted code - an error is not thrown, however repeat requests will be counted against any rate limit that is in place.

+ *

HTTP API Responses

+ *
    + *
  • Successful responses to submitted events return 202 Accepted with an empty body.
  • + *
  • Unauthorised access will be rejected with a 401 Unauthorized or 403 Forbidden response code.
  • + *
  • Events sent about users that cannot be found will return a 404 Not Found.
  • + *
  • Event lists containing duplicate events will have those duplicates ignored.
  • + *
  • Server errors will return a 500 response code and may contain an error message in the body.
  • + *
+ */ + public IntercomHttpResponse create(CreateDataEventRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("events") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>(null, response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * Create event summaries for a user. Event summaries are used to track the number of times an event has occurred, the first time it occurred and the last time it occurred. + */ + public IntercomHttpResponse summaries() { + return summaries(ListEventSummariesRequest.builder().build()); + } + + /** + * Create event summaries for a user. Event summaries are used to track the number of times an event has occurred, the first time it occurred and the last time it occurred. + */ + public IntercomHttpResponse summaries(ListEventSummariesRequest request) { + return summaries(request, null); + } + + /** + * Create event summaries for a user. Event summaries are used to track the number of times an event has occurred, the first time it occurred and the last time it occurred. + */ + public IntercomHttpResponse summaries(ListEventSummariesRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("events/summaries") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>(null, response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/intercom/api/resources/helpcenters/AsyncHelpCentersClient.java b/src/main/java/com/intercom/api/resources/helpcenters/AsyncHelpCentersClient.java index 0c4aad3..546eb3a 100644 --- a/src/main/java/com/intercom/api/resources/helpcenters/AsyncHelpCentersClient.java +++ b/src/main/java/com/intercom/api/resources/helpcenters/AsyncHelpCentersClient.java @@ -3,129 +3,63 @@ */ package com.intercom.api.resources.helpcenters; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.ObjectMappers; -import com.intercom.api.core.QueryStringMapper; import com.intercom.api.core.RequestOptions; import com.intercom.api.core.Suppliers; import com.intercom.api.core.pagination.SyncPagingIterable; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.helpcenter.types.HelpCenter; -import com.intercom.api.resources.helpcenter.types.HelpCenterList; import com.intercom.api.resources.helpcenters.collections.AsyncCollectionsClient; import com.intercom.api.resources.helpcenters.requests.FindHelpCenterRequest; import com.intercom.api.resources.helpcenters.requests.ListHelpCentersRequest; -import com.intercom.api.types.Error; -import java.io.IOException; -import java.util.List; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; import java.util.function.Supplier; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; public class AsyncHelpCentersClient { protected final ClientOptions clientOptions; + private final AsyncRawHelpCentersClient rawClient; + protected final Supplier collectionsClient; public AsyncHelpCentersClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new AsyncRawHelpCentersClient(clientOptions); this.collectionsClient = Suppliers.memoize(() -> new AsyncCollectionsClient(clientOptions)); } + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawHelpCentersClient withRawResponse() { + return this.rawClient; + } + /** * You can fetch the details of a single Help Center by making a GET request to https://api.intercom.io/help_center/help_center/<id>. */ public CompletableFuture find(FindHelpCenterRequest request) { - return find(request, null); + return this.rawClient.find(request).thenApply(response -> response.body()); } /** * You can fetch the details of a single Help Center by making a GET request to https://api.intercom.io/help_center/help_center/<id>. */ public CompletableFuture find(FindHelpCenterRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("help_center/help_centers") - .addPathSegment(request.getHelpCenterId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), HelpCenter.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.find(request, requestOptions).thenApply(response -> response.body()); } /** * You can list all Help Centers by making a GET request to https://api.intercom.io/help_center/help_centers. */ public CompletableFuture> list() { - return list(ListHelpCentersRequest.builder().build()); + return this.rawClient.list().thenApply(response -> response.body()); } /** * You can list all Help Centers by making a GET request to https://api.intercom.io/help_center/help_centers. */ public CompletableFuture> list(ListHelpCentersRequest request) { - return list(request, null); + return this.rawClient.list(request).thenApply(response -> response.body()); } /** @@ -133,78 +67,7 @@ public CompletableFuture> list(ListHelpCentersReq */ public CompletableFuture> list( ListHelpCentersRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("help_center/help_centers"); - if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getPerPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "per_page", request.getPerPage().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - HelpCenterList parsedResponse = - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), HelpCenterList.class); - int newPageNumber = - request.getPage().map(page -> page + 1).orElse(1); - ListHelpCentersRequest nextRequest = ListHelpCentersRequest.builder() - .from(request) - .page(newPageNumber) - .build(); - List result = parsedResponse.getData(); - future.complete(new SyncPagingIterable(true, result, () -> { - try { - return list(nextRequest, requestOptions).get(); - } catch (InterruptedException | ExecutionException e) { - throw new RuntimeException(e); - } - })); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.list(request, requestOptions).thenApply(response -> response.body()); } public AsyncCollectionsClient collections() { diff --git a/src/main/java/com/intercom/api/resources/helpcenters/AsyncRawHelpCentersClient.java b/src/main/java/com/intercom/api/resources/helpcenters/AsyncRawHelpCentersClient.java new file mode 100644 index 0000000..ce82a33 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/helpcenters/AsyncRawHelpCentersClient.java @@ -0,0 +1,216 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.helpcenters; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.QueryStringMapper; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.core.pagination.SyncPagingIterable; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.helpcenter.types.HelpCenter; +import com.intercom.api.resources.helpcenter.types.HelpCenterList; +import com.intercom.api.resources.helpcenters.requests.FindHelpCenterRequest; +import com.intercom.api.resources.helpcenters.requests.ListHelpCentersRequest; +import com.intercom.api.types.Error; +import java.io.IOException; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawHelpCentersClient { + protected final ClientOptions clientOptions; + + public AsyncRawHelpCentersClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can fetch the details of a single Help Center by making a GET request to https://api.intercom.io/help_center/help_center/<id>. + */ + public CompletableFuture> find(FindHelpCenterRequest request) { + return find(request, null); + } + + /** + * You can fetch the details of a single Help Center by making a GET request to https://api.intercom.io/help_center/help_center/<id>. + */ + public CompletableFuture> find( + FindHelpCenterRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("help_center/help_centers") + .addPathSegment(request.getHelpCenterId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), HelpCenter.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can list all Help Centers by making a GET request to https://api.intercom.io/help_center/help_centers. + */ + public CompletableFuture>> list() { + return list(ListHelpCentersRequest.builder().build()); + } + + /** + * You can list all Help Centers by making a GET request to https://api.intercom.io/help_center/help_centers. + */ + public CompletableFuture>> list( + ListHelpCentersRequest request) { + return list(request, null); + } + + /** + * You can list all Help Centers by making a GET request to https://api.intercom.io/help_center/help_centers. + */ + public CompletableFuture>> list( + ListHelpCentersRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("help_center/help_centers"); + if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "page", request.getPage().get().toString(), false); + } + if (request.getPerPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "per_page", request.getPerPage().get().toString(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture>> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + HelpCenterList parsedResponse = + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), HelpCenterList.class); + int newPageNumber = + request.getPage().map(page -> page + 1).orElse(1); + ListHelpCentersRequest nextRequest = ListHelpCentersRequest.builder() + .from(request) + .page(newPageNumber) + .build(); + List result = parsedResponse.getData(); + future.complete(new IntercomHttpResponse<>( + new SyncPagingIterable(true, result, () -> { + try { + return list(nextRequest, requestOptions) + .get() + .body(); + } catch (InterruptedException | ExecutionException e) { + throw new RuntimeException(e); + } + }), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/intercom/api/resources/helpcenters/HelpCentersClient.java b/src/main/java/com/intercom/api/resources/helpcenters/HelpCentersClient.java index 43a4c81..71cac18 100644 --- a/src/main/java/com/intercom/api/resources/helpcenters/HelpCentersClient.java +++ b/src/main/java/com/intercom/api/resources/helpcenters/HelpCentersClient.java @@ -3,164 +3,69 @@ */ package com.intercom.api.resources.helpcenters; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.ObjectMappers; -import com.intercom.api.core.QueryStringMapper; import com.intercom.api.core.RequestOptions; import com.intercom.api.core.Suppliers; import com.intercom.api.core.pagination.SyncPagingIterable; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.helpcenter.types.HelpCenter; -import com.intercom.api.resources.helpcenter.types.HelpCenterList; import com.intercom.api.resources.helpcenters.collections.CollectionsClient; import com.intercom.api.resources.helpcenters.requests.FindHelpCenterRequest; import com.intercom.api.resources.helpcenters.requests.ListHelpCentersRequest; -import com.intercom.api.types.Error; -import java.io.IOException; -import java.util.List; import java.util.function.Supplier; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; public class HelpCentersClient { protected final ClientOptions clientOptions; + private final RawHelpCentersClient rawClient; + protected final Supplier collectionsClient; public HelpCentersClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawHelpCentersClient(clientOptions); this.collectionsClient = Suppliers.memoize(() -> new CollectionsClient(clientOptions)); } + /** + * Get responses with HTTP metadata like headers + */ + public RawHelpCentersClient withRawResponse() { + return this.rawClient; + } + /** * You can fetch the details of a single Help Center by making a GET request to https://api.intercom.io/help_center/help_center/<id>. */ public HelpCenter find(FindHelpCenterRequest request) { - return find(request, null); + return this.rawClient.find(request).body(); } /** * You can fetch the details of a single Help Center by making a GET request to https://api.intercom.io/help_center/help_center/<id>. */ public HelpCenter find(FindHelpCenterRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("help_center/help_centers") - .addPathSegment(request.getHelpCenterId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), HelpCenter.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.find(request, requestOptions).body(); } /** * You can list all Help Centers by making a GET request to https://api.intercom.io/help_center/help_centers. */ public SyncPagingIterable list() { - return list(ListHelpCentersRequest.builder().build()); + return this.rawClient.list().body(); } /** * You can list all Help Centers by making a GET request to https://api.intercom.io/help_center/help_centers. */ public SyncPagingIterable list(ListHelpCentersRequest request) { - return list(request, null); + return this.rawClient.list(request).body(); } /** * You can list all Help Centers by making a GET request to https://api.intercom.io/help_center/help_centers. */ public SyncPagingIterable list(ListHelpCentersRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("help_center/help_centers"); - if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getPerPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "per_page", request.getPerPage().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - HelpCenterList parsedResponse = - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), HelpCenterList.class); - int newPageNumber = request.getPage().map(page -> page + 1).orElse(1); - ListHelpCentersRequest nextRequest = ListHelpCentersRequest.builder() - .from(request) - .page(newPageNumber) - .build(); - List result = parsedResponse.getData(); - return new SyncPagingIterable(true, result, () -> list(nextRequest, requestOptions)); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.list(request, requestOptions).body(); } public CollectionsClient collections() { diff --git a/src/main/java/com/intercom/api/resources/helpcenters/RawHelpCentersClient.java b/src/main/java/com/intercom/api/resources/helpcenters/RawHelpCentersClient.java new file mode 100644 index 0000000..3c24161 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/helpcenters/RawHelpCentersClient.java @@ -0,0 +1,169 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.helpcenters; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.QueryStringMapper; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.core.pagination.SyncPagingIterable; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.helpcenter.types.HelpCenter; +import com.intercom.api.resources.helpcenter.types.HelpCenterList; +import com.intercom.api.resources.helpcenters.requests.FindHelpCenterRequest; +import com.intercom.api.resources.helpcenters.requests.ListHelpCentersRequest; +import com.intercom.api.types.Error; +import java.io.IOException; +import java.util.List; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawHelpCentersClient { + protected final ClientOptions clientOptions; + + public RawHelpCentersClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can fetch the details of a single Help Center by making a GET request to https://api.intercom.io/help_center/help_center/<id>. + */ + public IntercomHttpResponse find(FindHelpCenterRequest request) { + return find(request, null); + } + + /** + * You can fetch the details of a single Help Center by making a GET request to https://api.intercom.io/help_center/help_center/<id>. + */ + public IntercomHttpResponse find(FindHelpCenterRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("help_center/help_centers") + .addPathSegment(request.getHelpCenterId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), HelpCenter.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can list all Help Centers by making a GET request to https://api.intercom.io/help_center/help_centers. + */ + public IntercomHttpResponse> list() { + return list(ListHelpCentersRequest.builder().build()); + } + + /** + * You can list all Help Centers by making a GET request to https://api.intercom.io/help_center/help_centers. + */ + public IntercomHttpResponse> list(ListHelpCentersRequest request) { + return list(request, null); + } + + /** + * You can list all Help Centers by making a GET request to https://api.intercom.io/help_center/help_centers. + */ + public IntercomHttpResponse> list( + ListHelpCentersRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("help_center/help_centers"); + if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "page", request.getPage().get().toString(), false); + } + if (request.getPerPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "per_page", request.getPerPage().get().toString(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + HelpCenterList parsedResponse = + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), HelpCenterList.class); + int newPageNumber = request.getPage().map(page -> page + 1).orElse(1); + ListHelpCentersRequest nextRequest = ListHelpCentersRequest.builder() + .from(request) + .page(newPageNumber) + .build(); + List result = parsedResponse.getData(); + return new IntercomHttpResponse<>( + new SyncPagingIterable(true, result, () -> list(nextRequest, requestOptions) + .body()), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/intercom/api/resources/helpcenters/collections/AsyncCollectionsClient.java b/src/main/java/com/intercom/api/resources/helpcenters/collections/AsyncCollectionsClient.java index 26b01ce..8ec144f 100644 --- a/src/main/java/com/intercom/api/resources/helpcenters/collections/AsyncCollectionsClient.java +++ b/src/main/java/com/intercom/api/resources/helpcenters/collections/AsyncCollectionsClient.java @@ -3,47 +3,33 @@ */ package com.intercom.api.resources.helpcenters.collections; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; -import com.intercom.api.core.QueryStringMapper; import com.intercom.api.core.RequestOptions; import com.intercom.api.core.pagination.SyncPagingIterable; -import com.intercom.api.errors.BadRequestError; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.helpcenter.types.Collection; import com.intercom.api.resources.helpcenters.collections.requests.CreateCollectionRequest; import com.intercom.api.resources.helpcenters.collections.requests.DeleteCollectionRequest; import com.intercom.api.resources.helpcenters.collections.requests.FindCollectionRequest; import com.intercom.api.resources.helpcenters.collections.requests.ListCollectionsRequest; import com.intercom.api.resources.helpcenters.collections.requests.UpdateCollectionRequest; -import com.intercom.api.types.CollectionList; import com.intercom.api.types.DeletedCollectionObject; -import com.intercom.api.types.Error; -import java.io.IOException; -import java.util.List; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; public class AsyncCollectionsClient { protected final ClientOptions clientOptions; + private final AsyncRawCollectionsClient rawClient; + public AsyncCollectionsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new AsyncRawCollectionsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawCollectionsClient withRawResponse() { + return this.rawClient; } /** @@ -51,7 +37,7 @@ public AsyncCollectionsClient(ClientOptions clientOptions) { *

Collections will be returned in descending order on the updated_at attribute. This means if you need to iterate through results then we'll show the most recently updated collections first.

*/ public CompletableFuture> list() { - return list(ListCollectionsRequest.builder().build()); + return this.rawClient.list().thenApply(response -> response.body()); } /** @@ -59,7 +45,7 @@ public CompletableFuture> list() { *

Collections will be returned in descending order on the updated_at attribute. This means if you need to iterate through results then we'll show the most recently updated collections first.

*/ public CompletableFuture> list(ListCollectionsRequest request) { - return list(request, null); + return this.rawClient.list(request).thenApply(response -> response.body()); } /** @@ -68,305 +54,56 @@ public CompletableFuture> list(ListCollectionsReq */ public CompletableFuture> list( ListCollectionsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("help_center/collections"); - if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getPerPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "per_page", request.getPerPage().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - CollectionList parsedResponse = - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CollectionList.class); - int newPageNumber = - request.getPage().map(page -> page + 1).orElse(1); - ListCollectionsRequest nextRequest = ListCollectionsRequest.builder() - .from(request) - .page(newPageNumber) - .build(); - List result = parsedResponse.getData(); - future.complete(new SyncPagingIterable(true, result, () -> { - try { - return list(nextRequest, requestOptions).get(); - } catch (InterruptedException | ExecutionException e) { - throw new RuntimeException(e); - } - })); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.list(request, requestOptions).thenApply(response -> response.body()); } /** * You can create a new collection by making a POST request to https://api.intercom.io/help_center/collections. */ public CompletableFuture create(CreateCollectionRequest request) { - return create(request, null); + return this.rawClient.create(request).thenApply(response -> response.body()); } /** * You can create a new collection by making a POST request to https://api.intercom.io/help_center/collections. */ public CompletableFuture create(CreateCollectionRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("help_center/collections") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Collection.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.create(request, requestOptions).thenApply(response -> response.body()); } /** * You can fetch the details of a single collection by making a GET request to https://api.intercom.io/help_center/collections/<id>. */ public CompletableFuture find(FindCollectionRequest request) { - return find(request, null); + return this.rawClient.find(request).thenApply(response -> response.body()); } /** * You can fetch the details of a single collection by making a GET request to https://api.intercom.io/help_center/collections/<id>. */ public CompletableFuture find(FindCollectionRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("help_center/collections") - .addPathSegment(request.getCollectionId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Collection.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.find(request, requestOptions).thenApply(response -> response.body()); } /** * You can update the details of a single collection by making a PUT request to https://api.intercom.io/collections/<id>. */ public CompletableFuture update(UpdateCollectionRequest request) { - return update(request, null); + return this.rawClient.update(request).thenApply(response -> response.body()); } /** * You can update the details of a single collection by making a PUT request to https://api.intercom.io/collections/<id>. */ public CompletableFuture update(UpdateCollectionRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("help_center/collections") - .addPathSegment(request.getCollectionId()) - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PUT", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Collection.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.update(request, requestOptions).thenApply(response -> response.body()); } /** * You can delete a single collection by making a DELETE request to https://api.intercom.io/collections/<id>. */ public CompletableFuture delete(DeleteCollectionRequest request) { - return delete(request, null); + return this.rawClient.delete(request).thenApply(response -> response.body()); } /** @@ -374,62 +111,6 @@ public CompletableFuture delete(DeleteCollectionRequest */ public CompletableFuture delete( DeleteCollectionRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("help_center/collections") - .addPathSegment(request.getCollectionId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), DeletedCollectionObject.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.delete(request, requestOptions).thenApply(response -> response.body()); } } diff --git a/src/main/java/com/intercom/api/resources/helpcenters/collections/AsyncRawCollectionsClient.java b/src/main/java/com/intercom/api/resources/helpcenters/collections/AsyncRawCollectionsClient.java new file mode 100644 index 0000000..af6a0db --- /dev/null +++ b/src/main/java/com/intercom/api/resources/helpcenters/collections/AsyncRawCollectionsClient.java @@ -0,0 +1,465 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.helpcenters.collections; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.QueryStringMapper; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.core.pagination.SyncPagingIterable; +import com.intercom.api.errors.BadRequestError; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.helpcenter.types.Collection; +import com.intercom.api.resources.helpcenters.collections.requests.CreateCollectionRequest; +import com.intercom.api.resources.helpcenters.collections.requests.DeleteCollectionRequest; +import com.intercom.api.resources.helpcenters.collections.requests.FindCollectionRequest; +import com.intercom.api.resources.helpcenters.collections.requests.ListCollectionsRequest; +import com.intercom.api.resources.helpcenters.collections.requests.UpdateCollectionRequest; +import com.intercom.api.types.CollectionList; +import com.intercom.api.types.DeletedCollectionObject; +import com.intercom.api.types.Error; +import java.io.IOException; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawCollectionsClient { + protected final ClientOptions clientOptions; + + public AsyncRawCollectionsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can fetch a list of all collections by making a GET request to https://api.intercom.io/help_center/collections. + *

Collections will be returned in descending order on the updated_at attribute. This means if you need to iterate through results then we'll show the most recently updated collections first.

+ */ + public CompletableFuture>> list() { + return list(ListCollectionsRequest.builder().build()); + } + + /** + * You can fetch a list of all collections by making a GET request to https://api.intercom.io/help_center/collections. + *

Collections will be returned in descending order on the updated_at attribute. This means if you need to iterate through results then we'll show the most recently updated collections first.

+ */ + public CompletableFuture>> list( + ListCollectionsRequest request) { + return list(request, null); + } + + /** + * You can fetch a list of all collections by making a GET request to https://api.intercom.io/help_center/collections. + *

Collections will be returned in descending order on the updated_at attribute. This means if you need to iterate through results then we'll show the most recently updated collections first.

+ */ + public CompletableFuture>> list( + ListCollectionsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("help_center/collections"); + if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "page", request.getPage().get().toString(), false); + } + if (request.getPerPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "per_page", request.getPerPage().get().toString(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture>> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + CollectionList parsedResponse = + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CollectionList.class); + int newPageNumber = + request.getPage().map(page -> page + 1).orElse(1); + ListCollectionsRequest nextRequest = ListCollectionsRequest.builder() + .from(request) + .page(newPageNumber) + .build(); + List result = parsedResponse.getData(); + future.complete(new IntercomHttpResponse<>( + new SyncPagingIterable(true, result, () -> { + try { + return list(nextRequest, requestOptions) + .get() + .body(); + } catch (InterruptedException | ExecutionException e) { + throw new RuntimeException(e); + } + }), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can create a new collection by making a POST request to https://api.intercom.io/help_center/collections. + */ + public CompletableFuture> create(CreateCollectionRequest request) { + return create(request, null); + } + + /** + * You can create a new collection by making a POST request to https://api.intercom.io/help_center/collections. + */ + public CompletableFuture> create( + CreateCollectionRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("help_center/collections") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Collection.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can fetch the details of a single collection by making a GET request to https://api.intercom.io/help_center/collections/<id>. + */ + public CompletableFuture> find(FindCollectionRequest request) { + return find(request, null); + } + + /** + * You can fetch the details of a single collection by making a GET request to https://api.intercom.io/help_center/collections/<id>. + */ + public CompletableFuture> find( + FindCollectionRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("help_center/collections") + .addPathSegment(request.getCollectionId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Collection.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can update the details of a single collection by making a PUT request to https://api.intercom.io/collections/<id>. + */ + public CompletableFuture> update(UpdateCollectionRequest request) { + return update(request, null); + } + + /** + * You can update the details of a single collection by making a PUT request to https://api.intercom.io/collections/<id>. + */ + public CompletableFuture> update( + UpdateCollectionRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("help_center/collections") + .addPathSegment(request.getCollectionId()) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Collection.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can delete a single collection by making a DELETE request to https://api.intercom.io/collections/<id>. + */ + public CompletableFuture> delete(DeleteCollectionRequest request) { + return delete(request, null); + } + + /** + * You can delete a single collection by making a DELETE request to https://api.intercom.io/collections/<id>. + */ + public CompletableFuture> delete( + DeleteCollectionRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("help_center/collections") + .addPathSegment(request.getCollectionId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), DeletedCollectionObject.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/intercom/api/resources/helpcenters/collections/CollectionsClient.java b/src/main/java/com/intercom/api/resources/helpcenters/collections/CollectionsClient.java index bfe8c74..fda987d 100644 --- a/src/main/java/com/intercom/api/resources/helpcenters/collections/CollectionsClient.java +++ b/src/main/java/com/intercom/api/resources/helpcenters/collections/CollectionsClient.java @@ -3,42 +3,32 @@ */ package com.intercom.api.resources.helpcenters.collections; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; -import com.intercom.api.core.QueryStringMapper; import com.intercom.api.core.RequestOptions; import com.intercom.api.core.pagination.SyncPagingIterable; -import com.intercom.api.errors.BadRequestError; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.helpcenter.types.Collection; import com.intercom.api.resources.helpcenters.collections.requests.CreateCollectionRequest; import com.intercom.api.resources.helpcenters.collections.requests.DeleteCollectionRequest; import com.intercom.api.resources.helpcenters.collections.requests.FindCollectionRequest; import com.intercom.api.resources.helpcenters.collections.requests.ListCollectionsRequest; import com.intercom.api.resources.helpcenters.collections.requests.UpdateCollectionRequest; -import com.intercom.api.types.CollectionList; import com.intercom.api.types.DeletedCollectionObject; -import com.intercom.api.types.Error; -import java.io.IOException; -import java.util.List; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; public class CollectionsClient { protected final ClientOptions clientOptions; + private final RawCollectionsClient rawClient; + public CollectionsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawCollectionsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawCollectionsClient withRawResponse() { + return this.rawClient; } /** @@ -46,7 +36,7 @@ public CollectionsClient(ClientOptions clientOptions) { *

Collections will be returned in descending order on the updated_at attribute. This means if you need to iterate through results then we'll show the most recently updated collections first.

*/ public SyncPagingIterable list() { - return list(ListCollectionsRequest.builder().build()); + return this.rawClient.list().body(); } /** @@ -54,7 +44,7 @@ public SyncPagingIterable list() { *

Collections will be returned in descending order on the updated_at attribute. This means if you need to iterate through results then we'll show the most recently updated collections first.

*/ public SyncPagingIterable list(ListCollectionsRequest request) { - return list(request, null); + return this.rawClient.list(request).body(); } /** @@ -62,281 +52,62 @@ public SyncPagingIterable list(ListCollectionsRequest request) { *

Collections will be returned in descending order on the updated_at attribute. This means if you need to iterate through results then we'll show the most recently updated collections first.

*/ public SyncPagingIterable list(ListCollectionsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("help_center/collections"); - if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getPerPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "per_page", request.getPerPage().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - CollectionList parsedResponse = - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CollectionList.class); - int newPageNumber = request.getPage().map(page -> page + 1).orElse(1); - ListCollectionsRequest nextRequest = ListCollectionsRequest.builder() - .from(request) - .page(newPageNumber) - .build(); - List result = parsedResponse.getData(); - return new SyncPagingIterable(true, result, () -> list(nextRequest, requestOptions)); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.list(request, requestOptions).body(); } /** * You can create a new collection by making a POST request to https://api.intercom.io/help_center/collections. */ public Collection create(CreateCollectionRequest request) { - return create(request, null); + return this.rawClient.create(request).body(); } /** * You can create a new collection by making a POST request to https://api.intercom.io/help_center/collections. */ public Collection create(CreateCollectionRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("help_center/collections") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Collection.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.create(request, requestOptions).body(); } /** * You can fetch the details of a single collection by making a GET request to https://api.intercom.io/help_center/collections/<id>. */ public Collection find(FindCollectionRequest request) { - return find(request, null); + return this.rawClient.find(request).body(); } /** * You can fetch the details of a single collection by making a GET request to https://api.intercom.io/help_center/collections/<id>. */ public Collection find(FindCollectionRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("help_center/collections") - .addPathSegment(request.getCollectionId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Collection.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.find(request, requestOptions).body(); } /** * You can update the details of a single collection by making a PUT request to https://api.intercom.io/collections/<id>. */ public Collection update(UpdateCollectionRequest request) { - return update(request, null); + return this.rawClient.update(request).body(); } /** * You can update the details of a single collection by making a PUT request to https://api.intercom.io/collections/<id>. */ public Collection update(UpdateCollectionRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("help_center/collections") - .addPathSegment(request.getCollectionId()) - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PUT", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Collection.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.update(request, requestOptions).body(); } /** * You can delete a single collection by making a DELETE request to https://api.intercom.io/collections/<id>. */ public DeletedCollectionObject delete(DeleteCollectionRequest request) { - return delete(request, null); + return this.rawClient.delete(request).body(); } /** * You can delete a single collection by making a DELETE request to https://api.intercom.io/collections/<id>. */ public DeletedCollectionObject delete(DeleteCollectionRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("help_center/collections") - .addPathSegment(request.getCollectionId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeletedCollectionObject.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.delete(request, requestOptions).body(); } } diff --git a/src/main/java/com/intercom/api/resources/helpcenters/collections/RawCollectionsClient.java b/src/main/java/com/intercom/api/resources/helpcenters/collections/RawCollectionsClient.java new file mode 100644 index 0000000..8e9cee2 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/helpcenters/collections/RawCollectionsClient.java @@ -0,0 +1,362 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.helpcenters.collections; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.QueryStringMapper; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.core.pagination.SyncPagingIterable; +import com.intercom.api.errors.BadRequestError; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.helpcenter.types.Collection; +import com.intercom.api.resources.helpcenters.collections.requests.CreateCollectionRequest; +import com.intercom.api.resources.helpcenters.collections.requests.DeleteCollectionRequest; +import com.intercom.api.resources.helpcenters.collections.requests.FindCollectionRequest; +import com.intercom.api.resources.helpcenters.collections.requests.ListCollectionsRequest; +import com.intercom.api.resources.helpcenters.collections.requests.UpdateCollectionRequest; +import com.intercom.api.types.CollectionList; +import com.intercom.api.types.DeletedCollectionObject; +import com.intercom.api.types.Error; +import java.io.IOException; +import java.util.List; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawCollectionsClient { + protected final ClientOptions clientOptions; + + public RawCollectionsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can fetch a list of all collections by making a GET request to https://api.intercom.io/help_center/collections. + *

Collections will be returned in descending order on the updated_at attribute. This means if you need to iterate through results then we'll show the most recently updated collections first.

+ */ + public IntercomHttpResponse> list() { + return list(ListCollectionsRequest.builder().build()); + } + + /** + * You can fetch a list of all collections by making a GET request to https://api.intercom.io/help_center/collections. + *

Collections will be returned in descending order on the updated_at attribute. This means if you need to iterate through results then we'll show the most recently updated collections first.

+ */ + public IntercomHttpResponse> list(ListCollectionsRequest request) { + return list(request, null); + } + + /** + * You can fetch a list of all collections by making a GET request to https://api.intercom.io/help_center/collections. + *

Collections will be returned in descending order on the updated_at attribute. This means if you need to iterate through results then we'll show the most recently updated collections first.

+ */ + public IntercomHttpResponse> list( + ListCollectionsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("help_center/collections"); + if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "page", request.getPage().get().toString(), false); + } + if (request.getPerPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "per_page", request.getPerPage().get().toString(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + CollectionList parsedResponse = + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CollectionList.class); + int newPageNumber = request.getPage().map(page -> page + 1).orElse(1); + ListCollectionsRequest nextRequest = ListCollectionsRequest.builder() + .from(request) + .page(newPageNumber) + .build(); + List result = parsedResponse.getData(); + return new IntercomHttpResponse<>( + new SyncPagingIterable(true, result, () -> list(nextRequest, requestOptions) + .body()), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can create a new collection by making a POST request to https://api.intercom.io/help_center/collections. + */ + public IntercomHttpResponse create(CreateCollectionRequest request) { + return create(request, null); + } + + /** + * You can create a new collection by making a POST request to https://api.intercom.io/help_center/collections. + */ + public IntercomHttpResponse create(CreateCollectionRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("help_center/collections") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Collection.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can fetch the details of a single collection by making a GET request to https://api.intercom.io/help_center/collections/<id>. + */ + public IntercomHttpResponse find(FindCollectionRequest request) { + return find(request, null); + } + + /** + * You can fetch the details of a single collection by making a GET request to https://api.intercom.io/help_center/collections/<id>. + */ + public IntercomHttpResponse find(FindCollectionRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("help_center/collections") + .addPathSegment(request.getCollectionId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Collection.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can update the details of a single collection by making a PUT request to https://api.intercom.io/collections/<id>. + */ + public IntercomHttpResponse update(UpdateCollectionRequest request) { + return update(request, null); + } + + /** + * You can update the details of a single collection by making a PUT request to https://api.intercom.io/collections/<id>. + */ + public IntercomHttpResponse update(UpdateCollectionRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("help_center/collections") + .addPathSegment(request.getCollectionId()) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Collection.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can delete a single collection by making a DELETE request to https://api.intercom.io/collections/<id>. + */ + public IntercomHttpResponse delete(DeleteCollectionRequest request) { + return delete(request, null); + } + + /** + * You can delete a single collection by making a DELETE request to https://api.intercom.io/collections/<id>. + */ + public IntercomHttpResponse delete( + DeleteCollectionRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("help_center/collections") + .addPathSegment(request.getCollectionId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeletedCollectionObject.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/intercom/api/resources/messages/AsyncMessagesClient.java b/src/main/java/com/intercom/api/resources/messages/AsyncMessagesClient.java index ac08b55..a0940a6 100644 --- a/src/main/java/com/intercom/api/resources/messages/AsyncMessagesClient.java +++ b/src/main/java/com/intercom/api/resources/messages/AsyncMessagesClient.java @@ -3,38 +3,27 @@ */ package com.intercom.api.resources.messages; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; import com.intercom.api.core.RequestOptions; -import com.intercom.api.errors.BadRequestError; -import com.intercom.api.errors.ForbiddenError; -import com.intercom.api.errors.UnauthorizedError; -import com.intercom.api.errors.UnprocessableEntityError; import com.intercom.api.resources.messages.types.Message; import com.intercom.api.types.CreateMessageRequest; -import com.intercom.api.types.Error; -import java.io.IOException; import java.util.concurrent.CompletableFuture; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; public class AsyncMessagesClient { protected final ClientOptions clientOptions; + private final AsyncRawMessagesClient rawClient; + public AsyncMessagesClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new AsyncRawMessagesClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawMessagesClient withRawResponse() { + return this.rawClient; } /** @@ -50,7 +39,7 @@ public AsyncMessagesClient(ClientOptions clientOptions) { * */ public CompletableFuture create(CreateMessageRequest request) { - return create(request, null); + return this.rawClient.create(request).thenApply(response -> response.body()); } /** @@ -66,75 +55,6 @@ public CompletableFuture create(CreateMessageRequest request) { * */ public CompletableFuture create(CreateMessageRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("messages") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Message.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.create(request, requestOptions).thenApply(response -> response.body()); } } diff --git a/src/main/java/com/intercom/api/resources/messages/AsyncRawMessagesClient.java b/src/main/java/com/intercom/api/resources/messages/AsyncRawMessagesClient.java new file mode 100644 index 0000000..30cc313 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/messages/AsyncRawMessagesClient.java @@ -0,0 +1,148 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.messages; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.BadRequestError; +import com.intercom.api.errors.ForbiddenError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.errors.UnprocessableEntityError; +import com.intercom.api.resources.messages.types.Message; +import com.intercom.api.types.CreateMessageRequest; +import com.intercom.api.types.Error; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawMessagesClient { + protected final ClientOptions clientOptions; + + public AsyncRawMessagesClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can create a message that has been initiated by an admin. The conversation can be either an in-app message or an email. + *
+ *

🚧 Sending for visitors

+ *

There can be a short delay between when a contact is created and when a contact becomes available to be messaged through the API. A 404 Not Found error will be returned in this case.

+ *
+ *

This will return the Message model that has been created.

+ *
+ *

🚧 Retrieving Associated Conversations

+ *

As this is a message, there will be no conversation present until the contact responds. Once they do, you will have to search for a contact's conversations with the id of the message.

+ *
+ */ + public CompletableFuture> create(CreateMessageRequest request) { + return create(request, null); + } + + /** + * You can create a message that has been initiated by an admin. The conversation can be either an in-app message or an email. + *
+ *

🚧 Sending for visitors

+ *

There can be a short delay between when a contact is created and when a contact becomes available to be messaged through the API. A 404 Not Found error will be returned in this case.

+ *
+ *

This will return the Message model that has been created.

+ *
+ *

🚧 Retrieving Associated Conversations

+ *

As this is a message, there will be no conversation present until the contact responds. Once they do, you will have to search for a contact's conversations with the id of the message.

+ *
+ */ + public CompletableFuture> create( + CreateMessageRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("messages") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Message.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 403: + future.completeExceptionally(new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 422: + future.completeExceptionally(new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/intercom/api/resources/messages/MessagesClient.java b/src/main/java/com/intercom/api/resources/messages/MessagesClient.java index 0ec9a2d..002bd34 100644 --- a/src/main/java/com/intercom/api/resources/messages/MessagesClient.java +++ b/src/main/java/com/intercom/api/resources/messages/MessagesClient.java @@ -3,34 +3,26 @@ */ package com.intercom.api.resources.messages; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; import com.intercom.api.core.RequestOptions; -import com.intercom.api.errors.BadRequestError; -import com.intercom.api.errors.ForbiddenError; -import com.intercom.api.errors.UnauthorizedError; -import com.intercom.api.errors.UnprocessableEntityError; import com.intercom.api.resources.messages.types.Message; import com.intercom.api.types.CreateMessageRequest; -import com.intercom.api.types.Error; -import java.io.IOException; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; public class MessagesClient { protected final ClientOptions clientOptions; + private final RawMessagesClient rawClient; + public MessagesClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawMessagesClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawMessagesClient withRawResponse() { + return this.rawClient; } /** @@ -46,7 +38,7 @@ public MessagesClient(ClientOptions clientOptions) { * */ public Message create(CreateMessageRequest request) { - return create(request, null); + return this.rawClient.create(request).body(); } /** @@ -62,57 +54,6 @@ public Message create(CreateMessageRequest request) { * */ public Message create(CreateMessageRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("messages") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Message.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 403: - throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.create(request, requestOptions).body(); } } diff --git a/src/main/java/com/intercom/api/resources/messages/RawMessagesClient.java b/src/main/java/com/intercom/api/resources/messages/RawMessagesClient.java new file mode 100644 index 0000000..feb1e76 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/messages/RawMessagesClient.java @@ -0,0 +1,122 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.messages; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.BadRequestError; +import com.intercom.api.errors.ForbiddenError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.errors.UnprocessableEntityError; +import com.intercom.api.resources.messages.types.Message; +import com.intercom.api.types.CreateMessageRequest; +import com.intercom.api.types.Error; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawMessagesClient { + protected final ClientOptions clientOptions; + + public RawMessagesClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can create a message that has been initiated by an admin. The conversation can be either an in-app message or an email. + *
+ *

🚧 Sending for visitors

+ *

There can be a short delay between when a contact is created and when a contact becomes available to be messaged through the API. A 404 Not Found error will be returned in this case.

+ *
+ *

This will return the Message model that has been created.

+ *
+ *

🚧 Retrieving Associated Conversations

+ *

As this is a message, there will be no conversation present until the contact responds. Once they do, you will have to search for a contact's conversations with the id of the message.

+ *
+ */ + public IntercomHttpResponse create(CreateMessageRequest request) { + return create(request, null); + } + + /** + * You can create a message that has been initiated by an admin. The conversation can be either an in-app message or an email. + *
+ *

🚧 Sending for visitors

+ *

There can be a short delay between when a contact is created and when a contact becomes available to be messaged through the API. A 404 Not Found error will be returned in this case.

+ *
+ *

This will return the Message model that has been created.

+ *
+ *

🚧 Retrieving Associated Conversations

+ *

As this is a message, there will be no conversation present until the contact responds. Once they do, you will have to search for a contact's conversations with the id of the message.

+ *
+ */ + public IntercomHttpResponse create(CreateMessageRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("messages") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Message.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 403: + throw new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/intercom/api/resources/news/feeds/AsyncFeedsClient.java b/src/main/java/com/intercom/api/resources/news/feeds/AsyncFeedsClient.java index 9c5a952..90b558b 100644 --- a/src/main/java/com/intercom/api/resources/news/feeds/AsyncFeedsClient.java +++ b/src/main/java/com/intercom/api/resources/news/feeds/AsyncFeedsClient.java @@ -3,43 +3,37 @@ */ package com.intercom.api.resources.news.feeds; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.ObjectMappers; import com.intercom.api.core.RequestOptions; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.news.feeds.requests.FindNewsFeedRequest; import com.intercom.api.resources.news.feeds.requests.ListNewsFeedItemsRequest; import com.intercom.api.resources.news.types.Newsfeed; -import com.intercom.api.types.Error; import com.intercom.api.types.PaginatedNewsItemResponse; import com.intercom.api.types.PaginatedNewsfeedResponse; -import java.io.IOException; import java.util.concurrent.CompletableFuture; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; public class AsyncFeedsClient { protected final ClientOptions clientOptions; + private final AsyncRawFeedsClient rawClient; + public AsyncFeedsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new AsyncRawFeedsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawFeedsClient withRawResponse() { + return this.rawClient; } /** * You can fetch a list of all news items that are live on a given newsfeed */ public CompletableFuture listItems(ListNewsFeedItemsRequest request) { - return listItems(request, null); + return this.rawClient.listItems(request).thenApply(response -> response.body()); } /** @@ -47,186 +41,34 @@ public CompletableFuture listItems(ListNewsFeedItemsR */ public CompletableFuture listItems( ListNewsFeedItemsRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("news/newsfeeds") - .addPathSegment(request.getNewsfeedId()) - .addPathSegments("items") - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), PaginatedNewsItemResponse.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.listItems(request, requestOptions).thenApply(response -> response.body()); } /** * You can fetch a list of all newsfeeds */ public CompletableFuture list() { - return list(null); + return this.rawClient.list().thenApply(response -> response.body()); } /** * You can fetch a list of all newsfeeds */ public CompletableFuture list(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("news/newsfeeds") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), PaginatedNewsfeedResponse.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.list(requestOptions).thenApply(response -> response.body()); } /** * You can fetch the details of a single newsfeed */ public CompletableFuture find(FindNewsFeedRequest request) { - return find(request, null); + return this.rawClient.find(request).thenApply(response -> response.body()); } /** * You can fetch the details of a single newsfeed */ public CompletableFuture find(FindNewsFeedRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("news/newsfeeds") - .addPathSegment(request.getNewsfeedId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Newsfeed.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.find(request, requestOptions).thenApply(response -> response.body()); } } diff --git a/src/main/java/com/intercom/api/resources/news/feeds/AsyncRawFeedsClient.java b/src/main/java/com/intercom/api/resources/news/feeds/AsyncRawFeedsClient.java new file mode 100644 index 0000000..9bb5511 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/news/feeds/AsyncRawFeedsClient.java @@ -0,0 +1,243 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.news.feeds; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.news.feeds.requests.FindNewsFeedRequest; +import com.intercom.api.resources.news.feeds.requests.ListNewsFeedItemsRequest; +import com.intercom.api.resources.news.types.Newsfeed; +import com.intercom.api.types.Error; +import com.intercom.api.types.PaginatedNewsItemResponse; +import com.intercom.api.types.PaginatedNewsfeedResponse; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawFeedsClient { + protected final ClientOptions clientOptions; + + public AsyncRawFeedsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can fetch a list of all news items that are live on a given newsfeed + */ + public CompletableFuture> listItems( + ListNewsFeedItemsRequest request) { + return listItems(request, null); + } + + /** + * You can fetch a list of all news items that are live on a given newsfeed + */ + public CompletableFuture> listItems( + ListNewsFeedItemsRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("news/newsfeeds") + .addPathSegment(request.getNewsfeedId()) + .addPathSegments("items") + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), PaginatedNewsItemResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can fetch a list of all newsfeeds + */ + public CompletableFuture> list() { + return list(null); + } + + /** + * You can fetch a list of all newsfeeds + */ + public CompletableFuture> list(RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("news/newsfeeds") + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), PaginatedNewsfeedResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can fetch the details of a single newsfeed + */ + public CompletableFuture> find(FindNewsFeedRequest request) { + return find(request, null); + } + + /** + * You can fetch the details of a single newsfeed + */ + public CompletableFuture> find( + FindNewsFeedRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("news/newsfeeds") + .addPathSegment(request.getNewsfeedId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Newsfeed.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/intercom/api/resources/news/feeds/FeedsClient.java b/src/main/java/com/intercom/api/resources/news/feeds/FeedsClient.java index da96d87..895cf2f 100644 --- a/src/main/java/com/intercom/api/resources/news/feeds/FeedsClient.java +++ b/src/main/java/com/intercom/api/resources/news/feeds/FeedsClient.java @@ -3,178 +3,70 @@ */ package com.intercom.api.resources.news.feeds; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.ObjectMappers; import com.intercom.api.core.RequestOptions; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.news.feeds.requests.FindNewsFeedRequest; import com.intercom.api.resources.news.feeds.requests.ListNewsFeedItemsRequest; import com.intercom.api.resources.news.types.Newsfeed; -import com.intercom.api.types.Error; import com.intercom.api.types.PaginatedNewsItemResponse; import com.intercom.api.types.PaginatedNewsfeedResponse; -import java.io.IOException; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; public class FeedsClient { protected final ClientOptions clientOptions; + private final RawFeedsClient rawClient; + public FeedsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawFeedsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawFeedsClient withRawResponse() { + return this.rawClient; } /** * You can fetch a list of all news items that are live on a given newsfeed */ public PaginatedNewsItemResponse listItems(ListNewsFeedItemsRequest request) { - return listItems(request, null); + return this.rawClient.listItems(request).body(); } /** * You can fetch a list of all news items that are live on a given newsfeed */ public PaginatedNewsItemResponse listItems(ListNewsFeedItemsRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("news/newsfeeds") - .addPathSegment(request.getNewsfeedId()) - .addPathSegments("items") - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), PaginatedNewsItemResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.listItems(request, requestOptions).body(); } /** * You can fetch a list of all newsfeeds */ public PaginatedNewsfeedResponse list() { - return list(null); + return this.rawClient.list().body(); } /** * You can fetch a list of all newsfeeds */ public PaginatedNewsfeedResponse list(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("news/newsfeeds") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), PaginatedNewsfeedResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.list(requestOptions).body(); } /** * You can fetch the details of a single newsfeed */ public Newsfeed find(FindNewsFeedRequest request) { - return find(request, null); + return this.rawClient.find(request).body(); } /** * You can fetch the details of a single newsfeed */ public Newsfeed find(FindNewsFeedRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("news/newsfeeds") - .addPathSegment(request.getNewsfeedId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Newsfeed.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.find(request, requestOptions).body(); } } diff --git a/src/main/java/com/intercom/api/resources/news/feeds/RawFeedsClient.java b/src/main/java/com/intercom/api/resources/news/feeds/RawFeedsClient.java new file mode 100644 index 0000000..b297ee9 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/news/feeds/RawFeedsClient.java @@ -0,0 +1,193 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.news.feeds; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.news.feeds.requests.FindNewsFeedRequest; +import com.intercom.api.resources.news.feeds.requests.ListNewsFeedItemsRequest; +import com.intercom.api.resources.news.types.Newsfeed; +import com.intercom.api.types.Error; +import com.intercom.api.types.PaginatedNewsItemResponse; +import com.intercom.api.types.PaginatedNewsfeedResponse; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawFeedsClient { + protected final ClientOptions clientOptions; + + public RawFeedsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can fetch a list of all news items that are live on a given newsfeed + */ + public IntercomHttpResponse listItems(ListNewsFeedItemsRequest request) { + return listItems(request, null); + } + + /** + * You can fetch a list of all news items that are live on a given newsfeed + */ + public IntercomHttpResponse listItems( + ListNewsFeedItemsRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("news/newsfeeds") + .addPathSegment(request.getNewsfeedId()) + .addPathSegments("items") + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), PaginatedNewsItemResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can fetch a list of all newsfeeds + */ + public IntercomHttpResponse list() { + return list(null); + } + + /** + * You can fetch a list of all newsfeeds + */ + public IntercomHttpResponse list(RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("news/newsfeeds") + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), PaginatedNewsfeedResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can fetch the details of a single newsfeed + */ + public IntercomHttpResponse find(FindNewsFeedRequest request) { + return find(request, null); + } + + /** + * You can fetch the details of a single newsfeed + */ + public IntercomHttpResponse find(FindNewsFeedRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("news/newsfeeds") + .addPathSegment(request.getNewsfeedId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Newsfeed.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/intercom/api/resources/news/items/AsyncItemsClient.java b/src/main/java/com/intercom/api/resources/news/items/AsyncItemsClient.java index c0d76e2..c4826f4 100644 --- a/src/main/java/com/intercom/api/resources/news/items/AsyncItemsClient.java +++ b/src/main/java/com/intercom/api/resources/news/items/AsyncItemsClient.java @@ -3,383 +3,95 @@ */ package com.intercom.api.resources.news.items; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; import com.intercom.api.core.RequestOptions; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.news.items.requests.DeleteNewsItemRequest; import com.intercom.api.resources.news.items.requests.FindNewsItemRequest; import com.intercom.api.resources.news.items.requests.UpdateNewsItemRequest; import com.intercom.api.resources.news.types.NewsItem; import com.intercom.api.types.DeletedObject; -import com.intercom.api.types.Error; import com.intercom.api.types.NewsItemRequest; import com.intercom.api.types.PaginatedNewsItemResponse; -import java.io.IOException; import java.util.concurrent.CompletableFuture; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; public class AsyncItemsClient { protected final ClientOptions clientOptions; + private final AsyncRawItemsClient rawClient; + public AsyncItemsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new AsyncRawItemsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawItemsClient withRawResponse() { + return this.rawClient; } /** * You can fetch a list of all news items */ public CompletableFuture list() { - return list(null); + return this.rawClient.list().thenApply(response -> response.body()); } /** * You can fetch a list of all news items */ public CompletableFuture list(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("news/news_items") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), PaginatedNewsItemResponse.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.list(requestOptions).thenApply(response -> response.body()); } /** * You can create a news item */ public CompletableFuture create(NewsItemRequest request) { - return create(request, null); + return this.rawClient.create(request).thenApply(response -> response.body()); } /** * You can create a news item */ public CompletableFuture create(NewsItemRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("news/news_items") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), NewsItem.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.create(request, requestOptions).thenApply(response -> response.body()); } /** * You can fetch the details of a single news item. */ public CompletableFuture find(FindNewsItemRequest request) { - return find(request, null); + return this.rawClient.find(request).thenApply(response -> response.body()); } /** * You can fetch the details of a single news item. */ public CompletableFuture find(FindNewsItemRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("news/news_items") - .addPathSegment(request.getNewsItemId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), NewsItem.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.find(request, requestOptions).thenApply(response -> response.body()); } public CompletableFuture update(UpdateNewsItemRequest request) { - return update(request, null); + return this.rawClient.update(request).thenApply(response -> response.body()); } public CompletableFuture update(UpdateNewsItemRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("news/news_items") - .addPathSegment(request.getNewsItemId()) - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request.getBody()), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PUT", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), NewsItem.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.update(request, requestOptions).thenApply(response -> response.body()); } /** * You can delete a single news item. */ public CompletableFuture delete(DeleteNewsItemRequest request) { - return delete(request, null); + return this.rawClient.delete(request).thenApply(response -> response.body()); } /** * You can delete a single news item. */ public CompletableFuture delete(DeleteNewsItemRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("news/news_items") - .addPathSegment(request.getNewsItemId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeletedObject.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.delete(request, requestOptions).thenApply(response -> response.body()); } } diff --git a/src/main/java/com/intercom/api/resources/news/items/AsyncRawItemsClient.java b/src/main/java/com/intercom/api/resources/news/items/AsyncRawItemsClient.java new file mode 100644 index 0000000..4386306 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/news/items/AsyncRawItemsClient.java @@ -0,0 +1,407 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.news.items; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.news.items.requests.DeleteNewsItemRequest; +import com.intercom.api.resources.news.items.requests.FindNewsItemRequest; +import com.intercom.api.resources.news.items.requests.UpdateNewsItemRequest; +import com.intercom.api.resources.news.types.NewsItem; +import com.intercom.api.types.DeletedObject; +import com.intercom.api.types.Error; +import com.intercom.api.types.NewsItemRequest; +import com.intercom.api.types.PaginatedNewsItemResponse; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawItemsClient { + protected final ClientOptions clientOptions; + + public AsyncRawItemsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can fetch a list of all news items + */ + public CompletableFuture> list() { + return list(null); + } + + /** + * You can fetch a list of all news items + */ + public CompletableFuture> list(RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("news/news_items") + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), PaginatedNewsItemResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can create a news item + */ + public CompletableFuture> create(NewsItemRequest request) { + return create(request, null); + } + + /** + * You can create a news item + */ + public CompletableFuture> create( + NewsItemRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("news/news_items") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), NewsItem.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can fetch the details of a single news item. + */ + public CompletableFuture> find(FindNewsItemRequest request) { + return find(request, null); + } + + /** + * You can fetch the details of a single news item. + */ + public CompletableFuture> find( + FindNewsItemRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("news/news_items") + .addPathSegment(request.getNewsItemId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), NewsItem.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + public CompletableFuture> update(UpdateNewsItemRequest request) { + return update(request, null); + } + + public CompletableFuture> update( + UpdateNewsItemRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("news/news_items") + .addPathSegment(request.getNewsItemId()) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request.getBody()), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), NewsItem.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can delete a single news item. + */ + public CompletableFuture> delete(DeleteNewsItemRequest request) { + return delete(request, null); + } + + /** + * You can delete a single news item. + */ + public CompletableFuture> delete( + DeleteNewsItemRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("news/news_items") + .addPathSegment(request.getNewsItemId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeletedObject.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/intercom/api/resources/news/items/ItemsClient.java b/src/main/java/com/intercom/api/resources/news/items/ItemsClient.java index 0ccdbaa..6c02302 100644 --- a/src/main/java/com/intercom/api/resources/news/items/ItemsClient.java +++ b/src/main/java/com/intercom/api/resources/news/items/ItemsClient.java @@ -3,299 +3,94 @@ */ package com.intercom.api.resources.news.items; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; import com.intercom.api.core.RequestOptions; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.news.items.requests.DeleteNewsItemRequest; import com.intercom.api.resources.news.items.requests.FindNewsItemRequest; import com.intercom.api.resources.news.items.requests.UpdateNewsItemRequest; import com.intercom.api.resources.news.types.NewsItem; import com.intercom.api.types.DeletedObject; -import com.intercom.api.types.Error; import com.intercom.api.types.NewsItemRequest; import com.intercom.api.types.PaginatedNewsItemResponse; -import java.io.IOException; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; public class ItemsClient { protected final ClientOptions clientOptions; + private final RawItemsClient rawClient; + public ItemsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawItemsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawItemsClient withRawResponse() { + return this.rawClient; } /** * You can fetch a list of all news items */ public PaginatedNewsItemResponse list() { - return list(null); + return this.rawClient.list().body(); } /** * You can fetch a list of all news items */ public PaginatedNewsItemResponse list(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("news/news_items") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), PaginatedNewsItemResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.list(requestOptions).body(); } /** * You can create a news item */ public NewsItem create(NewsItemRequest request) { - return create(request, null); + return this.rawClient.create(request).body(); } /** * You can create a news item */ public NewsItem create(NewsItemRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("news/news_items") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), NewsItem.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.create(request, requestOptions).body(); } /** * You can fetch the details of a single news item. */ public NewsItem find(FindNewsItemRequest request) { - return find(request, null); + return this.rawClient.find(request).body(); } /** * You can fetch the details of a single news item. */ public NewsItem find(FindNewsItemRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("news/news_items") - .addPathSegment(request.getNewsItemId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), NewsItem.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.find(request, requestOptions).body(); } public NewsItem update(UpdateNewsItemRequest request) { - return update(request, null); + return this.rawClient.update(request).body(); } public NewsItem update(UpdateNewsItemRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("news/news_items") - .addPathSegment(request.getNewsItemId()) - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request.getBody()), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PUT", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), NewsItem.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.update(request, requestOptions).body(); } /** * You can delete a single news item. */ public DeletedObject delete(DeleteNewsItemRequest request) { - return delete(request, null); + return this.rawClient.delete(request).body(); } /** * You can delete a single news item. */ public DeletedObject delete(DeleteNewsItemRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("news/news_items") - .addPathSegment(request.getNewsItemId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeletedObject.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.delete(request, requestOptions).body(); } } diff --git a/src/main/java/com/intercom/api/resources/news/items/RawItemsClient.java b/src/main/java/com/intercom/api/resources/news/items/RawItemsClient.java new file mode 100644 index 0000000..84644ce --- /dev/null +++ b/src/main/java/com/intercom/api/resources/news/items/RawItemsClient.java @@ -0,0 +1,318 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.news.items; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.news.items.requests.DeleteNewsItemRequest; +import com.intercom.api.resources.news.items.requests.FindNewsItemRequest; +import com.intercom.api.resources.news.items.requests.UpdateNewsItemRequest; +import com.intercom.api.resources.news.types.NewsItem; +import com.intercom.api.types.DeletedObject; +import com.intercom.api.types.Error; +import com.intercom.api.types.NewsItemRequest; +import com.intercom.api.types.PaginatedNewsItemResponse; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawItemsClient { + protected final ClientOptions clientOptions; + + public RawItemsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can fetch a list of all news items + */ + public IntercomHttpResponse list() { + return list(null); + } + + /** + * You can fetch a list of all news items + */ + public IntercomHttpResponse list(RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("news/news_items") + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), PaginatedNewsItemResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can create a news item + */ + public IntercomHttpResponse create(NewsItemRequest request) { + return create(request, null); + } + + /** + * You can create a news item + */ + public IntercomHttpResponse create(NewsItemRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("news/news_items") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), NewsItem.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can fetch the details of a single news item. + */ + public IntercomHttpResponse find(FindNewsItemRequest request) { + return find(request, null); + } + + /** + * You can fetch the details of a single news item. + */ + public IntercomHttpResponse find(FindNewsItemRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("news/news_items") + .addPathSegment(request.getNewsItemId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), NewsItem.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + public IntercomHttpResponse update(UpdateNewsItemRequest request) { + return update(request, null); + } + + public IntercomHttpResponse update(UpdateNewsItemRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("news/news_items") + .addPathSegment(request.getNewsItemId()) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request.getBody()), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), NewsItem.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can delete a single news item. + */ + public IntercomHttpResponse delete(DeleteNewsItemRequest request) { + return delete(request, null); + } + + /** + * You can delete a single news item. + */ + public IntercomHttpResponse delete(DeleteNewsItemRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("news/news_items") + .addPathSegment(request.getNewsItemId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeletedObject.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/intercom/api/resources/notes/AsyncNotesClient.java b/src/main/java/com/intercom/api/resources/notes/AsyncNotesClient.java index 46f3b09..b9d17de 100644 --- a/src/main/java/com/intercom/api/resources/notes/AsyncNotesClient.java +++ b/src/main/java/com/intercom/api/resources/notes/AsyncNotesClient.java @@ -3,50 +3,37 @@ */ package com.intercom.api.resources.notes; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; -import com.intercom.api.core.QueryStringMapper; import com.intercom.api.core.RequestOptions; import com.intercom.api.core.pagination.SyncPagingIterable; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.notes.requests.CreateContactNoteRequest; import com.intercom.api.resources.notes.requests.FindNoteRequest; import com.intercom.api.resources.notes.requests.ListContactNotesRequest; import com.intercom.api.resources.notes.types.Note; -import com.intercom.api.types.Error; -import com.intercom.api.types.NoteList; -import java.io.IOException; -import java.util.List; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; public class AsyncNotesClient { protected final ClientOptions clientOptions; + private final AsyncRawNotesClient rawClient; + public AsyncNotesClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new AsyncRawNotesClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawNotesClient withRawResponse() { + return this.rawClient; } /** * You can fetch a list of notes that are associated to a contact. */ public CompletableFuture> list(ListContactNotesRequest request) { - return list(request, null); + return this.rawClient.list(request).thenApply(response -> response.body()); } /** @@ -54,220 +41,34 @@ public CompletableFuture> list(ListContactNotesRequest */ public CompletableFuture> list( ListContactNotesRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("notes"); - if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getPerPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "per_page", request.getPerPage().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - NoteList parsedResponse = - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), NoteList.class); - int newPageNumber = - request.getPage().map(page -> page + 1).orElse(1); - ListContactNotesRequest nextRequest = ListContactNotesRequest.builder() - .from(request) - .page(newPageNumber) - .build(); - List result = parsedResponse.getData(); - future.complete(new SyncPagingIterable(true, result, () -> { - try { - return list(nextRequest, requestOptions).get(); - } catch (InterruptedException | ExecutionException e) { - throw new RuntimeException(e); - } - })); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 404) { - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.list(request, requestOptions).thenApply(response -> response.body()); } /** * You can add a note to a single contact. */ public CompletableFuture create(CreateContactNoteRequest request) { - return create(request, null); + return this.rawClient.create(request).thenApply(response -> response.body()); } /** * You can add a note to a single contact. */ public CompletableFuture create(CreateContactNoteRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("notes") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Note.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 404) { - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.create(request, requestOptions).thenApply(response -> response.body()); } /** * You can fetch the details of a single note. */ public CompletableFuture find(FindNoteRequest request) { - return find(request, null); + return this.rawClient.find(request).thenApply(response -> response.body()); } /** * You can fetch the details of a single note. */ public CompletableFuture find(FindNoteRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("notes") - .addPathSegment(request.getNoteId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Note.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.find(request, requestOptions).thenApply(response -> response.body()); } } diff --git a/src/main/java/com/intercom/api/resources/notes/AsyncRawNotesClient.java b/src/main/java/com/intercom/api/resources/notes/AsyncRawNotesClient.java new file mode 100644 index 0000000..9fb3e8a --- /dev/null +++ b/src/main/java/com/intercom/api/resources/notes/AsyncRawNotesClient.java @@ -0,0 +1,286 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.notes; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.QueryStringMapper; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.core.pagination.SyncPagingIterable; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.notes.requests.CreateContactNoteRequest; +import com.intercom.api.resources.notes.requests.FindNoteRequest; +import com.intercom.api.resources.notes.requests.ListContactNotesRequest; +import com.intercom.api.resources.notes.types.Note; +import com.intercom.api.types.Error; +import com.intercom.api.types.NoteList; +import java.io.IOException; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawNotesClient { + protected final ClientOptions clientOptions; + + public AsyncRawNotesClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can fetch a list of notes that are associated to a contact. + */ + public CompletableFuture>> list(ListContactNotesRequest request) { + return list(request, null); + } + + /** + * You can fetch a list of notes that are associated to a contact. + */ + public CompletableFuture>> list( + ListContactNotesRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("notes"); + if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "page", request.getPage().get().toString(), false); + } + if (request.getPerPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "per_page", request.getPerPage().get().toString(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture>> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + NoteList parsedResponse = + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), NoteList.class); + int newPageNumber = + request.getPage().map(page -> page + 1).orElse(1); + ListContactNotesRequest nextRequest = ListContactNotesRequest.builder() + .from(request) + .page(newPageNumber) + .build(); + List result = parsedResponse.getData(); + future.complete(new IntercomHttpResponse<>( + new SyncPagingIterable(true, result, () -> { + try { + return list(nextRequest, requestOptions) + .get() + .body(); + } catch (InterruptedException | ExecutionException e) { + throw new RuntimeException(e); + } + }), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can add a note to a single contact. + */ + public CompletableFuture> create(CreateContactNoteRequest request) { + return create(request, null); + } + + /** + * You can add a note to a single contact. + */ + public CompletableFuture> create( + CreateContactNoteRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("notes") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Note.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can fetch the details of a single note. + */ + public CompletableFuture> find(FindNoteRequest request) { + return find(request, null); + } + + /** + * You can fetch the details of a single note. + */ + public CompletableFuture> find(FindNoteRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("notes") + .addPathSegment(request.getNoteId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Note.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/intercom/api/resources/notes/NotesClient.java b/src/main/java/com/intercom/api/resources/notes/NotesClient.java index ab8a8de..9ddade2 100644 --- a/src/main/java/com/intercom/api/resources/notes/NotesClient.java +++ b/src/main/java/com/intercom/api/resources/notes/NotesClient.java @@ -3,211 +3,70 @@ */ package com.intercom.api.resources.notes; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; -import com.intercom.api.core.QueryStringMapper; import com.intercom.api.core.RequestOptions; import com.intercom.api.core.pagination.SyncPagingIterable; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.notes.requests.CreateContactNoteRequest; import com.intercom.api.resources.notes.requests.FindNoteRequest; import com.intercom.api.resources.notes.requests.ListContactNotesRequest; import com.intercom.api.resources.notes.types.Note; -import com.intercom.api.types.Error; -import com.intercom.api.types.NoteList; -import java.io.IOException; -import java.util.List; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; public class NotesClient { protected final ClientOptions clientOptions; + private final RawNotesClient rawClient; + public NotesClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawNotesClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawNotesClient withRawResponse() { + return this.rawClient; } /** * You can fetch a list of notes that are associated to a contact. */ public SyncPagingIterable list(ListContactNotesRequest request) { - return list(request, null); + return this.rawClient.list(request).body(); } /** * You can fetch a list of notes that are associated to a contact. */ public SyncPagingIterable list(ListContactNotesRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("notes"); - if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getPerPage().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "per_page", request.getPerPage().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - NoteList parsedResponse = ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), NoteList.class); - int newPageNumber = request.getPage().map(page -> page + 1).orElse(1); - ListContactNotesRequest nextRequest = ListContactNotesRequest.builder() - .from(request) - .page(newPageNumber) - .build(); - List result = parsedResponse.getData(); - return new SyncPagingIterable(true, result, () -> list(nextRequest, requestOptions)); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 404) { - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.list(request, requestOptions).body(); } /** * You can add a note to a single contact. */ public Note create(CreateContactNoteRequest request) { - return create(request, null); + return this.rawClient.create(request).body(); } /** * You can add a note to a single contact. */ public Note create(CreateContactNoteRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("notes") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Note.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 404) { - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.create(request, requestOptions).body(); } /** * You can fetch the details of a single note. */ public Note find(FindNoteRequest request) { - return find(request, null); + return this.rawClient.find(request).body(); } /** * You can fetch the details of a single note. */ public Note find(FindNoteRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("notes") - .addPathSegment(request.getNoteId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Note.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.find(request, requestOptions).body(); } } diff --git a/src/main/java/com/intercom/api/resources/notes/RawNotesClient.java b/src/main/java/com/intercom/api/resources/notes/RawNotesClient.java new file mode 100644 index 0000000..e2cc71e --- /dev/null +++ b/src/main/java/com/intercom/api/resources/notes/RawNotesClient.java @@ -0,0 +1,226 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.notes; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.QueryStringMapper; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.core.pagination.SyncPagingIterable; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.notes.requests.CreateContactNoteRequest; +import com.intercom.api.resources.notes.requests.FindNoteRequest; +import com.intercom.api.resources.notes.requests.ListContactNotesRequest; +import com.intercom.api.resources.notes.types.Note; +import com.intercom.api.types.Error; +import com.intercom.api.types.NoteList; +import java.io.IOException; +import java.util.List; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawNotesClient { + protected final ClientOptions clientOptions; + + public RawNotesClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can fetch a list of notes that are associated to a contact. + */ + public IntercomHttpResponse> list(ListContactNotesRequest request) { + return list(request, null); + } + + /** + * You can fetch a list of notes that are associated to a contact. + */ + public IntercomHttpResponse> list( + ListContactNotesRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("notes"); + if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "page", request.getPage().get().toString(), false); + } + if (request.getPerPage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "per_page", request.getPerPage().get().toString(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + NoteList parsedResponse = ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), NoteList.class); + int newPageNumber = request.getPage().map(page -> page + 1).orElse(1); + ListContactNotesRequest nextRequest = ListContactNotesRequest.builder() + .from(request) + .page(newPageNumber) + .build(); + List result = parsedResponse.getData(); + return new IntercomHttpResponse<>( + new SyncPagingIterable(true, result, () -> list(nextRequest, requestOptions) + .body()), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can add a note to a single contact. + */ + public IntercomHttpResponse create(CreateContactNoteRequest request) { + return create(request, null); + } + + /** + * You can add a note to a single contact. + */ + public IntercomHttpResponse create(CreateContactNoteRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("notes") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Note.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can fetch the details of a single note. + */ + public IntercomHttpResponse find(FindNoteRequest request) { + return find(request, null); + } + + /** + * You can fetch the details of a single note. + */ + public IntercomHttpResponse find(FindNoteRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("notes") + .addPathSegment(request.getNoteId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Note.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/intercom/api/resources/phonecallredirects/AsyncPhoneCallRedirectsClient.java b/src/main/java/com/intercom/api/resources/phonecallredirects/AsyncPhoneCallRedirectsClient.java index fd1c860..2c5e358 100644 --- a/src/main/java/com/intercom/api/resources/phonecallredirects/AsyncPhoneCallRedirectsClient.java +++ b/src/main/java/com/intercom/api/resources/phonecallredirects/AsyncPhoneCallRedirectsClient.java @@ -3,37 +3,27 @@ */ package com.intercom.api.resources.phonecallredirects; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; import com.intercom.api.core.RequestOptions; -import com.intercom.api.errors.BadRequestError; -import com.intercom.api.errors.UnauthorizedError; -import com.intercom.api.errors.UnprocessableEntityError; import com.intercom.api.resources.phonecallredirects.requests.CreatePhoneCallRedirectRequest; -import com.intercom.api.types.Error; import com.intercom.api.types.PhoneSwitch; -import java.io.IOException; import java.util.concurrent.CompletableFuture; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; public class AsyncPhoneCallRedirectsClient { protected final ClientOptions clientOptions; + private final AsyncRawPhoneCallRedirectsClient rawClient; + public AsyncPhoneCallRedirectsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new AsyncRawPhoneCallRedirectsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawPhoneCallRedirectsClient withRawResponse() { + return this.rawClient; } /** @@ -42,7 +32,7 @@ public AsyncPhoneCallRedirectsClient(ClientOptions clientOptions) { *

If custom attributes are specified, they will be added to the user or lead's custom data attributes.

*/ public CompletableFuture create(CreatePhoneCallRedirectRequest request) { - return create(request, null); + return this.rawClient.create(request).thenApply(response -> response.body()); } /** @@ -52,71 +42,6 @@ public CompletableFuture create(CreatePhoneCallRedirectRequest requ */ public CompletableFuture create( CreatePhoneCallRedirectRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("phone_call_redirects") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), PhoneSwitch.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.create(request, requestOptions).thenApply(response -> response.body()); } } diff --git a/src/main/java/com/intercom/api/resources/phonecallredirects/AsyncRawPhoneCallRedirectsClient.java b/src/main/java/com/intercom/api/resources/phonecallredirects/AsyncRawPhoneCallRedirectsClient.java new file mode 100644 index 0000000..bcbb060 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/phonecallredirects/AsyncRawPhoneCallRedirectsClient.java @@ -0,0 +1,129 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.phonecallredirects; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.BadRequestError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.errors.UnprocessableEntityError; +import com.intercom.api.resources.phonecallredirects.requests.CreatePhoneCallRedirectRequest; +import com.intercom.api.types.Error; +import com.intercom.api.types.PhoneSwitch; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawPhoneCallRedirectsClient { + protected final ClientOptions clientOptions; + + public AsyncRawPhoneCallRedirectsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can use the API to deflect phone calls to the Intercom Messenger. + * Calling this endpoint will send an SMS with a link to the Messenger to the phone number specified. + *

If custom attributes are specified, they will be added to the user or lead's custom data attributes.

+ */ + public CompletableFuture> create(CreatePhoneCallRedirectRequest request) { + return create(request, null); + } + + /** + * You can use the API to deflect phone calls to the Intercom Messenger. + * Calling this endpoint will send an SMS with a link to the Messenger to the phone number specified. + *

If custom attributes are specified, they will be added to the user or lead's custom data attributes.

+ */ + public CompletableFuture> create( + CreatePhoneCallRedirectRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("phone_call_redirects") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), PhoneSwitch.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 422: + future.completeExceptionally(new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/intercom/api/resources/phonecallredirects/PhoneCallRedirectsClient.java b/src/main/java/com/intercom/api/resources/phonecallredirects/PhoneCallRedirectsClient.java index 2727a23..836dc4f 100644 --- a/src/main/java/com/intercom/api/resources/phonecallredirects/PhoneCallRedirectsClient.java +++ b/src/main/java/com/intercom/api/resources/phonecallredirects/PhoneCallRedirectsClient.java @@ -3,33 +3,26 @@ */ package com.intercom.api.resources.phonecallredirects; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; import com.intercom.api.core.RequestOptions; -import com.intercom.api.errors.BadRequestError; -import com.intercom.api.errors.UnauthorizedError; -import com.intercom.api.errors.UnprocessableEntityError; import com.intercom.api.resources.phonecallredirects.requests.CreatePhoneCallRedirectRequest; -import com.intercom.api.types.Error; import com.intercom.api.types.PhoneSwitch; -import java.io.IOException; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; public class PhoneCallRedirectsClient { protected final ClientOptions clientOptions; + private final RawPhoneCallRedirectsClient rawClient; + public PhoneCallRedirectsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawPhoneCallRedirectsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawPhoneCallRedirectsClient withRawResponse() { + return this.rawClient; } /** @@ -38,7 +31,7 @@ public PhoneCallRedirectsClient(ClientOptions clientOptions) { *

If custom attributes are specified, they will be added to the user or lead's custom data attributes.

*/ public PhoneSwitch create(CreatePhoneCallRedirectRequest request) { - return create(request, null); + return this.rawClient.create(request).body(); } /** @@ -47,55 +40,6 @@ public PhoneSwitch create(CreatePhoneCallRedirectRequest request) { *

If custom attributes are specified, they will be added to the user or lead's custom data attributes.

*/ public PhoneSwitch create(CreatePhoneCallRedirectRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("phone_call_redirects") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), PhoneSwitch.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.create(request, requestOptions).body(); } } diff --git a/src/main/java/com/intercom/api/resources/phonecallredirects/RawPhoneCallRedirectsClient.java b/src/main/java/com/intercom/api/resources/phonecallredirects/RawPhoneCallRedirectsClient.java new file mode 100644 index 0000000..14ee509 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/phonecallredirects/RawPhoneCallRedirectsClient.java @@ -0,0 +1,105 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.phonecallredirects; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.BadRequestError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.errors.UnprocessableEntityError; +import com.intercom.api.resources.phonecallredirects.requests.CreatePhoneCallRedirectRequest; +import com.intercom.api.types.Error; +import com.intercom.api.types.PhoneSwitch; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawPhoneCallRedirectsClient { + protected final ClientOptions clientOptions; + + public RawPhoneCallRedirectsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can use the API to deflect phone calls to the Intercom Messenger. + * Calling this endpoint will send an SMS with a link to the Messenger to the phone number specified. + *

If custom attributes are specified, they will be added to the user or lead's custom data attributes.

+ */ + public IntercomHttpResponse create(CreatePhoneCallRedirectRequest request) { + return create(request, null); + } + + /** + * You can use the API to deflect phone calls to the Intercom Messenger. + * Calling this endpoint will send an SMS with a link to the Messenger to the phone number specified. + *

If custom attributes are specified, they will be added to the user or lead's custom data attributes.

+ */ + public IntercomHttpResponse create( + CreatePhoneCallRedirectRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("phone_call_redirects") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), PhoneSwitch.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/intercom/api/resources/segments/AsyncRawSegmentsClient.java b/src/main/java/com/intercom/api/resources/segments/AsyncRawSegmentsClient.java new file mode 100644 index 0000000..78d8f8b --- /dev/null +++ b/src/main/java/com/intercom/api/resources/segments/AsyncRawSegmentsClient.java @@ -0,0 +1,190 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.segments; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.QueryStringMapper; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.segments.requests.FindSegmentRequest; +import com.intercom.api.resources.segments.requests.ListSegmentsRequest; +import com.intercom.api.resources.segments.types.Segment; +import com.intercom.api.types.Error; +import com.intercom.api.types.SegmentList; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawSegmentsClient { + protected final ClientOptions clientOptions; + + public AsyncRawSegmentsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can fetch a list of all segments. + */ + public CompletableFuture> list() { + return list(ListSegmentsRequest.builder().build()); + } + + /** + * You can fetch a list of all segments. + */ + public CompletableFuture> list(ListSegmentsRequest request) { + return list(request, null); + } + + /** + * You can fetch a list of all segments. + */ + public CompletableFuture> list( + ListSegmentsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("segments"); + if (request.getIncludeCount().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "include_count", request.getIncludeCount().get().toString(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SegmentList.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can fetch the details of a single segment. + */ + public CompletableFuture> find(FindSegmentRequest request) { + return find(request, null); + } + + /** + * You can fetch the details of a single segment. + */ + public CompletableFuture> find( + FindSegmentRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("segments") + .addPathSegment(request.getSegmentId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Segment.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/intercom/api/resources/segments/AsyncSegmentsClient.java b/src/main/java/com/intercom/api/resources/segments/AsyncSegmentsClient.java index 15cc464..e1b18d9 100644 --- a/src/main/java/com/intercom/api/resources/segments/AsyncSegmentsClient.java +++ b/src/main/java/com/intercom/api/resources/segments/AsyncSegmentsClient.java @@ -3,178 +3,63 @@ */ package com.intercom.api.resources.segments; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.ObjectMappers; -import com.intercom.api.core.QueryStringMapper; import com.intercom.api.core.RequestOptions; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.segments.requests.FindSegmentRequest; import com.intercom.api.resources.segments.requests.ListSegmentsRequest; import com.intercom.api.resources.segments.types.Segment; -import com.intercom.api.types.Error; import com.intercom.api.types.SegmentList; -import java.io.IOException; import java.util.concurrent.CompletableFuture; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; public class AsyncSegmentsClient { protected final ClientOptions clientOptions; + private final AsyncRawSegmentsClient rawClient; + public AsyncSegmentsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new AsyncRawSegmentsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawSegmentsClient withRawResponse() { + return this.rawClient; } /** * You can fetch a list of all segments. */ public CompletableFuture list() { - return list(ListSegmentsRequest.builder().build()); + return this.rawClient.list().thenApply(response -> response.body()); } /** * You can fetch a list of all segments. */ public CompletableFuture list(ListSegmentsRequest request) { - return list(request, null); + return this.rawClient.list(request).thenApply(response -> response.body()); } /** * You can fetch a list of all segments. */ public CompletableFuture list(ListSegmentsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("segments"); - if (request.getIncludeCount().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "include_count", request.getIncludeCount().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SegmentList.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.list(request, requestOptions).thenApply(response -> response.body()); } /** * You can fetch the details of a single segment. */ public CompletableFuture find(FindSegmentRequest request) { - return find(request, null); + return this.rawClient.find(request).thenApply(response -> response.body()); } /** * You can fetch the details of a single segment. */ public CompletableFuture find(FindSegmentRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("segments") - .addPathSegment(request.getSegmentId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Segment.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.find(request, requestOptions).thenApply(response -> response.body()); } } diff --git a/src/main/java/com/intercom/api/resources/segments/RawSegmentsClient.java b/src/main/java/com/intercom/api/resources/segments/RawSegmentsClient.java new file mode 100644 index 0000000..723140f --- /dev/null +++ b/src/main/java/com/intercom/api/resources/segments/RawSegmentsClient.java @@ -0,0 +1,152 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.segments; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.QueryStringMapper; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.segments.requests.FindSegmentRequest; +import com.intercom.api.resources.segments.requests.ListSegmentsRequest; +import com.intercom.api.resources.segments.types.Segment; +import com.intercom.api.types.Error; +import com.intercom.api.types.SegmentList; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawSegmentsClient { + protected final ClientOptions clientOptions; + + public RawSegmentsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can fetch a list of all segments. + */ + public IntercomHttpResponse list() { + return list(ListSegmentsRequest.builder().build()); + } + + /** + * You can fetch a list of all segments. + */ + public IntercomHttpResponse list(ListSegmentsRequest request) { + return list(request, null); + } + + /** + * You can fetch a list of all segments. + */ + public IntercomHttpResponse list(ListSegmentsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("segments"); + if (request.getIncludeCount().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "include_count", request.getIncludeCount().get().toString(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SegmentList.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can fetch the details of a single segment. + */ + public IntercomHttpResponse find(FindSegmentRequest request) { + return find(request, null); + } + + /** + * You can fetch the details of a single segment. + */ + public IntercomHttpResponse find(FindSegmentRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("segments") + .addPathSegment(request.getSegmentId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Segment.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/intercom/api/resources/segments/SegmentsClient.java b/src/main/java/com/intercom/api/resources/segments/SegmentsClient.java index 68e22e1..c1999ea 100644 --- a/src/main/java/com/intercom/api/resources/segments/SegmentsClient.java +++ b/src/main/java/com/intercom/api/resources/segments/SegmentsClient.java @@ -3,143 +3,62 @@ */ package com.intercom.api.resources.segments; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.ObjectMappers; -import com.intercom.api.core.QueryStringMapper; import com.intercom.api.core.RequestOptions; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.segments.requests.FindSegmentRequest; import com.intercom.api.resources.segments.requests.ListSegmentsRequest; import com.intercom.api.resources.segments.types.Segment; -import com.intercom.api.types.Error; import com.intercom.api.types.SegmentList; -import java.io.IOException; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; public class SegmentsClient { protected final ClientOptions clientOptions; + private final RawSegmentsClient rawClient; + public SegmentsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawSegmentsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawSegmentsClient withRawResponse() { + return this.rawClient; } /** * You can fetch a list of all segments. */ public SegmentList list() { - return list(ListSegmentsRequest.builder().build()); + return this.rawClient.list().body(); } /** * You can fetch a list of all segments. */ public SegmentList list(ListSegmentsRequest request) { - return list(request, null); + return this.rawClient.list(request).body(); } /** * You can fetch a list of all segments. */ public SegmentList list(ListSegmentsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("segments"); - if (request.getIncludeCount().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "include_count", request.getIncludeCount().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SegmentList.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.list(request, requestOptions).body(); } /** * You can fetch the details of a single segment. */ public Segment find(FindSegmentRequest request) { - return find(request, null); + return this.rawClient.find(request).body(); } /** * You can fetch the details of a single segment. */ public Segment find(FindSegmentRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("segments") - .addPathSegment(request.getSegmentId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Segment.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.find(request, requestOptions).body(); } } diff --git a/src/main/java/com/intercom/api/resources/subscriptiontypes/AsyncRawSubscriptionTypesClient.java b/src/main/java/com/intercom/api/resources/subscriptiontypes/AsyncRawSubscriptionTypesClient.java new file mode 100644 index 0000000..4735b46 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/subscriptiontypes/AsyncRawSubscriptionTypesClient.java @@ -0,0 +1,100 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.subscriptiontypes; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.types.Error; +import com.intercom.api.types.SubscriptionTypeList; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawSubscriptionTypesClient { + protected final ClientOptions clientOptions; + + public AsyncRawSubscriptionTypesClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can list all subscription types. A list of subscription type objects will be returned. + */ + public CompletableFuture> list() { + return list(null); + } + + /** + * You can list all subscription types. A list of subscription type objects will be returned. + */ + public CompletableFuture> list(RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("subscription_types") + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SubscriptionTypeList.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/intercom/api/resources/subscriptiontypes/AsyncSubscriptionTypesClient.java b/src/main/java/com/intercom/api/resources/subscriptiontypes/AsyncSubscriptionTypesClient.java index ad6e07c..3293dab 100644 --- a/src/main/java/com/intercom/api/resources/subscriptiontypes/AsyncSubscriptionTypesClient.java +++ b/src/main/java/com/intercom/api/resources/subscriptiontypes/AsyncSubscriptionTypesClient.java @@ -3,95 +3,39 @@ */ package com.intercom.api.resources.subscriptiontypes; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.ObjectMappers; import com.intercom.api.core.RequestOptions; -import com.intercom.api.errors.UnauthorizedError; -import com.intercom.api.types.Error; import com.intercom.api.types.SubscriptionTypeList; -import java.io.IOException; import java.util.concurrent.CompletableFuture; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; public class AsyncSubscriptionTypesClient { protected final ClientOptions clientOptions; + private final AsyncRawSubscriptionTypesClient rawClient; + public AsyncSubscriptionTypesClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new AsyncRawSubscriptionTypesClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawSubscriptionTypesClient withRawResponse() { + return this.rawClient; } /** * You can list all subscription types. A list of subscription type objects will be returned. */ public CompletableFuture list() { - return list(null); + return this.rawClient.list().thenApply(response -> response.body()); } /** * You can list all subscription types. A list of subscription type objects will be returned. */ public CompletableFuture list(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("subscription_types") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SubscriptionTypeList.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.list(requestOptions).thenApply(response -> response.body()); } } diff --git a/src/main/java/com/intercom/api/resources/subscriptiontypes/RawSubscriptionTypesClient.java b/src/main/java/com/intercom/api/resources/subscriptiontypes/RawSubscriptionTypesClient.java new file mode 100644 index 0000000..5f46955 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/subscriptiontypes/RawSubscriptionTypesClient.java @@ -0,0 +1,82 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.subscriptiontypes; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.types.Error; +import com.intercom.api.types.SubscriptionTypeList; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawSubscriptionTypesClient { + protected final ClientOptions clientOptions; + + public RawSubscriptionTypesClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can list all subscription types. A list of subscription type objects will be returned. + */ + public IntercomHttpResponse list() { + return list(null); + } + + /** + * You can list all subscription types. A list of subscription type objects will be returned. + */ + public IntercomHttpResponse list(RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("subscription_types") + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SubscriptionTypeList.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/intercom/api/resources/subscriptiontypes/SubscriptionTypesClient.java b/src/main/java/com/intercom/api/resources/subscriptiontypes/SubscriptionTypesClient.java index 95a4b41..3864aa9 100644 --- a/src/main/java/com/intercom/api/resources/subscriptiontypes/SubscriptionTypesClient.java +++ b/src/main/java/com/intercom/api/resources/subscriptiontypes/SubscriptionTypesClient.java @@ -3,75 +3,38 @@ */ package com.intercom.api.resources.subscriptiontypes; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.ObjectMappers; import com.intercom.api.core.RequestOptions; -import com.intercom.api.errors.UnauthorizedError; -import com.intercom.api.types.Error; import com.intercom.api.types.SubscriptionTypeList; -import java.io.IOException; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; public class SubscriptionTypesClient { protected final ClientOptions clientOptions; + private final RawSubscriptionTypesClient rawClient; + public SubscriptionTypesClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawSubscriptionTypesClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawSubscriptionTypesClient withRawResponse() { + return this.rawClient; } /** * You can list all subscription types. A list of subscription type objects will be returned. */ public SubscriptionTypeList list() { - return list(null); + return this.rawClient.list().body(); } /** * You can list all subscription types. A list of subscription type objects will be returned. */ public SubscriptionTypeList list(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("subscription_types") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SubscriptionTypeList.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.list(requestOptions).body(); } } diff --git a/src/main/java/com/intercom/api/resources/tags/AsyncRawTagsClient.java b/src/main/java/com/intercom/api/resources/tags/AsyncRawTagsClient.java new file mode 100644 index 0000000..8dd4803 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/tags/AsyncRawTagsClient.java @@ -0,0 +1,850 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.tags; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.BadRequestError; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.tags.requests.DeleteTagRequest; +import com.intercom.api.resources.tags.requests.FindTagRequest; +import com.intercom.api.resources.tags.requests.TagContactRequest; +import com.intercom.api.resources.tags.requests.TagConversationRequest; +import com.intercom.api.resources.tags.requests.TagTicketRequest; +import com.intercom.api.resources.tags.requests.UntagContactRequest; +import com.intercom.api.resources.tags.requests.UntagConversationRequest; +import com.intercom.api.resources.tags.requests.UntagTicketRequest; +import com.intercom.api.resources.tags.types.Tag; +import com.intercom.api.resources.tags.types.TagsCreateRequestBody; +import com.intercom.api.types.Error; +import com.intercom.api.types.TagList; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawTagsClient { + protected final ClientOptions clientOptions; + + public AsyncRawTagsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can tag a specific contact. This will return a tag object for the tag that was added to the contact. + */ + public CompletableFuture> tagContact(TagContactRequest request) { + return tagContact(request, null); + } + + /** + * You can tag a specific contact. This will return a tag object for the tag that was added to the contact. + */ + public CompletableFuture> tagContact( + TagContactRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("tags") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can remove tag from a specific contact. This will return a tag object for the tag that was removed from the contact. + */ + public CompletableFuture> untagContact(UntagContactRequest request) { + return untagContact(request, null); + } + + /** + * You can remove tag from a specific contact. This will return a tag object for the tag that was removed from the contact. + */ + public CompletableFuture> untagContact( + UntagContactRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("tags") + .addPathSegment(request.getTagId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can tag a specific conversation. This will return a tag object for the tag that was added to the conversation. + */ + public CompletableFuture> tagConversation(TagConversationRequest request) { + return tagConversation(request, null); + } + + /** + * You can tag a specific conversation. This will return a tag object for the tag that was added to the conversation. + */ + public CompletableFuture> tagConversation( + TagConversationRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations") + .addPathSegment(request.getConversationId()) + .addPathSegments("tags") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can remove tag from a specific conversation. This will return a tag object for the tag that was removed from the conversation. + */ + public CompletableFuture> untagConversation(UntagConversationRequest request) { + return untagConversation(request, null); + } + + /** + * You can remove tag from a specific conversation. This will return a tag object for the tag that was removed from the conversation. + */ + public CompletableFuture> untagConversation( + UntagConversationRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations") + .addPathSegment(request.getConversationId()) + .addPathSegments("tags") + .addPathSegment(request.getTagId()) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("DELETE", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can fetch a list of all tags for a given workspace. + */ + public CompletableFuture> list() { + return list(null); + } + + /** + * You can fetch a list of all tags for a given workspace. + */ + public CompletableFuture> list(RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("tags") + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TagList.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can use this endpoint to perform the following operations: + *

1. Create a new tag: You can create a new tag by passing in the tag name as specified in "Create or Update Tag Request Payload" described below.

+ *

2. Update an existing tag: You can update an existing tag by passing the id of the tag as specified in "Create or Update Tag Request Payload" described below.

+ *

3. Tag Companies: You can tag single company or a list of companies. You can tag a company by passing in the tag name and the company details as specified in "Tag Company Request Payload" described below. Also, if the tag doesn't exist then a new one will be created automatically.

+ *

4. Untag Companies: You can untag a single company or a list of companies. You can untag a company by passing in the tag id and the company details as specified in "Untag Company Request Payload" described below.

+ *

5. Tag Multiple Users: You can tag a list of users. You can tag the users by passing in the tag name and the user details as specified in "Tag Users Request Payload" described below.

+ *

Each operation will return a tag object.

+ */ + public CompletableFuture> create(TagsCreateRequestBody request) { + return create(request, null); + } + + /** + * You can use this endpoint to perform the following operations: + *

1. Create a new tag: You can create a new tag by passing in the tag name as specified in "Create or Update Tag Request Payload" described below.

+ *

2. Update an existing tag: You can update an existing tag by passing the id of the tag as specified in "Create or Update Tag Request Payload" described below.

+ *

3. Tag Companies: You can tag single company or a list of companies. You can tag a company by passing in the tag name and the company details as specified in "Tag Company Request Payload" described below. Also, if the tag doesn't exist then a new one will be created automatically.

+ *

4. Untag Companies: You can untag a single company or a list of companies. You can untag a company by passing in the tag id and the company details as specified in "Untag Company Request Payload" described below.

+ *

5. Tag Multiple Users: You can tag a list of users. You can tag the users by passing in the tag name and the user details as specified in "Tag Users Request Payload" described below.

+ *

Each operation will return a tag object.

+ */ + public CompletableFuture> create( + TagsCreateRequestBody request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("tags") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can fetch the details of tags that are on the workspace by their id. + * This will return a tag object. + */ + public CompletableFuture> find(FindTagRequest request) { + return find(request, null); + } + + /** + * You can fetch the details of tags that are on the workspace by their id. + * This will return a tag object. + */ + public CompletableFuture> find(FindTagRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("tags") + .addPathSegment(request.getTagId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can delete the details of tags that are on the workspace by passing in the id. + */ + public CompletableFuture> delete(DeleteTagRequest request) { + return delete(request, null); + } + + /** + * You can delete the details of tags that are on the workspace by passing in the id. + */ + public CompletableFuture> delete( + DeleteTagRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("tags") + .addPathSegment(request.getTagId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>(null, response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can tag a specific ticket. This will return a tag object for the tag that was added to the ticket. + */ + public CompletableFuture> tagTicket(TagTicketRequest request) { + return tagTicket(request, null); + } + + /** + * You can tag a specific ticket. This will return a tag object for the tag that was added to the ticket. + */ + public CompletableFuture> tagTicket( + TagTicketRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("tickets") + .addPathSegment(request.getTicketId()) + .addPathSegments("tags") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can remove tag from a specific ticket. This will return a tag object for the tag that was removed from the ticket. + */ + public CompletableFuture> untagTicket(UntagTicketRequest request) { + return untagTicket(request, null); + } + + /** + * You can remove tag from a specific ticket. This will return a tag object for the tag that was removed from the ticket. + */ + public CompletableFuture> untagTicket( + UntagTicketRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("tickets") + .addPathSegment(request.getTicketId()) + .addPathSegments("tags") + .addPathSegment(request.getTagId()) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("DELETE", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/intercom/api/resources/tags/AsyncTagsClient.java b/src/main/java/com/intercom/api/resources/tags/AsyncTagsClient.java index 9e45b30..3eaee6e 100644 --- a/src/main/java/com/intercom/api/resources/tags/AsyncTagsClient.java +++ b/src/main/java/com/intercom/api/resources/tags/AsyncTagsClient.java @@ -3,16 +3,8 @@ */ package com.intercom.api.resources.tags; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; import com.intercom.api.core.RequestOptions; -import com.intercom.api.errors.BadRequestError; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.tags.requests.DeleteTagRequest; import com.intercom.api.resources.tags.requests.FindTagRequest; import com.intercom.api.resources.tags.requests.TagContactRequest; @@ -23,392 +15,94 @@ import com.intercom.api.resources.tags.requests.UntagTicketRequest; import com.intercom.api.resources.tags.types.Tag; import com.intercom.api.resources.tags.types.TagsCreateRequestBody; -import com.intercom.api.types.Error; import com.intercom.api.types.TagList; -import java.io.IOException; import java.util.concurrent.CompletableFuture; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; public class AsyncTagsClient { protected final ClientOptions clientOptions; + private final AsyncRawTagsClient rawClient; + public AsyncTagsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new AsyncRawTagsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawTagsClient withRawResponse() { + return this.rawClient; } /** * You can tag a specific contact. This will return a tag object for the tag that was added to the contact. */ public CompletableFuture tagContact(TagContactRequest request) { - return tagContact(request, null); + return this.rawClient.tagContact(request).thenApply(response -> response.body()); } /** * You can tag a specific contact. This will return a tag object for the tag that was added to the contact. */ public CompletableFuture tagContact(TagContactRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("tags") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.tagContact(request, requestOptions).thenApply(response -> response.body()); } /** * You can remove tag from a specific contact. This will return a tag object for the tag that was removed from the contact. */ public CompletableFuture untagContact(UntagContactRequest request) { - return untagContact(request, null); + return this.rawClient.untagContact(request).thenApply(response -> response.body()); } /** * You can remove tag from a specific contact. This will return a tag object for the tag that was removed from the contact. */ public CompletableFuture untagContact(UntagContactRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("tags") - .addPathSegment(request.getTagId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.untagContact(request, requestOptions).thenApply(response -> response.body()); } /** * You can tag a specific conversation. This will return a tag object for the tag that was added to the conversation. */ public CompletableFuture tagConversation(TagConversationRequest request) { - return tagConversation(request, null); + return this.rawClient.tagConversation(request).thenApply(response -> response.body()); } /** * You can tag a specific conversation. This will return a tag object for the tag that was added to the conversation. */ public CompletableFuture tagConversation(TagConversationRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations") - .addPathSegment(request.getConversationId()) - .addPathSegments("tags") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.tagConversation(request, requestOptions).thenApply(response -> response.body()); } /** * You can remove tag from a specific conversation. This will return a tag object for the tag that was removed from the conversation. */ public CompletableFuture untagConversation(UntagConversationRequest request) { - return untagConversation(request, null); + return this.rawClient.untagConversation(request).thenApply(response -> response.body()); } /** * You can remove tag from a specific conversation. This will return a tag object for the tag that was removed from the conversation. */ public CompletableFuture untagConversation(UntagConversationRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations") - .addPathSegment(request.getConversationId()) - .addPathSegments("tags") - .addPathSegment(request.getTagId()) - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.untagConversation(request, requestOptions).thenApply(response -> response.body()); } /** * You can fetch a list of all tags for a given workspace. */ public CompletableFuture list() { - return list(null); + return this.rawClient.list().thenApply(response -> response.body()); } /** * You can fetch a list of all tags for a given workspace. */ public CompletableFuture list(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("tags") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TagList.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.list(requestOptions).thenApply(response -> response.body()); } /** @@ -421,7 +115,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { *

Each operation will return a tag object.

*/ public CompletableFuture create(TagsCreateRequestBody request) { - return create(request, null); + return this.rawClient.create(request).thenApply(response -> response.body()); } /** @@ -434,72 +128,7 @@ public CompletableFuture create(TagsCreateRequestBody request) { *

Each operation will return a tag object.

*/ public CompletableFuture create(TagsCreateRequestBody request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("tags") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.create(request, requestOptions).thenApply(response -> response.body()); } /** @@ -507,7 +136,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { * This will return a tag object. */ public CompletableFuture find(FindTagRequest request) { - return find(request, null); + return this.rawClient.find(request).thenApply(response -> response.body()); } /** @@ -515,288 +144,48 @@ public CompletableFuture find(FindTagRequest request) { * This will return a tag object. */ public CompletableFuture find(FindTagRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("tags") - .addPathSegment(request.getTagId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.find(request, requestOptions).thenApply(response -> response.body()); } /** * You can delete the details of tags that are on the workspace by passing in the id. */ public CompletableFuture delete(DeleteTagRequest request) { - return delete(request, null); + return this.rawClient.delete(request).thenApply(response -> response.body()); } /** * You can delete the details of tags that are on the workspace by passing in the id. */ public CompletableFuture delete(DeleteTagRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("tags") - .addPathSegment(request.getTagId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(null); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.delete(request, requestOptions).thenApply(response -> response.body()); } /** * You can tag a specific ticket. This will return a tag object for the tag that was added to the ticket. */ public CompletableFuture tagTicket(TagTicketRequest request) { - return tagTicket(request, null); + return this.rawClient.tagTicket(request).thenApply(response -> response.body()); } /** * You can tag a specific ticket. This will return a tag object for the tag that was added to the ticket. */ public CompletableFuture tagTicket(TagTicketRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("tickets") - .addPathSegment(request.getTicketId()) - .addPathSegments("tags") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.tagTicket(request, requestOptions).thenApply(response -> response.body()); } /** * You can remove tag from a specific ticket. This will return a tag object for the tag that was removed from the ticket. */ public CompletableFuture untagTicket(UntagTicketRequest request) { - return untagTicket(request, null); + return this.rawClient.untagTicket(request).thenApply(response -> response.body()); } /** * You can remove tag from a specific ticket. This will return a tag object for the tag that was removed from the ticket. */ public CompletableFuture untagTicket(UntagTicketRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("tickets") - .addPathSegment(request.getTicketId()) - .addPathSegments("tags") - .addPathSegment(request.getTagId()) - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.untagTicket(request, requestOptions).thenApply(response -> response.body()); } } diff --git a/src/main/java/com/intercom/api/resources/tags/RawTagsClient.java b/src/main/java/com/intercom/api/resources/tags/RawTagsClient.java new file mode 100644 index 0000000..8581eba --- /dev/null +++ b/src/main/java/com/intercom/api/resources/tags/RawTagsClient.java @@ -0,0 +1,668 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.tags; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.BadRequestError; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.tags.requests.DeleteTagRequest; +import com.intercom.api.resources.tags.requests.FindTagRequest; +import com.intercom.api.resources.tags.requests.TagContactRequest; +import com.intercom.api.resources.tags.requests.TagConversationRequest; +import com.intercom.api.resources.tags.requests.TagTicketRequest; +import com.intercom.api.resources.tags.requests.UntagContactRequest; +import com.intercom.api.resources.tags.requests.UntagConversationRequest; +import com.intercom.api.resources.tags.requests.UntagTicketRequest; +import com.intercom.api.resources.tags.types.Tag; +import com.intercom.api.resources.tags.types.TagsCreateRequestBody; +import com.intercom.api.types.Error; +import com.intercom.api.types.TagList; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawTagsClient { + protected final ClientOptions clientOptions; + + public RawTagsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can tag a specific contact. This will return a tag object for the tag that was added to the contact. + */ + public IntercomHttpResponse tagContact(TagContactRequest request) { + return tagContact(request, null); + } + + /** + * You can tag a specific contact. This will return a tag object for the tag that was added to the contact. + */ + public IntercomHttpResponse tagContact(TagContactRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("tags") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can remove tag from a specific contact. This will return a tag object for the tag that was removed from the contact. + */ + public IntercomHttpResponse untagContact(UntagContactRequest request) { + return untagContact(request, null); + } + + /** + * You can remove tag from a specific contact. This will return a tag object for the tag that was removed from the contact. + */ + public IntercomHttpResponse untagContact(UntagContactRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("contacts") + .addPathSegment(request.getContactId()) + .addPathSegments("tags") + .addPathSegment(request.getTagId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can tag a specific conversation. This will return a tag object for the tag that was added to the conversation. + */ + public IntercomHttpResponse tagConversation(TagConversationRequest request) { + return tagConversation(request, null); + } + + /** + * You can tag a specific conversation. This will return a tag object for the tag that was added to the conversation. + */ + public IntercomHttpResponse tagConversation(TagConversationRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations") + .addPathSegment(request.getConversationId()) + .addPathSegments("tags") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can remove tag from a specific conversation. This will return a tag object for the tag that was removed from the conversation. + */ + public IntercomHttpResponse untagConversation(UntagConversationRequest request) { + return untagConversation(request, null); + } + + /** + * You can remove tag from a specific conversation. This will return a tag object for the tag that was removed from the conversation. + */ + public IntercomHttpResponse untagConversation( + UntagConversationRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("conversations") + .addPathSegment(request.getConversationId()) + .addPathSegments("tags") + .addPathSegment(request.getTagId()) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("DELETE", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can fetch a list of all tags for a given workspace. + */ + public IntercomHttpResponse list() { + return list(null); + } + + /** + * You can fetch a list of all tags for a given workspace. + */ + public IntercomHttpResponse list(RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("tags") + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TagList.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can use this endpoint to perform the following operations: + *

1. Create a new tag: You can create a new tag by passing in the tag name as specified in "Create or Update Tag Request Payload" described below.

+ *

2. Update an existing tag: You can update an existing tag by passing the id of the tag as specified in "Create or Update Tag Request Payload" described below.

+ *

3. Tag Companies: You can tag single company or a list of companies. You can tag a company by passing in the tag name and the company details as specified in "Tag Company Request Payload" described below. Also, if the tag doesn't exist then a new one will be created automatically.

+ *

4. Untag Companies: You can untag a single company or a list of companies. You can untag a company by passing in the tag id and the company details as specified in "Untag Company Request Payload" described below.

+ *

5. Tag Multiple Users: You can tag a list of users. You can tag the users by passing in the tag name and the user details as specified in "Tag Users Request Payload" described below.

+ *

Each operation will return a tag object.

+ */ + public IntercomHttpResponse create(TagsCreateRequestBody request) { + return create(request, null); + } + + /** + * You can use this endpoint to perform the following operations: + *

1. Create a new tag: You can create a new tag by passing in the tag name as specified in "Create or Update Tag Request Payload" described below.

+ *

2. Update an existing tag: You can update an existing tag by passing the id of the tag as specified in "Create or Update Tag Request Payload" described below.

+ *

3. Tag Companies: You can tag single company or a list of companies. You can tag a company by passing in the tag name and the company details as specified in "Tag Company Request Payload" described below. Also, if the tag doesn't exist then a new one will be created automatically.

+ *

4. Untag Companies: You can untag a single company or a list of companies. You can untag a company by passing in the tag id and the company details as specified in "Untag Company Request Payload" described below.

+ *

5. Tag Multiple Users: You can tag a list of users. You can tag the users by passing in the tag name and the user details as specified in "Tag Users Request Payload" described below.

+ *

Each operation will return a tag object.

+ */ + public IntercomHttpResponse create(TagsCreateRequestBody request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("tags") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can fetch the details of tags that are on the workspace by their id. + * This will return a tag object. + */ + public IntercomHttpResponse find(FindTagRequest request) { + return find(request, null); + } + + /** + * You can fetch the details of tags that are on the workspace by their id. + * This will return a tag object. + */ + public IntercomHttpResponse find(FindTagRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("tags") + .addPathSegment(request.getTagId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can delete the details of tags that are on the workspace by passing in the id. + */ + public IntercomHttpResponse delete(DeleteTagRequest request) { + return delete(request, null); + } + + /** + * You can delete the details of tags that are on the workspace by passing in the id. + */ + public IntercomHttpResponse delete(DeleteTagRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("tags") + .addPathSegment(request.getTagId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>(null, response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can tag a specific ticket. This will return a tag object for the tag that was added to the ticket. + */ + public IntercomHttpResponse tagTicket(TagTicketRequest request) { + return tagTicket(request, null); + } + + /** + * You can tag a specific ticket. This will return a tag object for the tag that was added to the ticket. + */ + public IntercomHttpResponse tagTicket(TagTicketRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("tickets") + .addPathSegment(request.getTicketId()) + .addPathSegments("tags") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can remove tag from a specific ticket. This will return a tag object for the tag that was removed from the ticket. + */ + public IntercomHttpResponse untagTicket(UntagTicketRequest request) { + return untagTicket(request, null); + } + + /** + * You can remove tag from a specific ticket. This will return a tag object for the tag that was removed from the ticket. + */ + public IntercomHttpResponse untagTicket(UntagTicketRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("tickets") + .addPathSegment(request.getTicketId()) + .addPathSegments("tags") + .addPathSegment(request.getTagId()) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("DELETE", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/intercom/api/resources/tags/TagsClient.java b/src/main/java/com/intercom/api/resources/tags/TagsClient.java index 6bfeb25..e3b5d84 100644 --- a/src/main/java/com/intercom/api/resources/tags/TagsClient.java +++ b/src/main/java/com/intercom/api/resources/tags/TagsClient.java @@ -3,16 +3,8 @@ */ package com.intercom.api.resources.tags; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; import com.intercom.api.core.RequestOptions; -import com.intercom.api.errors.BadRequestError; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.tags.requests.DeleteTagRequest; import com.intercom.api.resources.tags.requests.FindTagRequest; import com.intercom.api.resources.tags.requests.TagContactRequest; @@ -23,309 +15,93 @@ import com.intercom.api.resources.tags.requests.UntagTicketRequest; import com.intercom.api.resources.tags.types.Tag; import com.intercom.api.resources.tags.types.TagsCreateRequestBody; -import com.intercom.api.types.Error; import com.intercom.api.types.TagList; -import java.io.IOException; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; public class TagsClient { protected final ClientOptions clientOptions; + private final RawTagsClient rawClient; + public TagsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawTagsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawTagsClient withRawResponse() { + return this.rawClient; } /** * You can tag a specific contact. This will return a tag object for the tag that was added to the contact. */ public Tag tagContact(TagContactRequest request) { - return tagContact(request, null); + return this.rawClient.tagContact(request).body(); } /** * You can tag a specific contact. This will return a tag object for the tag that was added to the contact. */ public Tag tagContact(TagContactRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("tags") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.tagContact(request, requestOptions).body(); } /** * You can remove tag from a specific contact. This will return a tag object for the tag that was removed from the contact. */ public Tag untagContact(UntagContactRequest request) { - return untagContact(request, null); + return this.rawClient.untagContact(request).body(); } /** * You can remove tag from a specific contact. This will return a tag object for the tag that was removed from the contact. */ public Tag untagContact(UntagContactRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("contacts") - .addPathSegment(request.getContactId()) - .addPathSegments("tags") - .addPathSegment(request.getTagId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.untagContact(request, requestOptions).body(); } /** * You can tag a specific conversation. This will return a tag object for the tag that was added to the conversation. */ public Tag tagConversation(TagConversationRequest request) { - return tagConversation(request, null); + return this.rawClient.tagConversation(request).body(); } /** * You can tag a specific conversation. This will return a tag object for the tag that was added to the conversation. */ public Tag tagConversation(TagConversationRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations") - .addPathSegment(request.getConversationId()) - .addPathSegments("tags") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.tagConversation(request, requestOptions).body(); } /** * You can remove tag from a specific conversation. This will return a tag object for the tag that was removed from the conversation. */ public Tag untagConversation(UntagConversationRequest request) { - return untagConversation(request, null); + return this.rawClient.untagConversation(request).body(); } /** * You can remove tag from a specific conversation. This will return a tag object for the tag that was removed from the conversation. */ public Tag untagConversation(UntagConversationRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("conversations") - .addPathSegment(request.getConversationId()) - .addPathSegments("tags") - .addPathSegment(request.getTagId()) - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.untagConversation(request, requestOptions).body(); } /** * You can fetch a list of all tags for a given workspace. */ public TagList list() { - return list(null); + return this.rawClient.list().body(); } /** * You can fetch a list of all tags for a given workspace. */ public TagList list(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("tags") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TagList.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.list(requestOptions).body(); } /** @@ -338,7 +114,7 @@ public TagList list(RequestOptions requestOptions) { *

Each operation will return a tag object.

*/ public Tag create(TagsCreateRequestBody request) { - return create(request, null); + return this.rawClient.create(request).body(); } /** @@ -351,55 +127,7 @@ public Tag create(TagsCreateRequestBody request) { *

Each operation will return a tag object.

*/ public Tag create(TagsCreateRequestBody request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("tags") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.create(request, requestOptions).body(); } /** @@ -407,7 +135,7 @@ public Tag create(TagsCreateRequestBody request, RequestOptions requestOptions) * This will return a tag object. */ public Tag find(FindTagRequest request) { - return find(request, null); + return this.rawClient.find(request).body(); } /** @@ -415,223 +143,48 @@ public Tag find(FindTagRequest request) { * This will return a tag object. */ public Tag find(FindTagRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("tags") - .addPathSegment(request.getTagId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.find(request, requestOptions).body(); } /** * You can delete the details of tags that are on the workspace by passing in the id. */ public void delete(DeleteTagRequest request) { - delete(request, null); + this.rawClient.delete(request).body(); } /** * You can delete the details of tags that are on the workspace by passing in the id. */ public void delete(DeleteTagRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("tags") - .addPathSegment(request.getTagId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + this.rawClient.delete(request, requestOptions).body(); } /** * You can tag a specific ticket. This will return a tag object for the tag that was added to the ticket. */ public Tag tagTicket(TagTicketRequest request) { - return tagTicket(request, null); + return this.rawClient.tagTicket(request).body(); } /** * You can tag a specific ticket. This will return a tag object for the tag that was added to the ticket. */ public Tag tagTicket(TagTicketRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("tickets") - .addPathSegment(request.getTicketId()) - .addPathSegments("tags") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.tagTicket(request, requestOptions).body(); } /** * You can remove tag from a specific ticket. This will return a tag object for the tag that was removed from the ticket. */ public Tag untagTicket(UntagTicketRequest request) { - return untagTicket(request, null); + return this.rawClient.untagTicket(request).body(); } /** * You can remove tag from a specific ticket. This will return a tag object for the tag that was removed from the ticket. */ public Tag untagTicket(UntagTicketRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("tickets") - .addPathSegment(request.getTicketId()) - .addPathSegments("tags") - .addPathSegment(request.getTagId()) - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Tag.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.untagTicket(request, requestOptions).body(); } } diff --git a/src/main/java/com/intercom/api/resources/teams/AsyncRawTeamsClient.java b/src/main/java/com/intercom/api/resources/teams/AsyncRawTeamsClient.java new file mode 100644 index 0000000..6091ba7 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/teams/AsyncRawTeamsClient.java @@ -0,0 +1,175 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.teams; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.teams.requests.FindTeamRequest; +import com.intercom.api.resources.teams.types.Team; +import com.intercom.api.types.Error; +import com.intercom.api.types.TeamList; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawTeamsClient { + protected final ClientOptions clientOptions; + + public AsyncRawTeamsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * This will return a list of team objects for the App. + */ + public CompletableFuture> list() { + return list(null); + } + + /** + * This will return a list of team objects for the App. + */ + public CompletableFuture> list(RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("teams") + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TeamList.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can fetch the details of a single team, containing an array of admins that belong to this team. + */ + public CompletableFuture> find(FindTeamRequest request) { + return find(request, null); + } + + /** + * You can fetch the details of a single team, containing an array of admins that belong to this team. + */ + public CompletableFuture> find(FindTeamRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("teams") + .addPathSegment(request.getTeamId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Team.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/intercom/api/resources/teams/AsyncTeamsClient.java b/src/main/java/com/intercom/api/resources/teams/AsyncTeamsClient.java index b9f824b..fcc7824 100644 --- a/src/main/java/com/intercom/api/resources/teams/AsyncTeamsClient.java +++ b/src/main/java/com/intercom/api/resources/teams/AsyncTeamsClient.java @@ -3,166 +3,55 @@ */ package com.intercom.api.resources.teams; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.ObjectMappers; import com.intercom.api.core.RequestOptions; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.teams.requests.FindTeamRequest; import com.intercom.api.resources.teams.types.Team; -import com.intercom.api.types.Error; import com.intercom.api.types.TeamList; -import java.io.IOException; import java.util.concurrent.CompletableFuture; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; public class AsyncTeamsClient { protected final ClientOptions clientOptions; + private final AsyncRawTeamsClient rawClient; + public AsyncTeamsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new AsyncRawTeamsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawTeamsClient withRawResponse() { + return this.rawClient; } /** * This will return a list of team objects for the App. */ public CompletableFuture list() { - return list(null); + return this.rawClient.list().thenApply(response -> response.body()); } /** * This will return a list of team objects for the App. */ public CompletableFuture list(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("teams") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TeamList.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.list(requestOptions).thenApply(response -> response.body()); } /** * You can fetch the details of a single team, containing an array of admins that belong to this team. */ public CompletableFuture find(FindTeamRequest request) { - return find(request, null); + return this.rawClient.find(request).thenApply(response -> response.body()); } /** * You can fetch the details of a single team, containing an array of admins that belong to this team. */ public CompletableFuture find(FindTeamRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("teams") - .addPathSegment(request.getTeamId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Team.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.find(request, requestOptions).thenApply(response -> response.body()); } } diff --git a/src/main/java/com/intercom/api/resources/teams/RawTeamsClient.java b/src/main/java/com/intercom/api/resources/teams/RawTeamsClient.java new file mode 100644 index 0000000..0f7511e --- /dev/null +++ b/src/main/java/com/intercom/api/resources/teams/RawTeamsClient.java @@ -0,0 +1,140 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.teams; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.teams.requests.FindTeamRequest; +import com.intercom.api.resources.teams.types.Team; +import com.intercom.api.types.Error; +import com.intercom.api.types.TeamList; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawTeamsClient { + protected final ClientOptions clientOptions; + + public RawTeamsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * This will return a list of team objects for the App. + */ + public IntercomHttpResponse list() { + return list(null); + } + + /** + * This will return a list of team objects for the App. + */ + public IntercomHttpResponse list(RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("teams") + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TeamList.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can fetch the details of a single team, containing an array of admins that belong to this team. + */ + public IntercomHttpResponse find(FindTeamRequest request) { + return find(request, null); + } + + /** + * You can fetch the details of a single team, containing an array of admins that belong to this team. + */ + public IntercomHttpResponse find(FindTeamRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("teams") + .addPathSegment(request.getTeamId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Team.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/intercom/api/resources/teams/TeamsClient.java b/src/main/java/com/intercom/api/resources/teams/TeamsClient.java index 5c489b8..b8e5983 100644 --- a/src/main/java/com/intercom/api/resources/teams/TeamsClient.java +++ b/src/main/java/com/intercom/api/resources/teams/TeamsClient.java @@ -3,131 +3,54 @@ */ package com.intercom.api.resources.teams; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.ObjectMappers; import com.intercom.api.core.RequestOptions; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.teams.requests.FindTeamRequest; import com.intercom.api.resources.teams.types.Team; -import com.intercom.api.types.Error; import com.intercom.api.types.TeamList; -import java.io.IOException; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; public class TeamsClient { protected final ClientOptions clientOptions; + private final RawTeamsClient rawClient; + public TeamsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawTeamsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawTeamsClient withRawResponse() { + return this.rawClient; } /** * This will return a list of team objects for the App. */ public TeamList list() { - return list(null); + return this.rawClient.list().body(); } /** * This will return a list of team objects for the App. */ public TeamList list(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("teams") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TeamList.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.list(requestOptions).body(); } /** * You can fetch the details of a single team, containing an array of admins that belong to this team. */ public Team find(FindTeamRequest request) { - return find(request, null); + return this.rawClient.find(request).body(); } /** * You can fetch the details of a single team, containing an array of admins that belong to this team. */ public Team find(FindTeamRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("teams") - .addPathSegment(request.getTeamId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Team.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.find(request, requestOptions).body(); } } diff --git a/src/main/java/com/intercom/api/resources/tickets/AsyncRawTicketsClient.java b/src/main/java/com/intercom/api/resources/tickets/AsyncRawTicketsClient.java new file mode 100644 index 0000000..a081d11 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/tickets/AsyncRawTicketsClient.java @@ -0,0 +1,551 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.tickets; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.core.pagination.SyncPagingIterable; +import com.intercom.api.errors.BadRequestError; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.tickets.requests.CreateTicketRequest; +import com.intercom.api.resources.tickets.requests.FindTicketRequest; +import com.intercom.api.resources.tickets.requests.ReplyToTicketRequest; +import com.intercom.api.resources.tickets.requests.UpdateTicketRequest; +import com.intercom.api.resources.tickets.types.Ticket; +import com.intercom.api.types.CursorPages; +import com.intercom.api.types.Error; +import com.intercom.api.types.SearchRequest; +import com.intercom.api.types.StartingAfterPaging; +import com.intercom.api.types.TicketList; +import com.intercom.api.types.TicketReply; +import java.io.IOException; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawTicketsClient { + protected final ClientOptions clientOptions; + + public AsyncRawTicketsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can reply to a ticket with a message from an admin or on behalf of a contact, or with a note for admins. + */ + public CompletableFuture> reply(ReplyToTicketRequest request) { + return reply(request, null); + } + + /** + * You can reply to a ticket with a message from an admin or on behalf of a contact, or with a note for admins. + */ + public CompletableFuture> reply( + ReplyToTicketRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("tickets") + .addPathSegment(request.getTicketId()) + .addPathSegments("reply") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request.getBody()), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketReply.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can create a new ticket. + */ + public CompletableFuture> create(CreateTicketRequest request) { + return create(request, null); + } + + /** + * You can create a new ticket. + */ + public CompletableFuture> create( + CreateTicketRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("tickets") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Ticket.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can fetch the details of a single ticket. + */ + public CompletableFuture> get(FindTicketRequest request) { + return get(request, null); + } + + /** + * You can fetch the details of a single ticket. + */ + public CompletableFuture> get( + FindTicketRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("tickets") + .addPathSegment(request.getTicketId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Ticket.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can update a ticket. + */ + public CompletableFuture> update(UpdateTicketRequest request) { + return update(request, null); + } + + /** + * You can update a ticket. + */ + public CompletableFuture> update( + UpdateTicketRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("tickets") + .addPathSegment(request.getTicketId()) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Ticket.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can search for multiple tickets by the value of their attributes in order to fetch exactly which ones you want. + *

To search for tickets, you send a POST request to https://api.intercom.io/tickets/search.

+ *

This will accept a query object in the body which will define your filters. + * {% admonition type="warning" name="Optimizing search queries" %} + * Search queries can be complex, so optimizing them can help the performance of your search. + * Use the AND and OR operators to combine multiple filters to get the exact results you need and utilize + * pagination to limit the number of results returned. The default is 20 results per page. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %}

+ *

Nesting & Limitations

+ *

You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4). + * There are some limitations to the amount of multiples there can be:

+ *
    + *
  • There's a limit of max 2 nested filters
  • + *
  • There's a limit of max 15 filters for each AND or OR group
  • + *
+ *

Accepted Fields

+ *

Most keys listed as part of the Ticket model are searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as created_at accepts a date, the value cannot be a string such as "foobar").

+ *

| Field | Type | + * | :---------------------------------------- | :--------------------------------------------------------------------------------------- | + * | id | String | + * | created_at | Date (UNIX timestamp) | + * | updated_at | Date (UNIX timestamp) | + * | default_title | String | + * | default_description | String | + * | category | String | + * | ticket_type_id | String | + * | contact_ids | String | + * | teammate_ids | String | + * | admin_assignee_id | String | + * | team_assignee_id | String | + * | open | Boolean | + * | state | String | + * | snoozed_until | Date (UNIX timestamp) | + * | ticket_attribute.{id} | String or Boolean or Date (UNIX timestamp) or Float or Integer |

+ *

Accepted Operators

+ *

{% admonition type="info" name="Searching based on created_at" %} + * You may use the <= or >= operators to search by created_at. + * {% /admonition %}

+ *

The table below shows the operators you can use to define how you want to search for the value. The operator should be put in as a string ("="). The operator has to be compatible with the field's type (eg. you cannot search with > for a given string value as it's only compatible for integer's and dates).

+ *

| Operator | Valid Types | Description | + * | :------- | :----------------------------- | :----------------------------------------------------------- | + * | = | All | Equals | + * | != | All | Doesn't Equal | + * | IN | All | In Shortcut for OR queries Values most be in Array | + * | NIN | All | Not In Shortcut for OR ! queries Values must be in Array | + * | > | Integer Date (UNIX Timestamp) | Greater (or equal) than | + * | < | Integer Date (UNIX Timestamp) | Lower (or equal) than | + * | ~ | String | Contains | + * | !~ | String | Doesn't Contain | + * | ^ | String | Starts With | + * | $ | String | Ends With |

+ */ + public CompletableFuture>> search(SearchRequest request) { + return search(request, null); + } + + /** + * You can search for multiple tickets by the value of their attributes in order to fetch exactly which ones you want. + *

To search for tickets, you send a POST request to https://api.intercom.io/tickets/search.

+ *

This will accept a query object in the body which will define your filters. + * {% admonition type="warning" name="Optimizing search queries" %} + * Search queries can be complex, so optimizing them can help the performance of your search. + * Use the AND and OR operators to combine multiple filters to get the exact results you need and utilize + * pagination to limit the number of results returned. The default is 20 results per page. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %}

+ *

Nesting & Limitations

+ *

You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4). + * There are some limitations to the amount of multiples there can be:

+ *
    + *
  • There's a limit of max 2 nested filters
  • + *
  • There's a limit of max 15 filters for each AND or OR group
  • + *
+ *

Accepted Fields

+ *

Most keys listed as part of the Ticket model are searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as created_at accepts a date, the value cannot be a string such as "foobar").

+ *

| Field | Type | + * | :---------------------------------------- | :--------------------------------------------------------------------------------------- | + * | id | String | + * | created_at | Date (UNIX timestamp) | + * | updated_at | Date (UNIX timestamp) | + * | default_title | String | + * | default_description | String | + * | category | String | + * | ticket_type_id | String | + * | contact_ids | String | + * | teammate_ids | String | + * | admin_assignee_id | String | + * | team_assignee_id | String | + * | open | Boolean | + * | state | String | + * | snoozed_until | Date (UNIX timestamp) | + * | ticket_attribute.{id} | String or Boolean or Date (UNIX timestamp) or Float or Integer |

+ *

Accepted Operators

+ *

{% admonition type="info" name="Searching based on created_at" %} + * You may use the <= or >= operators to search by created_at. + * {% /admonition %}

+ *

The table below shows the operators you can use to define how you want to search for the value. The operator should be put in as a string ("="). The operator has to be compatible with the field's type (eg. you cannot search with > for a given string value as it's only compatible for integer's and dates).

+ *

| Operator | Valid Types | Description | + * | :------- | :----------------------------- | :----------------------------------------------------------- | + * | = | All | Equals | + * | != | All | Doesn't Equal | + * | IN | All | In Shortcut for OR queries Values most be in Array | + * | NIN | All | Not In Shortcut for OR ! queries Values must be in Array | + * | > | Integer Date (UNIX Timestamp) | Greater (or equal) than | + * | < | Integer Date (UNIX Timestamp) | Lower (or equal) than | + * | ~ | String | Contains | + * | !~ | String | Doesn't Contain | + * | ^ | String | Starts With | + * | $ | String | Ends With |

+ */ + public CompletableFuture>> search( + SearchRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("tickets/search") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture>> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + TicketList parsedResponse = + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketList.class); + Optional startingAfter = parsedResponse + .getPages() + .flatMap(CursorPages::getNext) + .flatMap(StartingAfterPaging::getStartingAfter); + Optional pagination = request.getPagination() + .map(pagination_ -> StartingAfterPaging.builder() + .from(pagination_) + .startingAfter(startingAfter) + .build()); + SearchRequest nextRequest = SearchRequest.builder() + .from(request) + .pagination(pagination) + .build(); + List result = parsedResponse.getTickets(); + future.complete(new IntercomHttpResponse<>( + new SyncPagingIterable(startingAfter.isPresent(), result, () -> { + try { + return search(nextRequest, requestOptions) + .get() + .body(); + } catch (InterruptedException | ExecutionException e) { + throw new RuntimeException(e); + } + }), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/intercom/api/resources/tickets/AsyncTicketsClient.java b/src/main/java/com/intercom/api/resources/tickets/AsyncTicketsClient.java index ab079c5..40832be 100644 --- a/src/main/java/com/intercom/api/resources/tickets/AsyncTicketsClient.java +++ b/src/main/java/com/intercom/api/resources/tickets/AsyncTicketsClient.java @@ -3,340 +3,89 @@ */ package com.intercom.api.resources.tickets; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; import com.intercom.api.core.RequestOptions; import com.intercom.api.core.pagination.SyncPagingIterable; -import com.intercom.api.errors.BadRequestError; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.tickets.requests.CreateTicketRequest; import com.intercom.api.resources.tickets.requests.FindTicketRequest; import com.intercom.api.resources.tickets.requests.ReplyToTicketRequest; import com.intercom.api.resources.tickets.requests.UpdateTicketRequest; import com.intercom.api.resources.tickets.types.Ticket; -import com.intercom.api.types.CursorPages; -import com.intercom.api.types.Error; import com.intercom.api.types.SearchRequest; -import com.intercom.api.types.StartingAfterPaging; -import com.intercom.api.types.TicketList; import com.intercom.api.types.TicketReply; -import java.io.IOException; -import java.util.List; -import java.util.Optional; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; public class AsyncTicketsClient { protected final ClientOptions clientOptions; + private final AsyncRawTicketsClient rawClient; + public AsyncTicketsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new AsyncRawTicketsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawTicketsClient withRawResponse() { + return this.rawClient; } /** * You can reply to a ticket with a message from an admin or on behalf of a contact, or with a note for admins. */ public CompletableFuture reply(ReplyToTicketRequest request) { - return reply(request, null); + return this.rawClient.reply(request).thenApply(response -> response.body()); } /** * You can reply to a ticket with a message from an admin or on behalf of a contact, or with a note for admins. */ public CompletableFuture reply(ReplyToTicketRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("tickets") - .addPathSegment(request.getTicketId()) - .addPathSegments("reply") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request.getBody()), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketReply.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.reply(request, requestOptions).thenApply(response -> response.body()); } /** * You can create a new ticket. */ public CompletableFuture create(CreateTicketRequest request) { - return create(request, null); + return this.rawClient.create(request).thenApply(response -> response.body()); } /** * You can create a new ticket. */ public CompletableFuture create(CreateTicketRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("tickets") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Ticket.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.create(request, requestOptions).thenApply(response -> response.body()); } /** * You can fetch the details of a single ticket. */ public CompletableFuture get(FindTicketRequest request) { - return get(request, null); + return this.rawClient.get(request).thenApply(response -> response.body()); } /** * You can fetch the details of a single ticket. */ public CompletableFuture get(FindTicketRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("tickets") - .addPathSegment(request.getTicketId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Ticket.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.get(request, requestOptions).thenApply(response -> response.body()); } /** * You can update a ticket. */ public CompletableFuture update(UpdateTicketRequest request) { - return update(request, null); + return this.rawClient.update(request).thenApply(response -> response.body()); } /** * You can update a ticket. */ public CompletableFuture update(UpdateTicketRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("tickets") - .addPathSegment(request.getTicketId()) - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PUT", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Ticket.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.update(request, requestOptions).thenApply(response -> response.body()); } /** @@ -394,7 +143,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { * | $ | String | Ends With |

*/ public CompletableFuture> search(SearchRequest request) { - return search(request, null); + return this.rawClient.search(request).thenApply(response -> response.body()); } /** @@ -452,75 +201,6 @@ public CompletableFuture> search(SearchRequest reques * | $ | String | Ends With |

*/ public CompletableFuture> search(SearchRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("tickets/search") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - TicketList parsedResponse = - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketList.class); - Optional startingAfter = parsedResponse - .getPages() - .flatMap(CursorPages::getNext) - .flatMap(StartingAfterPaging::getStartingAfter); - Optional pagination = request.getPagination() - .map(pagination_ -> StartingAfterPaging.builder() - .from(pagination_) - .startingAfter(startingAfter) - .build()); - SearchRequest nextRequest = SearchRequest.builder() - .from(request) - .pagination(pagination) - .build(); - List result = parsedResponse.getTickets(); - future.complete(new SyncPagingIterable(startingAfter.isPresent(), result, () -> { - try { - return search(nextRequest, requestOptions).get(); - } catch (InterruptedException | ExecutionException e) { - throw new RuntimeException(e); - } - })); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.search(request, requestOptions).thenApply(response -> response.body()); } } diff --git a/src/main/java/com/intercom/api/resources/tickets/RawTicketsClient.java b/src/main/java/com/intercom/api/resources/tickets/RawTicketsClient.java new file mode 100644 index 0000000..7fd2ea5 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/tickets/RawTicketsClient.java @@ -0,0 +1,458 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.tickets; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.core.pagination.SyncPagingIterable; +import com.intercom.api.errors.BadRequestError; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.tickets.requests.CreateTicketRequest; +import com.intercom.api.resources.tickets.requests.FindTicketRequest; +import com.intercom.api.resources.tickets.requests.ReplyToTicketRequest; +import com.intercom.api.resources.tickets.requests.UpdateTicketRequest; +import com.intercom.api.resources.tickets.types.Ticket; +import com.intercom.api.types.CursorPages; +import com.intercom.api.types.Error; +import com.intercom.api.types.SearchRequest; +import com.intercom.api.types.StartingAfterPaging; +import com.intercom.api.types.TicketList; +import com.intercom.api.types.TicketReply; +import java.io.IOException; +import java.util.List; +import java.util.Optional; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawTicketsClient { + protected final ClientOptions clientOptions; + + public RawTicketsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can reply to a ticket with a message from an admin or on behalf of a contact, or with a note for admins. + */ + public IntercomHttpResponse reply(ReplyToTicketRequest request) { + return reply(request, null); + } + + /** + * You can reply to a ticket with a message from an admin or on behalf of a contact, or with a note for admins. + */ + public IntercomHttpResponse reply(ReplyToTicketRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("tickets") + .addPathSegment(request.getTicketId()) + .addPathSegments("reply") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request.getBody()), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketReply.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can create a new ticket. + */ + public IntercomHttpResponse create(CreateTicketRequest request) { + return create(request, null); + } + + /** + * You can create a new ticket. + */ + public IntercomHttpResponse create(CreateTicketRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("tickets") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Ticket.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can fetch the details of a single ticket. + */ + public IntercomHttpResponse get(FindTicketRequest request) { + return get(request, null); + } + + /** + * You can fetch the details of a single ticket. + */ + public IntercomHttpResponse get(FindTicketRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("tickets") + .addPathSegment(request.getTicketId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Ticket.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can update a ticket. + */ + public IntercomHttpResponse update(UpdateTicketRequest request) { + return update(request, null); + } + + /** + * You can update a ticket. + */ + public IntercomHttpResponse update(UpdateTicketRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("tickets") + .addPathSegment(request.getTicketId()) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Ticket.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can search for multiple tickets by the value of their attributes in order to fetch exactly which ones you want. + *

To search for tickets, you send a POST request to https://api.intercom.io/tickets/search.

+ *

This will accept a query object in the body which will define your filters. + * {% admonition type="warning" name="Optimizing search queries" %} + * Search queries can be complex, so optimizing them can help the performance of your search. + * Use the AND and OR operators to combine multiple filters to get the exact results you need and utilize + * pagination to limit the number of results returned. The default is 20 results per page. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %}

+ *

Nesting & Limitations

+ *

You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4). + * There are some limitations to the amount of multiples there can be:

+ *
    + *
  • There's a limit of max 2 nested filters
  • + *
  • There's a limit of max 15 filters for each AND or OR group
  • + *
+ *

Accepted Fields

+ *

Most keys listed as part of the Ticket model are searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as created_at accepts a date, the value cannot be a string such as "foobar").

+ *

| Field | Type | + * | :---------------------------------------- | :--------------------------------------------------------------------------------------- | + * | id | String | + * | created_at | Date (UNIX timestamp) | + * | updated_at | Date (UNIX timestamp) | + * | default_title | String | + * | default_description | String | + * | category | String | + * | ticket_type_id | String | + * | contact_ids | String | + * | teammate_ids | String | + * | admin_assignee_id | String | + * | team_assignee_id | String | + * | open | Boolean | + * | state | String | + * | snoozed_until | Date (UNIX timestamp) | + * | ticket_attribute.{id} | String or Boolean or Date (UNIX timestamp) or Float or Integer |

+ *

Accepted Operators

+ *

{% admonition type="info" name="Searching based on created_at" %} + * You may use the <= or >= operators to search by created_at. + * {% /admonition %}

+ *

The table below shows the operators you can use to define how you want to search for the value. The operator should be put in as a string ("="). The operator has to be compatible with the field's type (eg. you cannot search with > for a given string value as it's only compatible for integer's and dates).

+ *

| Operator | Valid Types | Description | + * | :------- | :----------------------------- | :----------------------------------------------------------- | + * | = | All | Equals | + * | != | All | Doesn't Equal | + * | IN | All | In Shortcut for OR queries Values most be in Array | + * | NIN | All | Not In Shortcut for OR ! queries Values must be in Array | + * | > | Integer Date (UNIX Timestamp) | Greater (or equal) than | + * | < | Integer Date (UNIX Timestamp) | Lower (or equal) than | + * | ~ | String | Contains | + * | !~ | String | Doesn't Contain | + * | ^ | String | Starts With | + * | $ | String | Ends With |

+ */ + public IntercomHttpResponse> search(SearchRequest request) { + return search(request, null); + } + + /** + * You can search for multiple tickets by the value of their attributes in order to fetch exactly which ones you want. + *

To search for tickets, you send a POST request to https://api.intercom.io/tickets/search.

+ *

This will accept a query object in the body which will define your filters. + * {% admonition type="warning" name="Optimizing search queries" %} + * Search queries can be complex, so optimizing them can help the performance of your search. + * Use the AND and OR operators to combine multiple filters to get the exact results you need and utilize + * pagination to limit the number of results returned. The default is 20 results per page. + * See the pagination section for more details on how to use the starting_after param. + * {% /admonition %}

+ *

Nesting & Limitations

+ *

You can nest these filters in order to get even more granular insights that pinpoint exactly what you need. Example: (1 OR 2) AND (3 OR 4). + * There are some limitations to the amount of multiples there can be:

+ *
    + *
  • There's a limit of max 2 nested filters
  • + *
  • There's a limit of max 15 filters for each AND or OR group
  • + *
+ *

Accepted Fields

+ *

Most keys listed as part of the Ticket model are searchable, whether writeable or not. The value you search for has to match the accepted type, otherwise the query will fail (ie. as created_at accepts a date, the value cannot be a string such as "foobar").

+ *

| Field | Type | + * | :---------------------------------------- | :--------------------------------------------------------------------------------------- | + * | id | String | + * | created_at | Date (UNIX timestamp) | + * | updated_at | Date (UNIX timestamp) | + * | default_title | String | + * | default_description | String | + * | category | String | + * | ticket_type_id | String | + * | contact_ids | String | + * | teammate_ids | String | + * | admin_assignee_id | String | + * | team_assignee_id | String | + * | open | Boolean | + * | state | String | + * | snoozed_until | Date (UNIX timestamp) | + * | ticket_attribute.{id} | String or Boolean or Date (UNIX timestamp) or Float or Integer |

+ *

Accepted Operators

+ *

{% admonition type="info" name="Searching based on created_at" %} + * You may use the <= or >= operators to search by created_at. + * {% /admonition %}

+ *

The table below shows the operators you can use to define how you want to search for the value. The operator should be put in as a string ("="). The operator has to be compatible with the field's type (eg. you cannot search with > for a given string value as it's only compatible for integer's and dates).

+ *

| Operator | Valid Types | Description | + * | :------- | :----------------------------- | :----------------------------------------------------------- | + * | = | All | Equals | + * | != | All | Doesn't Equal | + * | IN | All | In Shortcut for OR queries Values most be in Array | + * | NIN | All | Not In Shortcut for OR ! queries Values must be in Array | + * | > | Integer Date (UNIX Timestamp) | Greater (or equal) than | + * | < | Integer Date (UNIX Timestamp) | Lower (or equal) than | + * | ~ | String | Contains | + * | !~ | String | Doesn't Contain | + * | ^ | String | Starts With | + * | $ | String | Ends With |

+ */ + public IntercomHttpResponse> search( + SearchRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("tickets/search") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + TicketList parsedResponse = + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketList.class); + Optional startingAfter = parsedResponse + .getPages() + .flatMap(CursorPages::getNext) + .flatMap(StartingAfterPaging::getStartingAfter); + Optional pagination = request.getPagination() + .map(pagination_ -> StartingAfterPaging.builder() + .from(pagination_) + .startingAfter(startingAfter) + .build()); + SearchRequest nextRequest = SearchRequest.builder() + .from(request) + .pagination(pagination) + .build(); + List result = parsedResponse.getTickets(); + return new IntercomHttpResponse<>( + new SyncPagingIterable( + startingAfter.isPresent(), result, () -> search(nextRequest, requestOptions) + .body()), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/intercom/api/resources/tickets/TicketsClient.java b/src/main/java/com/intercom/api/resources/tickets/TicketsClient.java index a1e6ce3..ccfdb01 100644 --- a/src/main/java/com/intercom/api/resources/tickets/TicketsClient.java +++ b/src/main/java/com/intercom/api/resources/tickets/TicketsClient.java @@ -3,272 +3,88 @@ */ package com.intercom.api.resources.tickets; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; import com.intercom.api.core.RequestOptions; import com.intercom.api.core.pagination.SyncPagingIterable; -import com.intercom.api.errors.BadRequestError; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.tickets.requests.CreateTicketRequest; import com.intercom.api.resources.tickets.requests.FindTicketRequest; import com.intercom.api.resources.tickets.requests.ReplyToTicketRequest; import com.intercom.api.resources.tickets.requests.UpdateTicketRequest; import com.intercom.api.resources.tickets.types.Ticket; -import com.intercom.api.types.CursorPages; -import com.intercom.api.types.Error; import com.intercom.api.types.SearchRequest; -import com.intercom.api.types.StartingAfterPaging; -import com.intercom.api.types.TicketList; import com.intercom.api.types.TicketReply; -import java.io.IOException; -import java.util.List; -import java.util.Optional; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; public class TicketsClient { protected final ClientOptions clientOptions; + private final RawTicketsClient rawClient; + public TicketsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawTicketsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawTicketsClient withRawResponse() { + return this.rawClient; } /** * You can reply to a ticket with a message from an admin or on behalf of a contact, or with a note for admins. */ public TicketReply reply(ReplyToTicketRequest request) { - return reply(request, null); + return this.rawClient.reply(request).body(); } /** * You can reply to a ticket with a message from an admin or on behalf of a contact, or with a note for admins. */ public TicketReply reply(ReplyToTicketRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("tickets") - .addPathSegment(request.getTicketId()) - .addPathSegments("reply") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request.getBody()), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketReply.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.reply(request, requestOptions).body(); } /** * You can create a new ticket. */ public Ticket create(CreateTicketRequest request) { - return create(request, null); + return this.rawClient.create(request).body(); } /** * You can create a new ticket. */ public Ticket create(CreateTicketRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("tickets") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Ticket.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.create(request, requestOptions).body(); } /** * You can fetch the details of a single ticket. */ public Ticket get(FindTicketRequest request) { - return get(request, null); + return this.rawClient.get(request).body(); } /** * You can fetch the details of a single ticket. */ public Ticket get(FindTicketRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("tickets") - .addPathSegment(request.getTicketId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Ticket.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.get(request, requestOptions).body(); } /** * You can update a ticket. */ public Ticket update(UpdateTicketRequest request) { - return update(request, null); + return this.rawClient.update(request).body(); } /** * You can update a ticket. */ public Ticket update(UpdateTicketRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("tickets") - .addPathSegment(request.getTicketId()) - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PUT", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Ticket.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.update(request, requestOptions).body(); } /** @@ -326,7 +142,7 @@ public Ticket update(UpdateTicketRequest request, RequestOptions requestOptions) * | $ | String | Ends With |

*/ public SyncPagingIterable search(SearchRequest request) { - return search(request, null); + return this.rawClient.search(request).body(); } /** @@ -384,57 +200,6 @@ public SyncPagingIterable search(SearchRequest request) { * | $ | String | Ends With |

*/ public SyncPagingIterable search(SearchRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("tickets/search") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - TicketList parsedResponse = - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketList.class); - Optional startingAfter = parsedResponse - .getPages() - .flatMap(CursorPages::getNext) - .flatMap(StartingAfterPaging::getStartingAfter); - Optional pagination = request.getPagination() - .map(pagination_ -> StartingAfterPaging.builder() - .from(pagination_) - .startingAfter(startingAfter) - .build()); - SearchRequest nextRequest = SearchRequest.builder() - .from(request) - .pagination(pagination) - .build(); - List result = parsedResponse.getTickets(); - return new SyncPagingIterable( - startingAfter.isPresent(), result, () -> search(nextRequest, requestOptions)); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.search(request, requestOptions).body(); } } diff --git a/src/main/java/com/intercom/api/resources/tickettypes/AsyncRawTicketTypesClient.java b/src/main/java/com/intercom/api/resources/tickettypes/AsyncRawTicketTypesClient.java new file mode 100644 index 0000000..f641605 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/tickettypes/AsyncRawTicketTypesClient.java @@ -0,0 +1,341 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.tickettypes; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.tickets.types.TicketType; +import com.intercom.api.resources.tickettypes.requests.CreateTicketTypeRequest; +import com.intercom.api.resources.tickettypes.requests.FindTicketTypeRequest; +import com.intercom.api.resources.tickettypes.requests.UpdateTicketTypeRequest; +import com.intercom.api.types.Error; +import com.intercom.api.types.TicketTypeList; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawTicketTypesClient { + protected final ClientOptions clientOptions; + + public AsyncRawTicketTypesClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can get a list of all ticket types for a workspace. + */ + public CompletableFuture> list() { + return list(null); + } + + /** + * You can get a list of all ticket types for a workspace. + */ + public CompletableFuture> list(RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("ticket_types") + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketTypeList.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can create a new ticket type. + *
+ *

📘 Creating ticket types.

+ *

Every ticket type will be created with two default attributes: default_title and default_description. + * For the icon propery, use an emoji from Twemoji Cheatsheet

+ *
+ */ + public CompletableFuture> create(CreateTicketTypeRequest request) { + return create(request, null); + } + + /** + * You can create a new ticket type. + *
+ *

📘 Creating ticket types.

+ *

Every ticket type will be created with two default attributes: default_title and default_description. + * For the icon propery, use an emoji from Twemoji Cheatsheet

+ *
+ */ + public CompletableFuture> create( + CreateTicketTypeRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("ticket_types") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketType.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can fetch the details of a single ticket type. + */ + public CompletableFuture> get(FindTicketTypeRequest request) { + return get(request, null); + } + + /** + * You can fetch the details of a single ticket type. + */ + public CompletableFuture> get( + FindTicketTypeRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("ticket_types") + .addPathSegment(request.getTicketTypeId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketType.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can update a ticket type. + *
+ *

📘 Updating a ticket type.

+ *

For the icon propery, use an emoji from Twemoji Cheatsheet

+ *
+ */ + public CompletableFuture> update(UpdateTicketTypeRequest request) { + return update(request, null); + } + + /** + * You can update a ticket type. + *
+ *

📘 Updating a ticket type.

+ *

For the icon propery, use an emoji from Twemoji Cheatsheet

+ *
+ */ + public CompletableFuture> update( + UpdateTicketTypeRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("ticket_types") + .addPathSegment(request.getTicketTypeId()) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketType.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/intercom/api/resources/tickettypes/AsyncTicketTypesClient.java b/src/main/java/com/intercom/api/resources/tickettypes/AsyncTicketTypesClient.java index 6560422..cc06212 100644 --- a/src/main/java/com/intercom/api/resources/tickettypes/AsyncTicketTypesClient.java +++ b/src/main/java/com/intercom/api/resources/tickettypes/AsyncTicketTypesClient.java @@ -3,108 +3,50 @@ */ package com.intercom.api.resources.tickettypes; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; import com.intercom.api.core.RequestOptions; import com.intercom.api.core.Suppliers; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.tickets.types.TicketType; import com.intercom.api.resources.tickettypes.attributes.AsyncAttributesClient; import com.intercom.api.resources.tickettypes.requests.CreateTicketTypeRequest; import com.intercom.api.resources.tickettypes.requests.FindTicketTypeRequest; import com.intercom.api.resources.tickettypes.requests.UpdateTicketTypeRequest; -import com.intercom.api.types.Error; import com.intercom.api.types.TicketTypeList; -import java.io.IOException; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; public class AsyncTicketTypesClient { protected final ClientOptions clientOptions; + private final AsyncRawTicketTypesClient rawClient; + protected final Supplier attributesClient; public AsyncTicketTypesClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new AsyncRawTicketTypesClient(clientOptions); this.attributesClient = Suppliers.memoize(() -> new AsyncAttributesClient(clientOptions)); } + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawTicketTypesClient withRawResponse() { + return this.rawClient; + } + /** * You can get a list of all ticket types for a workspace. */ public CompletableFuture list() { - return list(null); + return this.rawClient.list().thenApply(response -> response.body()); } /** * You can get a list of all ticket types for a workspace. */ public CompletableFuture list(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("ticket_types") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketTypeList.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.list(requestOptions).thenApply(response -> response.body()); } /** @@ -116,7 +58,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { * */ public CompletableFuture create(CreateTicketTypeRequest request) { - return create(request, null); + return this.rawClient.create(request).thenApply(response -> response.body()); } /** @@ -128,127 +70,21 @@ public CompletableFuture create(CreateTicketTypeRequest request) { * */ public CompletableFuture create(CreateTicketTypeRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("ticket_types") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketType.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.create(request, requestOptions).thenApply(response -> response.body()); } /** * You can fetch the details of a single ticket type. */ public CompletableFuture get(FindTicketTypeRequest request) { - return get(request, null); + return this.rawClient.get(request).thenApply(response -> response.body()); } /** * You can fetch the details of a single ticket type. */ public CompletableFuture get(FindTicketTypeRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("ticket_types") - .addPathSegment(request.getTicketTypeId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketType.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.get(request, requestOptions).thenApply(response -> response.body()); } /** @@ -259,7 +95,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { * */ public CompletableFuture update(UpdateTicketTypeRequest request) { - return update(request, null); + return this.rawClient.update(request).thenApply(response -> response.body()); } /** @@ -270,64 +106,7 @@ public CompletableFuture update(UpdateTicketTypeRequest request) { * */ public CompletableFuture update(UpdateTicketTypeRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("ticket_types") - .addPathSegment(request.getTicketTypeId()) - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PUT", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketType.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.update(request, requestOptions).thenApply(response -> response.body()); } public AsyncAttributesClient attributes() { diff --git a/src/main/java/com/intercom/api/resources/tickettypes/RawTicketTypesClient.java b/src/main/java/com/intercom/api/resources/tickettypes/RawTicketTypesClient.java new file mode 100644 index 0000000..528723f --- /dev/null +++ b/src/main/java/com/intercom/api/resources/tickettypes/RawTicketTypesClient.java @@ -0,0 +1,274 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.tickettypes; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.tickets.types.TicketType; +import com.intercom.api.resources.tickettypes.requests.CreateTicketTypeRequest; +import com.intercom.api.resources.tickettypes.requests.FindTicketTypeRequest; +import com.intercom.api.resources.tickettypes.requests.UpdateTicketTypeRequest; +import com.intercom.api.types.Error; +import com.intercom.api.types.TicketTypeList; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawTicketTypesClient { + protected final ClientOptions clientOptions; + + public RawTicketTypesClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can get a list of all ticket types for a workspace. + */ + public IntercomHttpResponse list() { + return list(null); + } + + /** + * You can get a list of all ticket types for a workspace. + */ + public IntercomHttpResponse list(RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("ticket_types") + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketTypeList.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can create a new ticket type. + *
+ *

📘 Creating ticket types.

+ *

Every ticket type will be created with two default attributes: default_title and default_description. + * For the icon propery, use an emoji from Twemoji Cheatsheet

+ *
+ */ + public IntercomHttpResponse create(CreateTicketTypeRequest request) { + return create(request, null); + } + + /** + * You can create a new ticket type. + *
+ *

📘 Creating ticket types.

+ *

Every ticket type will be created with two default attributes: default_title and default_description. + * For the icon propery, use an emoji from Twemoji Cheatsheet

+ *
+ */ + public IntercomHttpResponse create(CreateTicketTypeRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("ticket_types") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketType.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can fetch the details of a single ticket type. + */ + public IntercomHttpResponse get(FindTicketTypeRequest request) { + return get(request, null); + } + + /** + * You can fetch the details of a single ticket type. + */ + public IntercomHttpResponse get(FindTicketTypeRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("ticket_types") + .addPathSegment(request.getTicketTypeId()) + .build(); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketType.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can update a ticket type. + *
+ *

📘 Updating a ticket type.

+ *

For the icon propery, use an emoji from Twemoji Cheatsheet

+ *
+ */ + public IntercomHttpResponse update(UpdateTicketTypeRequest request) { + return update(request, null); + } + + /** + * You can update a ticket type. + *
+ *

📘 Updating a ticket type.

+ *

For the icon propery, use an emoji from Twemoji Cheatsheet

+ *
+ */ + public IntercomHttpResponse update(UpdateTicketTypeRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("ticket_types") + .addPathSegment(request.getTicketTypeId()) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketType.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/intercom/api/resources/tickettypes/TicketTypesClient.java b/src/main/java/com/intercom/api/resources/tickettypes/TicketTypesClient.java index f8e1227..1ec379f 100644 --- a/src/main/java/com/intercom/api/resources/tickettypes/TicketTypesClient.java +++ b/src/main/java/com/intercom/api/resources/tickettypes/TicketTypesClient.java @@ -3,88 +3,49 @@ */ package com.intercom.api.resources.tickettypes; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; import com.intercom.api.core.RequestOptions; import com.intercom.api.core.Suppliers; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.tickets.types.TicketType; import com.intercom.api.resources.tickettypes.attributes.AttributesClient; import com.intercom.api.resources.tickettypes.requests.CreateTicketTypeRequest; import com.intercom.api.resources.tickettypes.requests.FindTicketTypeRequest; import com.intercom.api.resources.tickettypes.requests.UpdateTicketTypeRequest; -import com.intercom.api.types.Error; import com.intercom.api.types.TicketTypeList; -import java.io.IOException; import java.util.function.Supplier; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; public class TicketTypesClient { protected final ClientOptions clientOptions; + private final RawTicketTypesClient rawClient; + protected final Supplier attributesClient; public TicketTypesClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawTicketTypesClient(clientOptions); this.attributesClient = Suppliers.memoize(() -> new AttributesClient(clientOptions)); } + /** + * Get responses with HTTP metadata like headers + */ + public RawTicketTypesClient withRawResponse() { + return this.rawClient; + } + /** * You can get a list of all ticket types for a workspace. */ public TicketTypeList list() { - return list(null); + return this.rawClient.list().body(); } /** * You can get a list of all ticket types for a workspace. */ public TicketTypeList list(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("ticket_types") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketTypeList.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.list(requestOptions).body(); } /** @@ -96,7 +57,7 @@ public TicketTypeList list(RequestOptions requestOptions) { * */ public TicketType create(CreateTicketTypeRequest request) { - return create(request, null); + return this.rawClient.create(request).body(); } /** @@ -108,97 +69,21 @@ public TicketType create(CreateTicketTypeRequest request) { * */ public TicketType create(CreateTicketTypeRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("ticket_types") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketType.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.create(request, requestOptions).body(); } /** * You can fetch the details of a single ticket type. */ public TicketType get(FindTicketTypeRequest request) { - return get(request, null); + return this.rawClient.get(request).body(); } /** * You can fetch the details of a single ticket type. */ public TicketType get(FindTicketTypeRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("ticket_types") - .addPathSegment(request.getTicketTypeId()) - .build(); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketType.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.get(request, requestOptions).body(); } /** @@ -209,7 +94,7 @@ public TicketType get(FindTicketTypeRequest request, RequestOptions requestOptio * */ public TicketType update(UpdateTicketTypeRequest request) { - return update(request, null); + return this.rawClient.update(request).body(); } /** @@ -220,49 +105,7 @@ public TicketType update(UpdateTicketTypeRequest request) { * */ public TicketType update(UpdateTicketTypeRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("ticket_types") - .addPathSegment(request.getTicketTypeId()) - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PUT", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketType.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.update(request, requestOptions).body(); } public AttributesClient attributes() { diff --git a/src/main/java/com/intercom/api/resources/tickettypes/attributes/AsyncAttributesClient.java b/src/main/java/com/intercom/api/resources/tickettypes/attributes/AsyncAttributesClient.java index c5b09d0..79d3ef0 100644 --- a/src/main/java/com/intercom/api/resources/tickettypes/attributes/AsyncAttributesClient.java +++ b/src/main/java/com/intercom/api/resources/tickettypes/attributes/AsyncAttributesClient.java @@ -3,43 +3,35 @@ */ package com.intercom.api.resources.tickettypes.attributes; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; import com.intercom.api.core.RequestOptions; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.tickettypes.attributes.requests.CreateTicketTypeAttributeRequest; import com.intercom.api.resources.tickettypes.attributes.requests.UpdateTicketTypeAttributeRequest; -import com.intercom.api.types.Error; import com.intercom.api.types.TicketTypeAttribute; -import java.io.IOException; import java.util.concurrent.CompletableFuture; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; public class AsyncAttributesClient { protected final ClientOptions clientOptions; + private final AsyncRawAttributesClient rawClient; + public AsyncAttributesClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new AsyncRawAttributesClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawAttributesClient withRawResponse() { + return this.rawClient; } /** * You can create a new attribute for a ticket type. */ public CompletableFuture create(CreateTicketTypeAttributeRequest request) { - return create(request, null); + return this.rawClient.create(request).thenApply(response -> response.body()); } /** @@ -47,73 +39,14 @@ public CompletableFuture create(CreateTicketTypeAttributeRe */ public CompletableFuture create( CreateTicketTypeAttributeRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("ticket_types") - .addPathSegment(request.getTicketTypeId()) - .addPathSegments("attributes") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketTypeAttribute.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.create(request, requestOptions).thenApply(response -> response.body()); } /** * You can update an existing attribute for a ticket type. */ public CompletableFuture update(UpdateTicketTypeAttributeRequest request) { - return update(request, null); + return this.rawClient.update(request).thenApply(response -> response.body()); } /** @@ -121,66 +54,6 @@ public CompletableFuture update(UpdateTicketTypeAttributeRe */ public CompletableFuture update( UpdateTicketTypeAttributeRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("ticket_types") - .addPathSegment(request.getTicketTypeId()) - .addPathSegments("attributes") - .addPathSegment(request.getAttributeId()) - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PUT", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketTypeAttribute.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.update(request, requestOptions).thenApply(response -> response.body()); } } diff --git a/src/main/java/com/intercom/api/resources/tickettypes/attributes/AsyncRawAttributesClient.java b/src/main/java/com/intercom/api/resources/tickettypes/attributes/AsyncRawAttributesClient.java new file mode 100644 index 0000000..0cc0ae5 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/tickettypes/attributes/AsyncRawAttributesClient.java @@ -0,0 +1,193 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.tickettypes.attributes; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.tickettypes.attributes.requests.CreateTicketTypeAttributeRequest; +import com.intercom.api.resources.tickettypes.attributes.requests.UpdateTicketTypeAttributeRequest; +import com.intercom.api.types.Error; +import com.intercom.api.types.TicketTypeAttribute; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawAttributesClient { + protected final ClientOptions clientOptions; + + public AsyncRawAttributesClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can create a new attribute for a ticket type. + */ + public CompletableFuture> create( + CreateTicketTypeAttributeRequest request) { + return create(request, null); + } + + /** + * You can create a new attribute for a ticket type. + */ + public CompletableFuture> create( + CreateTicketTypeAttributeRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("ticket_types") + .addPathSegment(request.getTicketTypeId()) + .addPathSegments("attributes") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketTypeAttribute.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can update an existing attribute for a ticket type. + */ + public CompletableFuture> update( + UpdateTicketTypeAttributeRequest request) { + return update(request, null); + } + + /** + * You can update an existing attribute for a ticket type. + */ + public CompletableFuture> update( + UpdateTicketTypeAttributeRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("ticket_types") + .addPathSegment(request.getTicketTypeId()) + .addPathSegments("attributes") + .addPathSegment(request.getAttributeId()) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketTypeAttribute.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/intercom/api/resources/tickettypes/attributes/AttributesClient.java b/src/main/java/com/intercom/api/resources/tickettypes/attributes/AttributesClient.java index 44e226f..964980c 100644 --- a/src/main/java/com/intercom/api/resources/tickettypes/attributes/AttributesClient.java +++ b/src/main/java/com/intercom/api/resources/tickettypes/attributes/AttributesClient.java @@ -3,146 +3,54 @@ */ package com.intercom.api.resources.tickettypes.attributes; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; import com.intercom.api.core.RequestOptions; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.tickettypes.attributes.requests.CreateTicketTypeAttributeRequest; import com.intercom.api.resources.tickettypes.attributes.requests.UpdateTicketTypeAttributeRequest; -import com.intercom.api.types.Error; import com.intercom.api.types.TicketTypeAttribute; -import java.io.IOException; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; public class AttributesClient { protected final ClientOptions clientOptions; + private final RawAttributesClient rawClient; + public AttributesClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawAttributesClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawAttributesClient withRawResponse() { + return this.rawClient; } /** * You can create a new attribute for a ticket type. */ public TicketTypeAttribute create(CreateTicketTypeAttributeRequest request) { - return create(request, null); + return this.rawClient.create(request).body(); } /** * You can create a new attribute for a ticket type. */ public TicketTypeAttribute create(CreateTicketTypeAttributeRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("ticket_types") - .addPathSegment(request.getTicketTypeId()) - .addPathSegments("attributes") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketTypeAttribute.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.create(request, requestOptions).body(); } /** * You can update an existing attribute for a ticket type. */ public TicketTypeAttribute update(UpdateTicketTypeAttributeRequest request) { - return update(request, null); + return this.rawClient.update(request).body(); } /** * You can update an existing attribute for a ticket type. */ public TicketTypeAttribute update(UpdateTicketTypeAttributeRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("ticket_types") - .addPathSegment(request.getTicketTypeId()) - .addPathSegments("attributes") - .addPathSegment(request.getAttributeId()) - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PUT", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketTypeAttribute.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.update(request, requestOptions).body(); } } diff --git a/src/main/java/com/intercom/api/resources/tickettypes/attributes/RawAttributesClient.java b/src/main/java/com/intercom/api/resources/tickettypes/attributes/RawAttributesClient.java new file mode 100644 index 0000000..36d50e5 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/tickettypes/attributes/RawAttributesClient.java @@ -0,0 +1,159 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.tickettypes.attributes; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.tickettypes.attributes.requests.CreateTicketTypeAttributeRequest; +import com.intercom.api.resources.tickettypes.attributes.requests.UpdateTicketTypeAttributeRequest; +import com.intercom.api.types.Error; +import com.intercom.api.types.TicketTypeAttribute; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawAttributesClient { + protected final ClientOptions clientOptions; + + public RawAttributesClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can create a new attribute for a ticket type. + */ + public IntercomHttpResponse create(CreateTicketTypeAttributeRequest request) { + return create(request, null); + } + + /** + * You can create a new attribute for a ticket type. + */ + public IntercomHttpResponse create( + CreateTicketTypeAttributeRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("ticket_types") + .addPathSegment(request.getTicketTypeId()) + .addPathSegments("attributes") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketTypeAttribute.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can update an existing attribute for a ticket type. + */ + public IntercomHttpResponse update(UpdateTicketTypeAttributeRequest request) { + return update(request, null); + } + + /** + * You can update an existing attribute for a ticket type. + */ + public IntercomHttpResponse update( + UpdateTicketTypeAttributeRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("ticket_types") + .addPathSegment(request.getTicketTypeId()) + .addPathSegments("attributes") + .addPathSegment(request.getAttributeId()) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TicketTypeAttribute.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/intercom/api/resources/visitors/AsyncRawVisitorsClient.java b/src/main/java/com/intercom/api/resources/visitors/AsyncRawVisitorsClient.java new file mode 100644 index 0000000..359e216 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/visitors/AsyncRawVisitorsClient.java @@ -0,0 +1,280 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.visitors; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.QueryStringMapper; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.contacts.types.Contact; +import com.intercom.api.resources.visitors.requests.FindVisitorRequest; +import com.intercom.api.resources.visitors.requests.MergeVisitorToContactRequest; +import com.intercom.api.types.Error; +import com.intercom.api.types.UpdateVisitorRequest; +import com.intercom.api.types.Visitor; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawVisitorsClient { + protected final ClientOptions clientOptions; + + public AsyncRawVisitorsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can fetch the details of a single visitor. + */ + public CompletableFuture> find(FindVisitorRequest request) { + return find(request, null); + } + + /** + * You can fetch the details of a single visitor. + */ + public CompletableFuture> find( + FindVisitorRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("visitors"); + QueryStringMapper.addQueryParameter(httpUrl, "user_id", request.getUserId(), false); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Visitor.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Sending a PUT request to /visitors will result in an update of an existing Visitor. + *

Option 1. You can update a visitor by passing in the user_id of the visitor in the Request body.

+ *

Option 2. You can update a visitor by passing in the id of the visitor in the Request body.

+ */ + public CompletableFuture> update(UpdateVisitorRequest request) { + return update(request, null); + } + + /** + * Sending a PUT request to /visitors will result in an update of an existing Visitor. + *

Option 1. You can update a visitor by passing in the user_id of the visitor in the Request body.

+ *

Option 2. You can update a visitor by passing in the id of the visitor in the Request body.

+ */ + public CompletableFuture> update( + UpdateVisitorRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("visitors") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Visitor.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * You can merge a Visitor to a Contact of role type lead or user. + *
+ *

📘 What happens upon a visitor being converted?

+ *

If the User exists, then the Visitor will be merged into it, the Visitor deleted and the User returned. If the User does not exist, the Visitor will be converted to a User, with the User identifiers replacing it's Visitor identifiers.

+ *
+ */ + public CompletableFuture> mergeToContact(MergeVisitorToContactRequest request) { + return mergeToContact(request, null); + } + + /** + * You can merge a Visitor to a Contact of role type lead or user. + *
+ *

📘 What happens upon a visitor being converted?

+ *

If the User exists, then the Visitor will be merged into it, the Visitor deleted and the User returned. If the User does not exist, the Visitor will be converted to a User, with the User identifiers replacing it's Visitor identifiers.

+ *
+ */ + public CompletableFuture> mergeToContact( + MergeVisitorToContactRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("visitors/convert") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Contact.class), response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/intercom/api/resources/visitors/AsyncVisitorsClient.java b/src/main/java/com/intercom/api/resources/visitors/AsyncVisitorsClient.java index 8a01b0a..75614d3 100644 --- a/src/main/java/com/intercom/api/resources/visitors/AsyncVisitorsClient.java +++ b/src/main/java/com/intercom/api/resources/visitors/AsyncVisitorsClient.java @@ -3,108 +3,44 @@ */ package com.intercom.api.resources.visitors; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; -import com.intercom.api.core.QueryStringMapper; import com.intercom.api.core.RequestOptions; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.contacts.types.Contact; import com.intercom.api.resources.visitors.requests.FindVisitorRequest; import com.intercom.api.resources.visitors.requests.MergeVisitorToContactRequest; -import com.intercom.api.types.Error; import com.intercom.api.types.UpdateVisitorRequest; import com.intercom.api.types.Visitor; -import java.io.IOException; import java.util.concurrent.CompletableFuture; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; public class AsyncVisitorsClient { protected final ClientOptions clientOptions; + private final AsyncRawVisitorsClient rawClient; + public AsyncVisitorsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new AsyncRawVisitorsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawVisitorsClient withRawResponse() { + return this.rawClient; } /** * You can fetch the details of a single visitor. */ public CompletableFuture find(FindVisitorRequest request) { - return find(request, null); + return this.rawClient.find(request).thenApply(response -> response.body()); } /** * You can fetch the details of a single visitor. */ public CompletableFuture find(FindVisitorRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("visitors"); - QueryStringMapper.addQueryParameter(httpUrl, "user_id", request.getUserId(), false); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Visitor.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.find(request, requestOptions).thenApply(response -> response.body()); } /** @@ -113,7 +49,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { *

Option 2. You can update a visitor by passing in the id of the visitor in the Request body.

*/ public CompletableFuture update(UpdateVisitorRequest request) { - return update(request, null); + return this.rawClient.update(request).thenApply(response -> response.body()); } /** @@ -122,68 +58,7 @@ public CompletableFuture update(UpdateVisitorRequest request) { *

Option 2. You can update a visitor by passing in the id of the visitor in the Request body.

*/ public CompletableFuture update(UpdateVisitorRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("visitors") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PUT", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Visitor.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.update(request, requestOptions).thenApply(response -> response.body()); } /** @@ -194,7 +69,7 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { * */ public CompletableFuture mergeToContact(MergeVisitorToContactRequest request) { - return mergeToContact(request, null); + return this.rawClient.mergeToContact(request).thenApply(response -> response.body()); } /** @@ -206,62 +81,6 @@ public CompletableFuture mergeToContact(MergeVisitorToContactRequest re */ public CompletableFuture mergeToContact( MergeVisitorToContactRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("visitors/convert") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Contact.class)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class))); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class))); - return; - } catch (IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new IntercomException("Network error executing HTTP request", e)); - } - }); - return future; + return this.rawClient.mergeToContact(request, requestOptions).thenApply(response -> response.body()); } } diff --git a/src/main/java/com/intercom/api/resources/visitors/RawVisitorsClient.java b/src/main/java/com/intercom/api/resources/visitors/RawVisitorsClient.java new file mode 100644 index 0000000..84903e3 --- /dev/null +++ b/src/main/java/com/intercom/api/resources/visitors/RawVisitorsClient.java @@ -0,0 +1,226 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.resources.visitors; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.intercom.api.core.ClientOptions; +import com.intercom.api.core.IntercomApiException; +import com.intercom.api.core.IntercomException; +import com.intercom.api.core.IntercomHttpResponse; +import com.intercom.api.core.MediaTypes; +import com.intercom.api.core.ObjectMappers; +import com.intercom.api.core.QueryStringMapper; +import com.intercom.api.core.RequestOptions; +import com.intercom.api.errors.NotFoundError; +import com.intercom.api.errors.UnauthorizedError; +import com.intercom.api.resources.contacts.types.Contact; +import com.intercom.api.resources.visitors.requests.FindVisitorRequest; +import com.intercom.api.resources.visitors.requests.MergeVisitorToContactRequest; +import com.intercom.api.types.Error; +import com.intercom.api.types.UpdateVisitorRequest; +import com.intercom.api.types.Visitor; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawVisitorsClient { + protected final ClientOptions clientOptions; + + public RawVisitorsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * You can fetch the details of a single visitor. + */ + public IntercomHttpResponse find(FindVisitorRequest request) { + return find(request, null); + } + + /** + * You can fetch the details of a single visitor. + */ + public IntercomHttpResponse find(FindVisitorRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("visitors"); + QueryStringMapper.addQueryParameter(httpUrl, "user_id", request.getUserId(), false); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Visitor.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * Sending a PUT request to /visitors will result in an update of an existing Visitor. + *

Option 1. You can update a visitor by passing in the user_id of the visitor in the Request body.

+ *

Option 2. You can update a visitor by passing in the id of the visitor in the Request body.

+ */ + public IntercomHttpResponse update(UpdateVisitorRequest request) { + return update(request, null); + } + + /** + * Sending a PUT request to /visitors will result in an update of an existing Visitor. + *

Option 1. You can update a visitor by passing in the user_id of the visitor in the Request body.

+ *

Option 2. You can update a visitor by passing in the id of the visitor in the Request body.

+ */ + public IntercomHttpResponse update(UpdateVisitorRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("visitors") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Visitor.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } + + /** + * You can merge a Visitor to a Contact of role type lead or user. + *
+ *

📘 What happens upon a visitor being converted?

+ *

If the User exists, then the Visitor will be merged into it, the Visitor deleted and the User returned. If the User does not exist, the Visitor will be converted to a User, with the User identifiers replacing it's Visitor identifiers.

+ *
+ */ + public IntercomHttpResponse mergeToContact(MergeVisitorToContactRequest request) { + return mergeToContact(request, null); + } + + /** + * You can merge a Visitor to a Contact of role type lead or user. + *
+ *

📘 What happens upon a visitor being converted?

+ *

If the User exists, then the Visitor will be merged into it, the Visitor deleted and the User returned. If the User does not exist, the Visitor will be converted to a User, with the User identifiers replacing it's Visitor identifiers.

+ *
+ */ + public IntercomHttpResponse mergeToContact( + MergeVisitorToContactRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("visitors/convert") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new IntercomException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new IntercomHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Contact.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 401) { + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new IntercomApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new IntercomException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/intercom/api/resources/visitors/VisitorsClient.java b/src/main/java/com/intercom/api/resources/visitors/VisitorsClient.java index 924e23b..9c3f7df 100644 --- a/src/main/java/com/intercom/api/resources/visitors/VisitorsClient.java +++ b/src/main/java/com/intercom/api/resources/visitors/VisitorsClient.java @@ -3,88 +3,43 @@ */ package com.intercom.api.resources.visitors; -import com.fasterxml.jackson.core.JsonProcessingException; import com.intercom.api.core.ClientOptions; -import com.intercom.api.core.IntercomApiException; -import com.intercom.api.core.IntercomException; -import com.intercom.api.core.MediaTypes; -import com.intercom.api.core.ObjectMappers; -import com.intercom.api.core.QueryStringMapper; import com.intercom.api.core.RequestOptions; -import com.intercom.api.errors.NotFoundError; -import com.intercom.api.errors.UnauthorizedError; import com.intercom.api.resources.contacts.types.Contact; import com.intercom.api.resources.visitors.requests.FindVisitorRequest; import com.intercom.api.resources.visitors.requests.MergeVisitorToContactRequest; -import com.intercom.api.types.Error; import com.intercom.api.types.UpdateVisitorRequest; import com.intercom.api.types.Visitor; -import java.io.IOException; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; public class VisitorsClient { protected final ClientOptions clientOptions; + private final RawVisitorsClient rawClient; + public VisitorsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawVisitorsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawVisitorsClient withRawResponse() { + return this.rawClient; } /** * You can fetch the details of a single visitor. */ public Visitor find(FindVisitorRequest request) { - return find(request, null); + return this.rawClient.find(request).body(); } /** * You can fetch the details of a single visitor. */ public Visitor find(FindVisitorRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("visitors"); - QueryStringMapper.addQueryParameter(httpUrl, "user_id", request.getUserId(), false); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Visitor.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.find(request, requestOptions).body(); } /** @@ -93,7 +48,7 @@ public Visitor find(FindVisitorRequest request, RequestOptions requestOptions) { *

Option 2. You can update a visitor by passing in the id of the visitor in the Request body.

*/ public Visitor update(UpdateVisitorRequest request) { - return update(request, null); + return this.rawClient.update(request).body(); } /** @@ -102,52 +57,7 @@ public Visitor update(UpdateVisitorRequest request) { *

Option 2. You can update a visitor by passing in the id of the visitor in the Request body.

*/ public Visitor update(UpdateVisitorRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("visitors") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PUT", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Visitor.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - case 404: - throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.update(request, requestOptions).body(); } /** @@ -158,7 +68,7 @@ public Visitor update(UpdateVisitorRequest request, RequestOptions requestOption * */ public Contact mergeToContact(MergeVisitorToContactRequest request) { - return mergeToContact(request, null); + return this.rawClient.mergeToContact(request).body(); } /** @@ -169,47 +79,6 @@ public Contact mergeToContact(MergeVisitorToContactRequest request) { * */ public Contact mergeToContact(MergeVisitorToContactRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("visitors/convert") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new IntercomException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Contact.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 401) { - throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Error.class)); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new IntercomApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } catch (IOException e) { - throw new IntercomException("Network error executing HTTP request", e); - } + return this.rawClient.mergeToContact(request, requestOptions).body(); } } diff --git a/src/test/java/com/intercom/api/core/QueryStringMapperTest.java b/src/test/java/com/intercom/api/core/QueryStringMapperTest.java new file mode 100644 index 0000000..18fdff2 --- /dev/null +++ b/src/test/java/com/intercom/api/core/QueryStringMapperTest.java @@ -0,0 +1,339 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.intercom.api.core; + +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import okhttp3.HttpUrl; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public final class QueryStringMapperTest { + @Test + public void testObjectWithQuotedString_indexedArrays() { + Map map = new HashMap() { + { + put("hello", "\"world\""); + } + }; + + String expectedQueryString = "withquoted%5Bhello%5D=%22world%22"; + + String actualQueryString = queryString( + new HashMap() { + { + put("withquoted", map); + } + }, + false); + + Assertions.assertEquals(expectedQueryString, actualQueryString); + } + + @Test + public void testObjectWithQuotedString_arraysAsRepeats() { + Map map = new HashMap() { + { + put("hello", "\"world\""); + } + }; + + String expectedQueryString = "withquoted%5Bhello%5D=%22world%22"; + + String actualQueryString = queryString( + new HashMap() { + { + put("withquoted", map); + } + }, + true); + + Assertions.assertEquals(expectedQueryString, actualQueryString); + } + + @Test + public void testObject_indexedArrays() { + Map map = new HashMap() { + { + put("foo", "bar"); + put("baz", "qux"); + } + }; + + String expectedQueryString = "metadata%5Bfoo%5D=bar&metadata%5Bbaz%5D=qux"; + + String actualQueryString = queryString( + new HashMap() { + { + put("metadata", map); + } + }, + false); + + Assertions.assertEquals(expectedQueryString, actualQueryString); + } + + @Test + public void testObject_arraysAsRepeats() { + Map map = new HashMap() { + { + put("foo", "bar"); + put("baz", "qux"); + } + }; + + String expectedQueryString = "metadata%5Bfoo%5D=bar&metadata%5Bbaz%5D=qux"; + + String actualQueryString = queryString( + new HashMap() { + { + put("metadata", map); + } + }, + true); + + Assertions.assertEquals(expectedQueryString, actualQueryString); + } + + @Test + public void testNestedObject_indexedArrays() { + Map> nestedMap = new HashMap>() { + { + put("mapkey1", new HashMap() { + { + put("mapkey1mapkey1", "mapkey1mapkey1value"); + put("mapkey1mapkey2", "mapkey1mapkey2value"); + } + }); + put("mapkey2", new HashMap() { + { + put("mapkey2mapkey1", "mapkey2mapkey1value"); + } + }); + } + }; + + String expectedQueryString = + "nested%5Bmapkey2%5D%5Bmapkey2mapkey1%5D=mapkey2mapkey1value&nested%5Bmapkey1%5D%5Bmapkey1mapkey1" + + "%5D=mapkey1mapkey1value&nested%5Bmapkey1%5D%5Bmapkey1mapkey2%5D=mapkey1mapkey2value"; + + String actualQueryString = queryString( + new HashMap() { + { + put("nested", nestedMap); + } + }, + false); + + Assertions.assertEquals(expectedQueryString, actualQueryString); + } + + @Test + public void testNestedObject_arraysAsRepeats() { + Map> nestedMap = new HashMap>() { + { + put("mapkey1", new HashMap() { + { + put("mapkey1mapkey1", "mapkey1mapkey1value"); + put("mapkey1mapkey2", "mapkey1mapkey2value"); + } + }); + put("mapkey2", new HashMap() { + { + put("mapkey2mapkey1", "mapkey2mapkey1value"); + } + }); + } + }; + + String expectedQueryString = + "nested%5Bmapkey2%5D%5Bmapkey2mapkey1%5D=mapkey2mapkey1value&nested%5Bmapkey1%5D%5Bmapkey1mapkey1" + + "%5D=mapkey1mapkey1value&nested%5Bmapkey1%5D%5Bmapkey1mapkey2%5D=mapkey1mapkey2value"; + + String actualQueryString = queryString( + new HashMap() { + { + put("nested", nestedMap); + } + }, + true); + + Assertions.assertEquals(expectedQueryString, actualQueryString); + } + + @Test + public void testDateTime_indexedArrays() { + OffsetDateTime dateTime = + OffsetDateTime.ofInstant(Instant.ofEpochSecond(1740412107L), ZoneId.of("America/New_York")); + + String expectedQueryString = "datetime=2025-02-24T10%3A48%3A27-05%3A00"; + + String actualQueryString = queryString( + new HashMap() { + { + put("datetime", dateTime); + } + }, + false); + + Assertions.assertEquals(expectedQueryString, actualQueryString); + } + + @Test + public void testDateTime_arraysAsRepeats() { + OffsetDateTime dateTime = + OffsetDateTime.ofInstant(Instant.ofEpochSecond(1740412107L), ZoneId.of("America/New_York")); + + String expectedQueryString = "datetime=2025-02-24T10%3A48%3A27-05%3A00"; + + String actualQueryString = queryString( + new HashMap() { + { + put("datetime", dateTime); + } + }, + true); + + Assertions.assertEquals(expectedQueryString, actualQueryString); + } + + @Test + public void testObjectArray_indexedArrays() { + List> mapArray = new ArrayList>() { + { + add(new HashMap() { + { + put("key", "hello"); + put("value", "world"); + } + }); + add(new HashMap() { + { + put("key", "foo"); + put("value", "bar"); + } + }); + add(new HashMap<>()); + } + }; + + String expectedQueryString = "objects%5B0%5D%5Bvalue%5D=world&objects%5B0%5D%5Bkey%5D=hello&objects%5B1%5D" + + "%5Bvalue%5D=bar&objects%5B1%5D%5Bkey%5D=foo"; + + String actualQueryString = queryString( + new HashMap() { + { + put("objects", mapArray); + } + }, + false); + + Assertions.assertEquals(expectedQueryString, actualQueryString); + } + + @Test + public void testObjectArray_arraysAsRepeats() { + List> mapArray = new ArrayList>() { + { + add(new HashMap() { + { + put("key", "hello"); + put("value", "world"); + } + }); + add(new HashMap() { + { + put("key", "foo"); + put("value", "bar"); + } + }); + add(new HashMap<>()); + } + }; + + String expectedQueryString = + "objects%5Bvalue%5D=world&objects%5Bkey%5D=hello&objects%5Bvalue" + "%5D=bar&objects%5Bkey%5D=foo"; + + String actualQueryString = queryString( + new HashMap() { + { + put("objects", mapArray); + } + }, + true); + + Assertions.assertEquals(expectedQueryString, actualQueryString); + } + + @Test + public void testObjectWithArray_indexedArrays() { + Map objectWithArray = new HashMap() { + { + put("id", "abc123"); + put("contactIds", new ArrayList() { + { + add("id1"); + add("id2"); + add("id3"); + } + }); + } + }; + + String expectedQueryString = + "objectwitharray%5Bid%5D=abc123&objectwitharray%5BcontactIds%5D%5B0%5D=id1&objectwitharray" + + "%5BcontactIds%5D%5B1%5D=id2&objectwitharray%5BcontactIds%5D%5B2%5D=id3"; + + String actualQueryString = queryString( + new HashMap() { + { + put("objectwitharray", objectWithArray); + } + }, + false); + + Assertions.assertEquals(expectedQueryString, actualQueryString); + } + + @Test + public void testObjectWithArray_arraysAsRepeats() { + Map objectWithArray = new HashMap() { + { + put("id", "abc123"); + put("contactIds", new ArrayList() { + { + add("id1"); + add("id2"); + add("id3"); + } + }); + } + }; + + String expectedQueryString = "objectwitharray%5Bid%5D=abc123&objectwitharray%5BcontactIds" + + "%5D=id1&objectwitharray%5BcontactIds%5D=id2&objectwitharray%5BcontactIds%5D=id3"; + + String actualQueryString = queryString( + new HashMap() { + { + put("objectwitharray", objectWithArray); + } + }, + true); + + Assertions.assertEquals(expectedQueryString, actualQueryString); + } + + private static String queryString(Map params, boolean arraysAsRepeats) { + HttpUrl.Builder httpUrl = HttpUrl.parse("http://www.fakewebsite.com/").newBuilder(); + params.forEach((paramName, paramValue) -> + QueryStringMapper.addQueryParameter(httpUrl, paramName, paramValue, arraysAsRepeats)); + return httpUrl.build().encodedQuery(); + } +}