From 844870199e1e1fe420a61d9bc4fff75a2efdff26 Mon Sep 17 00:00:00 2001 From: ylakhdar Date: Thu, 8 Jun 2023 08:15:09 -0400 Subject: [PATCH 1/8] ci: add linting job --- .github/workflows/build.yml | 5 + .gitignore | 4 +- .vscode/code-style.xml | 337 ++++++++++++++++++++++++++++++++++++ pom.xml | 53 ++++-- 4 files changed, 383 insertions(+), 16 deletions(-) create mode 100644 .vscode/code-style.xml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 1768f2ff..493522ea 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -15,10 +15,15 @@ jobs: steps: - uses: actions/checkout@v2 + - name: Set up JDK 11 uses: actions/setup-java@v2 with: java-version: '11' distribution: 'adopt' + + - name: Validate code format + run: mvn formatter:validate + - name: Build with Maven run: mvn -B package --file pom.xml diff --git a/.gitignore b/.gitignore index d5a7ca72..43e8b80c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ /target/ .env /.idea/ -.vscode \ No newline at end of file +.vscode/* + +!.vscode/code-style.xml \ No newline at end of file diff --git a/.vscode/code-style.xml b/.vscode/code-style.xml new file mode 100644 index 00000000..7bb6804e --- /dev/null +++ b/.vscode/code-style.xml @@ -0,0 +1,337 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pom.xml b/pom.xml index 142e7175..8dd72cc1 100644 --- a/pom.xml +++ b/pom.xml @@ -49,26 +49,49 @@ + + + + + org.apache.maven.plugins + maven-source-plugin + 3.0.0 + + + + attach-sources + + jar-no-fork + + + + + + + + net.revelc.code.formatter + formatter-maven-plugin + + .vscode/code-style.xml + LF + + + + + format + + + + + + + + release - - org.apache.maven.plugins - maven-source-plugin - 3.0.0 - - - - - attach-sources - - jar-no-fork - - - - org.apache.maven.plugins maven-javadoc-plugin From 9b34fd2ff26ce106be74fcace659231693167044 Mon Sep 17 00:00:00 2001 From: ylakhdar Date: Thu, 8 Jun 2023 08:26:56 -0400 Subject: [PATCH 2/8] docs: add formatting instructions in readme --- README.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/README.md b/README.md index 4d0a54e0..d569f2d8 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,20 @@ public class PushOneDocument { ``` +## Local Setup to Contribute + +### Formatting +Make sure to format your code before each pull request by manually invoking the [formatter-maven-plugin](https://code.revelc.net/formatter-maven-plugin/) Java plugin: +```bash +mvn formatter:format +``` + +You could also configure your IDE to use `.vscode/code-style.xml` for the formatting rules. +In VSCode, you can either update `~/Library/Application Support/Code/User/settings.json` or `.vscode/settings.json` by adding the following instruction: +```json +"java.format.settings.url": ".vscode/code-style.xml" +``` + ## Release * Tag the commit following semver. From 03c978c810cde98074b8338a758c0bdf78abd0d3 Mon Sep 17 00:00:00 2001 From: ylakhdar Date: Thu, 8 Jun 2023 09:14:14 -0400 Subject: [PATCH 3/8] ci: change indentation --- .vscode/code-style.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.vscode/code-style.xml b/.vscode/code-style.xml index 7bb6804e..bb335f00 100644 --- a/.vscode/code-style.xml +++ b/.vscode/code-style.xml @@ -167,7 +167,7 @@ - + From 99f045c0d7770a71b3def6d0f244b5a87e448eb8 Mon Sep 17 00:00:00 2001 From: ylakhdar Date: Fri, 9 Jun 2023 11:42:36 -0400 Subject: [PATCH 4/8] switch to spotless --- .github/workflows/build.yml | 2 +- .gitignore | 2 -- README.md | 11 +++-------- pom.xml | 24 +++++++++++++----------- 4 files changed, 17 insertions(+), 22 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 493522ea..96b6c600 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -23,7 +23,7 @@ jobs: distribution: 'adopt' - name: Validate code format - run: mvn formatter:validate + run: mvn spotless:check - name: Build with Maven run: mvn -B package --file pom.xml diff --git a/.gitignore b/.gitignore index 43e8b80c..61ca0e58 100644 --- a/.gitignore +++ b/.gitignore @@ -2,5 +2,3 @@ .env /.idea/ .vscode/* - -!.vscode/code-style.xml \ No newline at end of file diff --git a/README.md b/README.md index d569f2d8..67c9cd4d 100644 --- a/README.md +++ b/README.md @@ -48,15 +48,10 @@ public class PushOneDocument { ## Local Setup to Contribute ### Formatting -Make sure to format your code before each pull request by manually invoking the [formatter-maven-plugin](https://code.revelc.net/formatter-maven-plugin/) Java plugin: -```bash -mvn formatter:format -``` -You could also configure your IDE to use `.vscode/code-style.xml` for the formatting rules. -In VSCode, you can either update `~/Library/Application Support/Code/User/settings.json` or `.vscode/settings.json` by adding the following instruction: -```json -"java.format.settings.url": ".vscode/code-style.xml" +This project uses [Google Java Format](https://github.com/google/google-java-format), so make sure your code is properly formatted before opening a pull request. +```bash +mvn spotless:apply ``` ## Release diff --git a/pom.xml b/pom.xml index 8dd72cc1..9c4183c9 100644 --- a/pom.xml +++ b/pom.xml @@ -69,19 +69,20 @@ - net.revelc.code.formatter - formatter-maven-plugin + com.diffplug.spotless + spotless-maven-plugin + ${spotless.version} - .vscode/code-style.xml - LF + + + src/main/java/**/*.java + src/test/java/**/*.java + + + + + - - - - format - - - @@ -192,5 +193,6 @@ 11 11 UTF-8 + 2.37.0 \ No newline at end of file From 45e6ed784d98636ea07375e5d83175ff18d6b85b Mon Sep 17 00:00:00 2001 From: ylakhdar Date: Fri, 9 Jun 2023 11:44:56 -0400 Subject: [PATCH 5/8] style: repo formatting --- .../com/coveo/pushapiclient/AliasMapping.java | 11 +- .../AnySecurityIdentityBuilder.java | 40 +- .../java/com/coveo/pushapiclient/ApiUrl.java | 204 ++-- .../com/coveo/pushapiclient/BaseSource.java | 49 +- .../coveo/pushapiclient/BatchIdentity.java | 71 +- .../pushapiclient/BatchIdentityRecord.java | 38 +- .../com/coveo/pushapiclient/BatchUpdate.java | 89 +- .../pushapiclient/BatchUpdateRecord.java | 83 +- .../coveo/pushapiclient/CatalogSource.java | 262 ++-- .../pushapiclient/CompressedBinaryData.java | 107 +- .../coveo/pushapiclient/CompressionType.java | 54 +- .../coveo/pushapiclient/DeleteDocument.java | 34 +- .../com/coveo/pushapiclient/Document.java | 274 ++--- .../coveo/pushapiclient/DocumentBuilder.java | 743 ++++++------ .../pushapiclient/DocumentPermissions.java | 31 +- .../pushapiclient/DocumentUploadQueue.java | 166 ++- .../com/coveo/pushapiclient/Environment.java | 26 +- .../coveo/pushapiclient/FileContainer.java | 10 +- .../GroupSecurityIdentityBuilder.java | 103 +- .../coveo/pushapiclient/IdentityModel.java | 16 +- .../coveo/pushapiclient/PlatformClient.java | 1063 +++++++++-------- .../com/coveo/pushapiclient/PlatformUrl.java | 72 +- .../pushapiclient/PlatformUrlBuilder.java | 26 +- .../coveo/pushapiclient/PushAPIStatus.java | 11 +- .../pushapiclient/PushEnabledSource.java | 4 +- .../com/coveo/pushapiclient/PushSource.java | 566 +++++---- .../java/com/coveo/pushapiclient/Region.java | 26 +- .../coveo/pushapiclient/SecurityIdentity.java | 58 +- .../SecurityIdentityAliasModel.java | 15 +- .../SecurityIdentityBatchConfig.java | 79 +- .../SecurityIdentityBatchResponse.java | 31 +- .../SecurityIdentityBuilder.java | 17 +- .../pushapiclient/SecurityIdentityDelete.java | 60 +- .../SecurityIdentityDeleteOptions.java | 80 +- .../pushapiclient/SecurityIdentityModel.java | 15 +- .../SecurityIdentityModelBase.java | 12 +- .../pushapiclient/SecurityIdentityType.java | 40 +- .../java/com/coveo/pushapiclient/Source.java | 446 +++---- .../com/coveo/pushapiclient/SourceType.java | 65 +- .../coveo/pushapiclient/SourceVisibility.java | 43 +- .../pushapiclient/StreamEnabledSource.java | 4 +- .../coveo/pushapiclient/StreamResponse.java | 9 +- .../coveo/pushapiclient/StreamService.java | 200 ++-- .../pushapiclient/StreamServiceInternal.java | 84 +- .../coveo/pushapiclient/UploadStrategy.java | 2 +- .../UserSecurityIdentityBuilder.java | 138 ++- .../VirtualGroupSecurityIdentityBuilder.java | 104 +- .../exceptions/NoOpenStreamException.java | 6 +- .../com/coveo/pushapiclient/ApiUrlTest.java | 156 +-- .../pushapiclient/BatchUpdateRecordTest.java | 106 +- .../coveo/pushapiclient/BatchUpdateTest.java | 147 ++- .../CompressedBinaryDataTest.java | 96 +- .../pushapiclient/DocumentBuilderTest.java | 719 ++++++----- .../DocumentUploadQueueTest.java | 330 ++--- .../GroupSecurityIdentityBuilderTest.java | 121 +- .../pushapiclient/PlatformClientTest.java | 760 +++++++----- .../pushapiclient/PlatformUrlBuilderTest.java | 120 +- .../SecurityIdentityBatchConfigTest.java | 94 +- .../SecurityIdentityDeleteOptionsTest.java | 100 +- .../SecurityIdentityDeleteTest.java | 111 +- .../StreamServiceInternalTest.java | 129 +- .../coveo/pushapiclient/StringSubscriber.java | 76 +- .../UserSecurityIdentityBuilderTest.java | 151 +-- ...rtualGroupSecurityIdentityBuilderTest.java | 121 +- 64 files changed, 4605 insertions(+), 4419 deletions(-) diff --git a/src/main/java/com/coveo/pushapiclient/AliasMapping.java b/src/main/java/com/coveo/pushapiclient/AliasMapping.java index c43ad1e9..3c9866a8 100644 --- a/src/main/java/com/coveo/pushapiclient/AliasMapping.java +++ b/src/main/java/com/coveo/pushapiclient/AliasMapping.java @@ -3,10 +3,11 @@ import java.util.Map; public class AliasMapping extends IdentityModel { - public final String provider; + public final String provider; - public AliasMapping(String provider, String name, SecurityIdentityType type, Map additionalInfo) { - super(name, type, additionalInfo); - this.provider = provider; - } + public AliasMapping( + String provider, String name, SecurityIdentityType type, Map additionalInfo) { + super(name, type, additionalInfo); + this.provider = provider; + } } diff --git a/src/main/java/com/coveo/pushapiclient/AnySecurityIdentityBuilder.java b/src/main/java/com/coveo/pushapiclient/AnySecurityIdentityBuilder.java index b6ee814f..f1ef831c 100644 --- a/src/main/java/com/coveo/pushapiclient/AnySecurityIdentityBuilder.java +++ b/src/main/java/com/coveo/pushapiclient/AnySecurityIdentityBuilder.java @@ -3,25 +3,29 @@ import java.util.Arrays; public class AnySecurityIdentityBuilder implements SecurityIdentityBuilder { - private final String[] identities; - private final SecurityIdentityType securityIdentityType; - private final String securityProvider; + private final String[] identities; + private final SecurityIdentityType securityIdentityType; + private final String securityProvider; - public AnySecurityIdentityBuilder(String identity, SecurityIdentityType securityIdentityType, String securityProvider) { - this.identities = new String[]{identity}; - this.securityIdentityType = securityIdentityType; - this.securityProvider = securityProvider; - } + public AnySecurityIdentityBuilder( + String identity, SecurityIdentityType securityIdentityType, String securityProvider) { + this.identities = new String[] {identity}; + this.securityIdentityType = securityIdentityType; + this.securityProvider = securityProvider; + } - public AnySecurityIdentityBuilder(String[] identities, SecurityIdentityType securityIdentityType, String securityProvider) { - this.identities = identities; - this.securityIdentityType = securityIdentityType; - this.securityProvider = securityProvider; - } + public AnySecurityIdentityBuilder( + String[] identities, SecurityIdentityType securityIdentityType, String securityProvider) { + this.identities = identities; + this.securityIdentityType = securityIdentityType; + this.securityProvider = securityProvider; + } - public SecurityIdentity[] build() { - return Arrays.stream(this.identities) - .map(identity -> new SecurityIdentity(identity, this.securityIdentityType, this.securityProvider)) - .toArray(SecurityIdentity[]::new); - } + public SecurityIdentity[] build() { + return Arrays.stream(this.identities) + .map( + identity -> + new SecurityIdentity(identity, this.securityIdentityType, this.securityProvider)) + .toArray(SecurityIdentity[]::new); + } } diff --git a/src/main/java/com/coveo/pushapiclient/ApiUrl.java b/src/main/java/com/coveo/pushapiclient/ApiUrl.java index b416576d..55d1f27a 100644 --- a/src/main/java/com/coveo/pushapiclient/ApiUrl.java +++ b/src/main/java/com/coveo/pushapiclient/ApiUrl.java @@ -9,114 +9,118 @@ import java.util.regex.Pattern; /** - * Private util class to extract dynamic parts from a API URL - * Handles extraction of identifiers and platform URL from a source URL. - * - * @See https://docs.coveo.com/en/1546#push-api-url - * https://docs.coveo.com/en/3295#stream-api-url + * Private util class to extract dynamic parts from a API URL Handles extraction of identifiers and + * platform URL from a source URL. @See https://docs.coveo.com/en/1546#push-api-url + * https://docs.coveo.com/en/3295#stream-api-url */ class ApiUrl { - private final String organizationId; - private final String sourceId; - private final PlatformUrl platformUrl; - private final String sourceUrl; - - public ApiUrl(URL sourceUrl) throws MalformedURLException { - List identifiers = this.extractIdentifiers(sourceUrl); - this.organizationId = identifiers.get(0); - this.sourceId = identifiers.get(1); - this.sourceUrl = sourceUrl.toString(); - this.platformUrl = this.extractPlatformUrl(sourceUrl); + private final String organizationId; + private final String sourceId; + private final PlatformUrl platformUrl; + private final String sourceUrl; + + public ApiUrl(URL sourceUrl) throws MalformedURLException { + List identifiers = this.extractIdentifiers(sourceUrl); + this.organizationId = identifiers.get(0); + this.sourceId = identifiers.get(1); + this.sourceUrl = sourceUrl.toString(); + this.platformUrl = this.extractPlatformUrl(sourceUrl); + } + + public ApiUrl(String organizationId, String sourceId, PlatformUrl platformUrl) { + this.organizationId = organizationId; + this.sourceId = sourceId; + this.platformUrl = platformUrl; + this.sourceUrl = + String.format( + "https://api.cloud.coveo.com/push/v1/organizations/%s/sources/%s", + this.organizationId, this.sourceId); + } + + public String getUrl() { + return this.sourceUrl; + } + + public String getOrganizationId() { + return this.organizationId; + } + + public String getSourceId() { + return this.sourceId; + } + + public PlatformUrl getPlatformUrl() { + return this.platformUrl; + } + + private List extractIdentifiers(URL sourceUrl) throws MalformedURLException { + String host = sourceUrl.getPath(); + Pattern pattern = Pattern.compile("/push/v1/organizations/([^/]+)/sources/([^/]+)"); + Matcher matcher = pattern.matcher(host); + + if (matcher.find()) { + String organizationId = matcher.group(1); + String sourceId = matcher.group(2); + return Arrays.asList(organizationId, sourceId); } - public ApiUrl(String organizationId, String sourceId, PlatformUrl platformUrl) { - this.organizationId = organizationId; - this.sourceId = sourceId; - this.platformUrl = platformUrl; - this.sourceUrl = String.format("https://api.cloud.coveo.com/push/v1/organizations/%s/sources/%s", - this.organizationId, this.sourceId); + String errorMessage = + this.getErrorMessage( + "Unable to find organization and source ids from the provided API url"); + throw new MalformedURLException(errorMessage); + } + + private PlatformUrl extractPlatformUrl(URL sourceUrl) throws MalformedURLException { + String host = sourceUrl.getHost(); + Pattern pattern = Pattern.compile("api([a-z]*)([a-z-]*)\\.cloud\\.coveo\\.com"); + Matcher matcher = pattern.matcher(host); + + if (matcher.find()) { + String extractedEnvironment = matcher.group(1); + String extractedRegion = matcher.group(2).replace("-", ""); + + Environment urlEnvironment = + extractedEnvironment.isEmpty() + ? PlatformUrl.DEFAULT_ENVIRONMENT + : EnumSet.allOf(Environment.class).stream() + .filter(e -> e.getValue().equalsIgnoreCase(extractedEnvironment)) + .findFirst() + .orElseThrow( + () -> + new MalformedURLException( + String.format( + "Invalid platform environment '%s'", extractedEnvironment))); + + Region urlRegion = + extractedRegion.isEmpty() + ? PlatformUrl.DEFAULT_REGION + : EnumSet.allOf(Region.class).stream() + .filter(r -> r.getValue().equalsIgnoreCase(extractedRegion)) + .findFirst() + .orElseThrow( + () -> + new MalformedURLException( + String.format("Invalid platform region '%s'", extractedRegion))); + + return new PlatformUrl(urlEnvironment, urlRegion); } - public String getUrl() { - return this.sourceUrl; - } - - public String getOrganizationId() { - return this.organizationId; - } - - public String getSourceId() { - return this.sourceId; - } - - public PlatformUrl getPlatformUrl() { - return this.platformUrl; - } + String invalidHostMessage = this.getErrorMessage("Invalid API URL host"); + throw new MalformedURLException(invalidHostMessage); + } - private List extractIdentifiers(URL sourceUrl) throws MalformedURLException { - String host = sourceUrl.getPath(); - Pattern pattern = Pattern.compile("/push/v1/organizations/([^/]+)/sources/([^/]+)"); - Matcher matcher = pattern.matcher(host); + private String getErrorMessage(String reason) { + String newLine = System.getProperty("line.separator"); + String message = "The provided API URL is invalid"; - if (matcher.find()) { - String organizationId = matcher.group(1); - String sourceId = matcher.group(2); - return Arrays.asList(organizationId, sourceId); - } + message.concat(newLine).concat(reason); - String errorMessage = this - .getErrorMessage("Unable to find organization and source ids from the provided API url"); - throw new MalformedURLException(errorMessage); - } - - private PlatformUrl extractPlatformUrl(URL sourceUrl) throws MalformedURLException { - String host = sourceUrl.getHost(); - Pattern pattern = Pattern.compile("api([a-z]*)([a-z-]*)\\.cloud\\.coveo\\.com"); - Matcher matcher = pattern.matcher(host); - - if (matcher.find()) { - String extractedEnvironment = matcher.group(1); - String extractedRegion = matcher.group(2).replace("-", ""); - - Environment urlEnvironment = extractedEnvironment.isEmpty() - ? PlatformUrl.DEFAULT_ENVIRONMENT - : EnumSet.allOf(Environment.class) - .stream() - .filter(e -> e.getValue().equalsIgnoreCase(extractedEnvironment)) - .findFirst() - .orElseThrow(() -> new MalformedURLException( - String.format("Invalid platform environment '%s'", extractedEnvironment))); - - Region urlRegion = extractedRegion.isEmpty() - ? PlatformUrl.DEFAULT_REGION - : EnumSet.allOf(Region.class) - .stream() - .filter(r -> r.getValue().equalsIgnoreCase(extractedRegion)) - .findFirst() - .orElseThrow(() -> new MalformedURLException( - String.format("Invalid platform region '%s'", extractedRegion))); - - return new PlatformUrl(urlEnvironment, urlRegion); - - } - - String invalidHostMessage = this.getErrorMessage("Invalid API URL host"); - throw new MalformedURLException(invalidHostMessage); - } - - private String getErrorMessage(String reason) { - String newLine = System.getProperty("line.separator"); - String message = "The provided API URL is invalid"; - - message.concat(newLine).concat(reason); - - message - .concat(newLine) - .concat("For a Push Source, visit: https://docs.coveo.com/en/1546") - .concat(newLine) - .concat("For a Catalog Source, visit:https://docs.coveo.com/en/3295"); - - return message; - } + message + .concat(newLine) + .concat("For a Push Source, visit: https://docs.coveo.com/en/1546") + .concat(newLine) + .concat("For a Catalog Source, visit:https://docs.coveo.com/en/3295"); + return message; + } } diff --git a/src/main/java/com/coveo/pushapiclient/BaseSource.java b/src/main/java/com/coveo/pushapiclient/BaseSource.java index a3edd80c..169fd645 100644 --- a/src/main/java/com/coveo/pushapiclient/BaseSource.java +++ b/src/main/java/com/coveo/pushapiclient/BaseSource.java @@ -1,32 +1,31 @@ package com.coveo.pushapiclient; public interface BaseSource { - /** - * Returns the API key used for all operations regarding your source. - * - * @return - */ - String getApiKey(); + /** + * Returns the API key used for all operations regarding your source. + * + * @return + */ + String getApiKey(); - /** - * Returns the {@link PlatformUrl} object associated to the source. - * - * @return - */ - PlatformUrl getPlatformUrl(); + /** + * Returns the {@link PlatformUrl} object associated to the source. + * + * @return + */ + PlatformUrl getPlatformUrl(); - /** - * The unique identifier of your organization. - * - * @return - */ - String getOrganizationId(); - - /** - * The unique identifier of your source. - * - * @return - */ - String getId(); + /** + * The unique identifier of your organization. + * + * @return + */ + String getOrganizationId(); + /** + * The unique identifier of your source. + * + * @return + */ + String getId(); } diff --git a/src/main/java/com/coveo/pushapiclient/BatchIdentity.java b/src/main/java/com/coveo/pushapiclient/BatchIdentity.java index f7d376b8..710e0ee0 100644 --- a/src/main/java/com/coveo/pushapiclient/BatchIdentity.java +++ b/src/main/java/com/coveo/pushapiclient/BatchIdentity.java @@ -2,41 +2,46 @@ import com.google.gson.Gson; import com.google.gson.JsonObject; - import java.util.List; -/** - * See [Manage Batches of Security Identities](https://docs.coveo.com/en/55) - */ +/** See [Manage Batches of Security Identities](https://docs.coveo.com/en/55) */ public class BatchIdentity { - private List members; - private List mappings; - private List deleted; - - public BatchIdentity(List members, List mappings, List deleted) { - this.members = members; - this.mappings = mappings; - this.deleted = deleted; - } - - public BatchIdentityRecord marshal() { - return new BatchIdentityRecord( - this.members.stream().map(s -> new Gson().toJsonTree(s).getAsJsonObject()).toArray(JsonObject[]::new), - this.mappings.stream().map(s -> new Gson().toJsonTree(s).getAsJsonObject()).toArray(JsonObject[]::new), - this.deleted.stream().map(s -> new Gson().toJsonTree(s).getAsJsonObject()).toArray(JsonObject[]::new) - ); - } - - public List getMembers() { - return members; - } - - public List getMappings() { - return mappings; - } - - public List getDeleted() { - return deleted; - } + private List members; + private List mappings; + private List deleted; + + public BatchIdentity( + List members, + List mappings, + List deleted) { + this.members = members; + this.mappings = mappings; + this.deleted = deleted; + } + + public BatchIdentityRecord marshal() { + return new BatchIdentityRecord( + this.members.stream() + .map(s -> new Gson().toJsonTree(s).getAsJsonObject()) + .toArray(JsonObject[]::new), + this.mappings.stream() + .map(s -> new Gson().toJsonTree(s).getAsJsonObject()) + .toArray(JsonObject[]::new), + this.deleted.stream() + .map(s -> new Gson().toJsonTree(s).getAsJsonObject()) + .toArray(JsonObject[]::new)); + } + + public List getMembers() { + return members; + } + + public List getMappings() { + return mappings; + } + + public List getDeleted() { + return deleted; + } } diff --git a/src/main/java/com/coveo/pushapiclient/BatchIdentityRecord.java b/src/main/java/com/coveo/pushapiclient/BatchIdentityRecord.java index c807cc1d..f0670036 100644 --- a/src/main/java/com/coveo/pushapiclient/BatchIdentityRecord.java +++ b/src/main/java/com/coveo/pushapiclient/BatchIdentityRecord.java @@ -2,30 +2,28 @@ import com.google.gson.JsonObject; -/** - * See [BatchIdentityBody](https://docs.coveo.com/en/139#batchidentitybody) - */ +/** See [BatchIdentityBody](https://docs.coveo.com/en/139#batchidentitybody) */ public class BatchIdentityRecord { - private JsonObject[] members; - private JsonObject[] mappings; - private JsonObject[] deleted; + private JsonObject[] members; + private JsonObject[] mappings; + private JsonObject[] deleted; - public BatchIdentityRecord(JsonObject[] members, JsonObject[] mappings, JsonObject[] deleted) { - this.members = members; - this.mappings = mappings; - this.deleted = deleted; - } + public BatchIdentityRecord(JsonObject[] members, JsonObject[] mappings, JsonObject[] deleted) { + this.members = members; + this.mappings = mappings; + this.deleted = deleted; + } - public JsonObject[] getMembers() { - return members; - } + public JsonObject[] getMembers() { + return members; + } - public JsonObject[] getMappings() { - return mappings; - } + public JsonObject[] getMappings() { + return mappings; + } - public JsonObject[] getDeleted() { - return deleted; - } + public JsonObject[] getDeleted() { + return deleted; + } } diff --git a/src/main/java/com/coveo/pushapiclient/BatchUpdate.java b/src/main/java/com/coveo/pushapiclient/BatchUpdate.java index 2a7efa6d..c251fe5b 100644 --- a/src/main/java/com/coveo/pushapiclient/BatchUpdate.java +++ b/src/main/java/com/coveo/pushapiclient/BatchUpdate.java @@ -1,56 +1,51 @@ package com.coveo.pushapiclient; import com.google.gson.JsonObject; - import java.util.List; import java.util.Objects; -/** - * See [Manage Batches of Items in a Push Source](https://docs.coveo.com/en/90) - */ +/** See [Manage Batches of Items in a Push Source](https://docs.coveo.com/en/90) */ public class BatchUpdate { - private final List addOrUpdate; - private final List delete; - - public BatchUpdate(List addOrUpdate, List delete) { - this.addOrUpdate = addOrUpdate; - this.delete = delete; - } - - public BatchUpdateRecord marshal() { - return new BatchUpdateRecord( - this.addOrUpdate.stream().map(DocumentBuilder::marshalJsonObject).toArray(JsonObject[]::new), - this.delete.stream().map(DeleteDocument::marshalJsonObject).toArray(JsonObject[]::new) - ); - } - - public List getAddOrUpdate() { - return addOrUpdate; - } - - public List getDelete() { - return delete; - } - - @Override - public String toString() { - return "BatchUpdate[" + - "addOrUpdate=" + addOrUpdate + - ", delete=" + delete + - ']'; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null || getClass() != obj.getClass()) return false; - BatchUpdate that = (BatchUpdate) obj; - return addOrUpdate.equals(that.addOrUpdate) && delete.equals(that.delete); - } - - @Override - public int hashCode() { - return Objects.hash(addOrUpdate, delete); - } + private final List addOrUpdate; + private final List delete; + + public BatchUpdate(List addOrUpdate, List delete) { + this.addOrUpdate = addOrUpdate; + this.delete = delete; + } + + public BatchUpdateRecord marshal() { + return new BatchUpdateRecord( + this.addOrUpdate.stream() + .map(DocumentBuilder::marshalJsonObject) + .toArray(JsonObject[]::new), + this.delete.stream().map(DeleteDocument::marshalJsonObject).toArray(JsonObject[]::new)); + } + + public List getAddOrUpdate() { + return addOrUpdate; + } + + public List getDelete() { + return delete; + } + + @Override + public String toString() { + return "BatchUpdate[" + "addOrUpdate=" + addOrUpdate + ", delete=" + delete + ']'; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null || getClass() != obj.getClass()) return false; + BatchUpdate that = (BatchUpdate) obj; + return addOrUpdate.equals(that.addOrUpdate) && delete.equals(that.delete); + } + + @Override + public int hashCode() { + return Objects.hash(addOrUpdate, delete); + } } diff --git a/src/main/java/com/coveo/pushapiclient/BatchUpdateRecord.java b/src/main/java/com/coveo/pushapiclient/BatchUpdateRecord.java index 56c90fda..f511d363 100644 --- a/src/main/java/com/coveo/pushapiclient/BatchUpdateRecord.java +++ b/src/main/java/com/coveo/pushapiclient/BatchUpdateRecord.java @@ -1,50 +1,49 @@ package com.coveo.pushapiclient; import com.google.gson.JsonObject; - import java.util.Arrays; -/** - * See [BatchDocumentBody](https://docs.coveo.com/en/75/#batchdocumentbody) - */ +/** See [BatchDocumentBody](https://docs.coveo.com/en/75/#batchdocumentbody) */ public class BatchUpdateRecord { - private final JsonObject[] addOrUpdate; - private final JsonObject[] delete; - - public BatchUpdateRecord(JsonObject[] addOrUpdate, JsonObject[] delete) { - this.addOrUpdate = addOrUpdate; - this.delete = delete; - } - - public JsonObject[] getAddOrUpdate() { - return addOrUpdate; - } - - public JsonObject[] getDelete() { - return delete; - } - - @Override - public String toString() { - return "BatchUpdateRecord[" + - "addOrUpdate=" + Arrays.toString(addOrUpdate) + - ", delete=" + Arrays.toString(delete) + - ']'; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null || getClass() != obj.getClass()) return false; - BatchUpdateRecord that = (BatchUpdateRecord) obj; - return Arrays.equals(addOrUpdate, that.addOrUpdate) && Arrays.equals(delete, that.delete); - } - - @Override - public int hashCode() { - int result = Arrays.hashCode(addOrUpdate); - result = 31 * result + Arrays.hashCode(delete); - return result; - } + private final JsonObject[] addOrUpdate; + private final JsonObject[] delete; + + public BatchUpdateRecord(JsonObject[] addOrUpdate, JsonObject[] delete) { + this.addOrUpdate = addOrUpdate; + this.delete = delete; + } + + public JsonObject[] getAddOrUpdate() { + return addOrUpdate; + } + + public JsonObject[] getDelete() { + return delete; + } + + @Override + public String toString() { + return "BatchUpdateRecord[" + + "addOrUpdate=" + + Arrays.toString(addOrUpdate) + + ", delete=" + + Arrays.toString(delete) + + ']'; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null || getClass() != obj.getClass()) return false; + BatchUpdateRecord that = (BatchUpdateRecord) obj; + return Arrays.equals(addOrUpdate, that.addOrUpdate) && Arrays.equals(delete, that.delete); + } + + @Override + public int hashCode() { + int result = Arrays.hashCode(addOrUpdate); + result = 31 * result + Arrays.hashCode(delete); + return result; + } } diff --git a/src/main/java/com/coveo/pushapiclient/CatalogSource.java b/src/main/java/com/coveo/pushapiclient/CatalogSource.java index ea723153..27980c92 100644 --- a/src/main/java/com/coveo/pushapiclient/CatalogSource.java +++ b/src/main/java/com/coveo/pushapiclient/CatalogSource.java @@ -7,165 +7,123 @@ // TODO: LENS-851 - Make public when ready class CatalogSource implements StreamEnabledSource { - private final String apiKey; - private final ApiUrl urlExtractor; + private final String apiKey; + private final ApiUrl urlExtractor; + /** + * Creates a Catalog Source in Coveo Org + * + * @param platformClient + * @param name The name of the source to create + * @param sourceVisibility The security option that should be applied to the content of the + * source. See [Content Security](https://docs.coveo.com/en/1779). + * @return + * @throws IOException + * @throws InterruptedException + */ + public static HttpResponse create( + PlatformClient platformClient, String name, SourceVisibility sourceVisibility) + throws IOException, InterruptedException { + return platformClient.createSource(name, SourceType.CATALOG, sourceVisibility); + } - /** - * Creates a Catalog Source in Coveo Org - * - * @param platformClient - * @param name The name of the source to create - * @param sourceVisibility The security option that should be applied to the content of the source. See [Content Security](https://docs.coveo.com/en/1779). - * @return - * @throws IOException - * @throws InterruptedException - */ - public static HttpResponse create(PlatformClient platformClient, String name, SourceVisibility sourceVisibility) throws IOException, InterruptedException { - return platformClient.createSource(name, SourceType.CATALOG, sourceVisibility); - } + /** + * Create a Catalog source instance from its Stream API URL + * + * @param apiKey The API key used for all operations regarding your source. + *

Ensure your API key has the required privileges for the operation you will be performing + * * + *

For more information about which privileges are required, see Privilege Reference. + * @param sourceUrl The URL available when you edit your source in the Coveo Administration + * Console. The URL should contain your ORGANIZATION_ID and SOURCE_ID + * , which are required parameters for all operations regarding your source. + *

Some examples of valid source URLs: + *

+   * https://api.cloud.coveo.com/push/v1/organizations/my-org-if/sources/my-source-id/stream/open
+   * https://api-eu.cloud.coveo.com/push/v1/organizations/my-org-if/sources/my-source-id/stream/open
+   *                  
+ * + * @throws MalformedURLException + */ + public CatalogSource(String apiKey, URL sourceUrl) throws MalformedURLException { + this.apiKey = apiKey; + this.urlExtractor = new ApiUrl(sourceUrl); + } - /** - * Create a Catalog source instance from its - * Stream API URL - * - * @param apiKey The API key used for all operations regarding your source. - *

- * Ensure your API key has the required privileges for the - * operation you will be performing - * * - *

- * For more information about which privileges are required, - * see - * Privilege - * Reference. - * - * @param sourceUrl The URL available when you edit your source in the Coveo - * Administration Console. The URL should contain your - * ORGANIZATION_ID and SOURCE_ID, - * which are required parameters for all operations regarding - * your source. - *

- * Some examples of valid source URLs: - * - *

-     * https://api.cloud.coveo.com/push/v1/organizations/my-org-if/sources/my-source-id/stream/open
-     * https://api-eu.cloud.coveo.com/push/v1/organizations/my-org-if/sources/my-source-id/stream/open
-     *                  
- * - * @throws MalformedURLException - */ - public CatalogSource(String apiKey, URL sourceUrl) throws MalformedURLException { - this.apiKey = apiKey; - this.urlExtractor = new ApiUrl(sourceUrl); - } + /** + * Create a Catalog source instance from its Stream API URL + * + * @param apiKey The API key used for all operations regarding your source. + *

Ensure your API key has the required privileges for the operation you will be performing + * * + *

For more information about which privileges are required, see Privilege Reference. + * @param organizationId The unique identifier of your organization. + *

The Organization Id can be retrieved in the URL of your Coveo organization. + * @param sourceId The unique identifier of the target Catalog source. + *

The Source Id can be retrieved when you edit your source in the Coveo Administration + * Console + */ + public static CatalogSource fromPlatformUrl( + String apiKey, String organizationId, String sourceId) { + PlatformUrl platformUrl = + new PlatformUrl(PlatformUrl.DEFAULT_ENVIRONMENT, PlatformUrl.DEFAULT_REGION); + return new CatalogSource(apiKey, organizationId, sourceId, platformUrl); + } - /** - * Create a Catalog source instance from its - * Stream API URL - * - * @param apiKey The API key used for all operations regarding your - * source. - *

- * Ensure your API key has the required privileges for the - * operation you will be performing - * * - *

- * For more information about which privileges are - * required, - * see - * Privilege - * Reference. - * - * @param organizationId The unique identifier of your organization. - *

- * The Organization Id can be retrieved in the URL of your - * Coveo organization. - * - * @param sourceId The unique identifier of the target Catalog source. - *

- * The Source Id can be retrieved when you edit your - * source in the Coveo - * Administration Console - * - */ - public static CatalogSource fromPlatformUrl(String apiKey, String organizationId, String sourceId) { - PlatformUrl platformUrl = new PlatformUrl(PlatformUrl.DEFAULT_ENVIRONMENT, PlatformUrl.DEFAULT_REGION); - return new CatalogSource(apiKey, organizationId, sourceId, platformUrl); - } + /** + * Create a Catalog source instance from its Stream API URL + * + * @param apiKey The API key used for all operations regarding your source. + *

Ensure your API key has the required privileges for the operation you will be performing + * * + *

For more information about which privileges are required, see Privilege Reference. + * @param organizationId The unique identifier of your organization. + *

The Organization Id can be retrieved in the URL of your Coveo organization. + * @param sourceId The unique identifier of the target Catalog source. + *

The Source Id can be retrieved when you edit your source in the Coveo Administration + * Console + * @param platformUrl The object containing additional information on the URL endpoint. You can + * use the {@link PlatformUrl} when your organization is located in a non-default Coveo + * environement and/or region. When not specified, the default platform URL values will be + * used: {@link PlatformUrl#DEFAULT_ENVIRONMENT} and {@link PlatformUrl#DEFAULT_REGION} + */ + public static CatalogSource fromPlatformUrl( + String apiKey, String organizationId, String sourceId, PlatformUrl platformUrl) { + return new CatalogSource(apiKey, organizationId, sourceId, platformUrl); + } - /** - * Create a Catalog source instance from its - * Stream API URL - * - * @param apiKey The API key used for all operations regarding your - * source. - *

- * Ensure your API key has the required privileges for the - * operation you will be performing - * * - *

- * For more information about which privileges are - * required, - * see - * Privilege - * Reference. - * - * @param organizationId The unique identifier of your organization. - *

- * The Organization Id can be retrieved in the URL of your - * Coveo organization. - * - * @param sourceId The unique identifier of the target Catalog source. - *

- * The Source Id can be retrieved when you edit your - * source in the Coveo - * Administration Console - * - * @param platformUrl The object containing additional information on the - * URL endpoint. - * You can use the {@link PlatformUrl} when your - * organization is located in a non-default Coveo - * environement and/or region. When not specified, the - * default platform URL values will be used: - * {@link PlatformUrl#DEFAULT_ENVIRONMENT} and - * {@link PlatformUrl#DEFAULT_REGION} - * - */ - public static CatalogSource fromPlatformUrl(String apiKey, String organizationId, String sourceId, - PlatformUrl platformUrl) { - return new CatalogSource(apiKey, organizationId, sourceId, platformUrl); - } + private CatalogSource( + String apiKey, String organizationId, String sourceId, PlatformUrl platformUrl) { + this.apiKey = apiKey; + this.urlExtractor = new ApiUrl(organizationId, sourceId, platformUrl); + } - private CatalogSource(String apiKey, String organizationId, String sourceId, PlatformUrl platformUrl) { - this.apiKey = apiKey; - this.urlExtractor = new ApiUrl(organizationId, sourceId, platformUrl); - } + @Override + public String getOrganizationId() { + return this.urlExtractor.getOrganizationId(); + } - @Override - public String getOrganizationId() { - return this.urlExtractor.getOrganizationId(); - } + @Override + public PlatformUrl getPlatformUrl() { + return this.urlExtractor.getPlatformUrl(); + } - @Override - public PlatformUrl getPlatformUrl() { - return this.urlExtractor.getPlatformUrl(); - } - - @Override - public String getId() { - return this.urlExtractor.getSourceId(); - } - - @Override - public String getApiKey() { - return this.apiKey; - } + @Override + public String getId() { + return this.urlExtractor.getSourceId(); + } + @Override + public String getApiKey() { + return this.apiKey; + } } diff --git a/src/main/java/com/coveo/pushapiclient/CompressedBinaryData.java b/src/main/java/com/coveo/pushapiclient/CompressedBinaryData.java index 4d252e49..d15aafff 100644 --- a/src/main/java/com/coveo/pushapiclient/CompressedBinaryData.java +++ b/src/main/java/com/coveo/pushapiclient/CompressedBinaryData.java @@ -3,56 +3,63 @@ import java.util.Objects; /** - * The original binary item content, compressed using one of the supported compression types (Deflate, GZip, LZMA, Uncompressed, or ZLib), and then Base64 encoded. - *

- * You can use this parameter when you're pushing a compressed binary item (such as XML/HTML, PDF, Word, or binary) whose size is less than 5 MB. - *

- * Whenever you're pushing an item whose size is 5 MB or more, use the CompressedBinaryDataFileId property instead. - *

- * If you're pushing less than 5 MB of textual (non-binary) content, you can use the data property instead. - *

- * See https://docs.coveo.com/en/73 for more information. + * The original binary item content, compressed using one of the supported compression types + * (Deflate, GZip, LZMA, Uncompressed, or ZLib), and then Base64 encoded. + * + *

You can use this parameter when you're pushing a compressed binary item (such as XML/HTML, + * PDF, Word, or binary) whose size is less than 5 MB. + * + *

Whenever you're pushing an item whose size is 5 MB or more, use the CompressedBinaryDataFileId + * property instead. + * + *

If you're pushing less than 5 MB of textual (non-binary) content, you can use the data + * property instead. + * + *

See https://docs.coveo.com/en/73 for more information. */ public class CompressedBinaryData { - private final String data; - private final CompressionType compressionType; - - /** - * @param data The base64 encoded binary data. Example: `eJxzrUjMLchJBQAK4ALN` - * @param compressionType The compression type that was applied to your document. - */ - public CompressedBinaryData(String data, CompressionType compressionType) { - this.data = data; - this.compressionType = compressionType; - } - - public String getData() { - return data; - } - - public CompressionType getCompressionType() { - return compressionType; - } - - @Override - public String toString() { - return "CompressedBinaryData[" + - "data='" + data + '\'' + - ", compressionType=" + compressionType + - ']'; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null || getClass() != obj.getClass()) return false; - CompressedBinaryData that = (CompressedBinaryData) obj; - return Objects.equals(data, that.data) && compressionType == that.compressionType; - } - - @Override - public int hashCode() { - return Objects.hash(data, compressionType); - } -} \ No newline at end of file + private final String data; + private final CompressionType compressionType; + + /** + * @param data The base64 encoded binary data. Example: `eJxzrUjMLchJBQAK4ALN` + * @param compressionType The compression type that was applied to your document. + */ + public CompressedBinaryData(String data, CompressionType compressionType) { + this.data = data; + this.compressionType = compressionType; + } + + public String getData() { + return data; + } + + public CompressionType getCompressionType() { + return compressionType; + } + + @Override + public String toString() { + return "CompressedBinaryData[" + + "data='" + + data + + '\'' + + ", compressionType=" + + compressionType + + ']'; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null || getClass() != obj.getClass()) return false; + CompressedBinaryData that = (CompressedBinaryData) obj; + return Objects.equals(data, that.data) && compressionType == that.compressionType; + } + + @Override + public int hashCode() { + return Objects.hash(data, compressionType); + } +} diff --git a/src/main/java/com/coveo/pushapiclient/CompressionType.java b/src/main/java/com/coveo/pushapiclient/CompressionType.java index 8490aafc..2329e47e 100644 --- a/src/main/java/com/coveo/pushapiclient/CompressionType.java +++ b/src/main/java/com/coveo/pushapiclient/CompressionType.java @@ -1,32 +1,30 @@ package com.coveo.pushapiclient; -/** - * The compression type that was applied to your compressed document. - */ +/** The compression type that was applied to your compressed document. */ public enum CompressionType { - UNCOMPRESSED { - public String toString() { - return "UNCOMPRESSED"; - } - }, - DEFLATE { - public String toString() { - return "DEFLATE"; - } - }, - GZIP { - public String toString() { - return "GZIP"; - } - }, - LZMA { - public String toString() { - return "LZMA"; - } - }, - ZLIB { - public String toString() { - return "ZLIB"; - } + UNCOMPRESSED { + public String toString() { + return "UNCOMPRESSED"; } -} \ No newline at end of file + }, + DEFLATE { + public String toString() { + return "DEFLATE"; + } + }, + GZIP { + public String toString() { + return "GZIP"; + } + }, + LZMA { + public String toString() { + return "LZMA"; + } + }, + ZLIB { + public String toString() { + return "ZLIB"; + } + } +} diff --git a/src/main/java/com/coveo/pushapiclient/DeleteDocument.java b/src/main/java/com/coveo/pushapiclient/DeleteDocument.java index 200d7c42..0cb313f5 100644 --- a/src/main/java/com/coveo/pushapiclient/DeleteDocument.java +++ b/src/main/java/com/coveo/pushapiclient/DeleteDocument.java @@ -5,27 +5,23 @@ public class DeleteDocument { - /** - * The documentId of the document. - */ - public String documentId; + /** The documentId of the document. */ + public String documentId; - /** - * Flag to delete children of the document. - */ - public boolean deleteChildren; + /** Flag to delete children of the document. */ + public boolean deleteChildren; - public DeleteDocument(String documentId) { - this.documentId = documentId; - this.deleteChildren = false; - } + public DeleteDocument(String documentId) { + this.documentId = documentId; + this.deleteChildren = false; + } - public DeleteDocument(String documentId, boolean deleteChildren) { - this.documentId = documentId; - this.deleteChildren = deleteChildren; - } + public DeleteDocument(String documentId, boolean deleteChildren) { + this.documentId = documentId; + this.deleteChildren = deleteChildren; + } - public JsonObject marshalJsonObject() { - return new Gson().toJsonTree(this).getAsJsonObject(); - } + public JsonObject marshalJsonObject() { + return new Gson().toJsonTree(this).getAsJsonObject(); + } } diff --git a/src/main/java/com/coveo/pushapiclient/Document.java b/src/main/java/com/coveo/pushapiclient/Document.java index 30161dec..a02e632b 100644 --- a/src/main/java/com/coveo/pushapiclient/Document.java +++ b/src/main/java/com/coveo/pushapiclient/Document.java @@ -3,138 +3,144 @@ import java.util.HashMap; public class Document { - /** - * The metadata key-value pairs for a given document. - *

- * Each metadata in the document must be unique. - *

- * Metadata are case-insensitive (e.g., the Push API considers mykey, MyKey, myKey, MYKEY, etc. as identical). - *

- * See https://docs.coveo.com/en/115 for more information. - */ - public final HashMap metadata; - - /** - * The list of permission sets for this item. - *

- * This is useful when item based security is required (i.e., when security isn't configured at the source level). - *

- * See https://docs.coveo.com/en/107 for more information. - */ - public DocumentPermissions[] permissions; - - /** - * The Uniform Resource Identifier (URI) that uniquely identifies the document in a Coveo index. - *

- * Examples: - * - `http://www.example.com/` - * - `file://folder/text.txt` - */ - public String uri; - - /** - * The documentId of the document. - */ - public String documentId; - - /** - * The title of the document. - */ - public String title; - - /** - * The clickable URI associated with the document. - */ - public String clickableUri; - - /** - * The author of the document. - */ - public String author; - - /** - * The date of the document, represented as an ISO string. - *

- * Optional, will default to indexation date. - */ - public String date; - - /** - * The modified date of the document, represented as an ISO string. - *

- * Optional, will default to indexation date. - */ - public String modifiedDate; - - /** - * The permanent identifier of a document that does not change over time. - *

- * Optional, will be derived from the document URI. - */ - public String permanentId; - - /** - * The unique identifier (URI) of the parent item. - *

- * Specifying a value for this key creates a relationship between the attachment item (child) and its parent item. - *

- * This value also ensures that a parent and all of its attachments will be routed in the same index slice. - */ - public String parentId; - - /** - * The textual (non-binary) content of the item. - *

- * Whenever you're pushing a compressed binary item (such as XML/HTML, PDF, Word, or binary), you should use the CompressedBinaryData or CompressedBinaryDataFileId attribute instead, depending on the content size. - *

- * Accepts 5 MB or less of uncompressed textual data. - *

- * See https://docs.coveo.com/en/73 for more information. - *

- * Example: `This is a simple string that will be used for searchability as well as to generate excerpt and summaries for the document.` - */ - public String data; - - /** - * The original binary item content, compressed using one of the supported compression types (Deflate, GZip, LZMA, Uncompressed, or ZLib), and then Base64 encoded. - *

- * You can use this parameter when you're pushing a compressed binary item (such as XML/HTML, PDF, Word, or binary) whose size is less than 5 MB. - *

- * Whenever you're pushing an item whose size is 5 MB or more, use the CompressedBinaryDataFileId property instead. - *

- * If you're pushing less than 5 MB of textual (non-binary) content, you can use the data property instead. - *

- * See https://docs.coveo.com/en/73 for more information. - */ - public CompressedBinaryData compressedBinaryData; - - /** - * The fileId from the content that has been uploaded to the S3 via a FileContainer. The file is compressed using one of the supported compression types (Deflate, GZip, LZMA, Uncompressed, or ZLib). - *

- * You can use this parameter when you're pushing a compressed binary item (such as XML/HTML, PDF, Word, or binary) whose size is greater than 5 MB. - *

- * Whenever you're pushing an item whose size is less than 5 MB, use the CompressedBinaryData property instead. - *

- * If you're pushing less than 5 MB of textual (non-binary) content, you can use the data property instead. - *

- * See https://docs.coveo.com/en/73 for more information. - */ - public String compressedBinaryDataFileId; - - /** - * The file extension of the data you're pushing. - *

- * This is useful when pushing a compressed item. The converter uses this information to identify how to correctly process the item. - *

- * Values must include the preceding . character. - *

- * Example: `.html` - */ - public String fileExtension; - - public Document() { - this.permissions = new DocumentPermissions[]{new DocumentPermissions()}; - this.metadata = new HashMap(); - } + /** + * The metadata key-value pairs for a given document. + * + *

Each metadata in the document must be unique. + * + *

Metadata are case-insensitive (e.g., the Push API considers mykey, MyKey, myKey, MYKEY, etc. + * as identical). + * + *

See https://docs.coveo.com/en/115 for more information. + */ + public final HashMap metadata; + + /** + * The list of permission sets for this item. + * + *

This is useful when item based security is required (i.e., when security isn't configured at + * the source level). + * + *

See https://docs.coveo.com/en/107 for more information. + */ + public DocumentPermissions[] permissions; + + /** + * The Uniform Resource Identifier (URI) that uniquely identifies the document in a Coveo index. + * + *

Examples: - `http://www.example.com/` - `file://folder/text.txt` + */ + public String uri; + + /** The documentId of the document. */ + public String documentId; + + /** The title of the document. */ + public String title; + + /** The clickable URI associated with the document. */ + public String clickableUri; + + /** The author of the document. */ + public String author; + + /** + * The date of the document, represented as an ISO string. + * + *

Optional, will default to indexation date. + */ + public String date; + + /** + * The modified date of the document, represented as an ISO string. + * + *

Optional, will default to indexation date. + */ + public String modifiedDate; + + /** + * The permanent identifier of a document that does not change over time. + * + *

Optional, will be derived from the document URI. + */ + public String permanentId; + + /** + * The unique identifier (URI) of the parent item. + * + *

Specifying a value for this key creates a relationship between the attachment item (child) + * and its parent item. + * + *

This value also ensures that a parent and all of its attachments will be routed in the same + * index slice. + */ + public String parentId; + + /** + * The textual (non-binary) content of the item. + * + *

Whenever you're pushing a compressed binary item (such as XML/HTML, PDF, Word, or binary), + * you should use the CompressedBinaryData or CompressedBinaryDataFileId attribute instead, + * depending on the content size. + * + *

Accepts 5 MB or less of uncompressed textual data. + * + *

See https://docs.coveo.com/en/73 for more information. + * + *

Example: `This is a simple string that will be used for searchability as well as to generate + * excerpt and summaries for the document.` + */ + public String data; + + /** + * The original binary item content, compressed using one of the supported compression types + * (Deflate, GZip, LZMA, Uncompressed, or ZLib), and then Base64 encoded. + * + *

You can use this parameter when you're pushing a compressed binary item (such as XML/HTML, + * PDF, Word, or binary) whose size is less than 5 MB. + * + *

Whenever you're pushing an item whose size is 5 MB or more, use the + * CompressedBinaryDataFileId property instead. + * + *

If you're pushing less than 5 MB of textual (non-binary) content, you can use the data + * property instead. + * + *

See https://docs.coveo.com/en/73 for more information. + */ + public CompressedBinaryData compressedBinaryData; + + /** + * The fileId from the content that has been uploaded to the S3 via a FileContainer. The file is + * compressed using one of the supported compression types (Deflate, GZip, LZMA, Uncompressed, or + * ZLib). + * + *

You can use this parameter when you're pushing a compressed binary item (such as XML/HTML, + * PDF, Word, or binary) whose size is greater than 5 MB. + * + *

Whenever you're pushing an item whose size is less than 5 MB, use the CompressedBinaryData + * property instead. + * + *

If you're pushing less than 5 MB of textual (non-binary) content, you can use the data + * property instead. + * + *

See https://docs.coveo.com/en/73 for more information. + */ + public String compressedBinaryDataFileId; + + /** + * The file extension of the data you're pushing. + * + *

This is useful when pushing a compressed item. The converter uses this information to + * identify how to correctly process the item. + * + *

Values must include the preceding . character. + * + *

Example: `.html` + */ + public String fileExtension; + + public Document() { + this.permissions = new DocumentPermissions[] {new DocumentPermissions()}; + this.metadata = new HashMap(); + } } - diff --git a/src/main/java/com/coveo/pushapiclient/DocumentBuilder.java b/src/main/java/com/coveo/pushapiclient/DocumentBuilder.java index dd3bbd36..e4ad3385 100644 --- a/src/main/java/com/coveo/pushapiclient/DocumentBuilder.java +++ b/src/main/java/com/coveo/pushapiclient/DocumentBuilder.java @@ -2,388 +2,397 @@ import com.google.gson.Gson; import com.google.gson.JsonObject; -import org.apache.commons.codec.digest.DigestUtils; -import org.joda.time.DateTime; -import org.joda.time.format.ISODateTimeFormat; - import java.util.ArrayList; import java.util.Date; import java.util.Map; +import org.apache.commons.codec.digest.DigestUtils; +import org.joda.time.DateTime; +import org.joda.time.format.ISODateTimeFormat; -/** - * Utility class to build a {@link Document} - */ +/** Utility class to build a {@link Document} */ public class DocumentBuilder { - private static final ArrayList reservedKeynames = new ArrayList<>() {{ - add("compressedBinaryData"); - add("compressedBinaryDataFileId"); - add("parentId"); - add("fileExtension"); - add("data"); - add("permissions"); - add("documentId"); - add("orderingId"); - }}; - - private final Document document; - - /** - * @param uri the URI of the document. See {@link Document#uri} - * @param title the title of the document. See {@link Document#title} - */ - public DocumentBuilder(String uri, String title) { - this.document = new Document(); - this.document.uri = uri; - this.document.title = title; - } - - public Document getDocument() { - return this.document; - } - - /** - * Set the data of the document. See {@link Document#data} - * - * @param data - * @return - */ - public DocumentBuilder withData(String data) { - this.document.data = data; - return this; - } - - /** - * Set the date of the document. See {@link Document#date} - * - * @param date - * @return - */ - public DocumentBuilder withDate(String date) { - DateTime dt = DateTime.parse(date); - this.document.date = this.dateFormat(dt); - return this; - } - - /** - * Set the date of the document. See {@link Document#date} - * - * @param date - * @return - */ - public DocumentBuilder withDate(Long date) { - DateTime dt = new DateTime(date); - this.document.date = this.dateFormat(dt); - return this; - } - - /** - * Set the date of the document. See {@link Document#date} - * - * @param date - * @return - */ - public DocumentBuilder withDate(Date date) { - DateTime dt = new DateTime(date); - this.document.date = this.dateFormat(dt); - return this; - } - - /** - * Set the date of the document. See {@link Document#date} - * - * @param date - * @return - */ - public DocumentBuilder withDate(DateTime date) { - this.document.date = this.dateFormat(date); - return this; - } - - /** - * Set the modified date of the document. See {@link Document#modifiedDate} - * - * @param date - * @return - */ - public DocumentBuilder withModifiedDate(String date) { - DateTime dt = DateTime.parse(date); - this.document.modifiedDate = this.dateFormat(dt); - return this; - } - - /** - * Set the modified date of the document. See {@link Document#modifiedDate} - * - * @param date - * @return - */ - public DocumentBuilder withModifiedDate(Long date) { - DateTime dt = new DateTime(date); - this.document.modifiedDate = this.dateFormat(dt); - return this; - } - - /** - * Set the modified date of the document. See {@link Document#modifiedDate} - * - * @param date - * @return - */ - public DocumentBuilder withModifiedDate(DateTime date) { - this.document.modifiedDate = this.dateFormat(date); - return this; - } - - /** - * Set the modified date of the document. See {@link Document#modifiedDate} - * - * @param date - * @return - */ - public DocumentBuilder withModifiedDate(Date date) { - DateTime dt = new DateTime(date); - this.document.modifiedDate = this.dateFormat(dt); - return this; - } - - /** - * Set the permanentID of the document. See {@link Document#permanentId} - * - * @param permanentId - * @return - */ - public DocumentBuilder withPermanentId(String permanentId) { - this.document.permanentId = permanentId; - return this; - } - - /** - * Set the base64 encoded, compressed binary data of the document. See {@link Document#compressedBinaryData} - * - * @param compressedBinaryData - * @return - */ - public DocumentBuilder withCompressedBinaryData(CompressedBinaryData compressedBinaryData) { - this.document.compressedBinaryData = compressedBinaryData; - return this; - } - - /** - * Set the file container file ID for the compressed binary data of the document. See {@link Document#compressedBinaryDataFileId} - * - * @param compressedBinaryDataFileId - * @return - */ - public DocumentBuilder withCompressedBinaryDataFileId(String compressedBinaryDataFileId) { - this.document.compressedBinaryDataFileId = compressedBinaryDataFileId; - return this; - } - - /** - * Set the file extension on the document. See {@link Document#fileExtension} - * - * @param fileExtension - * @return - */ - public DocumentBuilder withFileExtension(String fileExtension) { - this.validateFileExtension(fileExtension); - this.document.fileExtension = fileExtension; - return this; - } - - /** - * Set the parentID on the document. See {@link Document#parentId} - * - * @param parentID - * @return - */ - public DocumentBuilder withParentID(String parentID) { - this.document.parentId = parentID; - return this; - } - - /** - * Set the clickableURI on the document. See {@link Document#clickableUri} - * - * @param clickableUri - * @return - */ - public DocumentBuilder withClickableUri(String clickableUri) { - this.document.clickableUri = clickableUri; - return this; - } - - /** - * Set the author on the document. See {@link Document#author} - * - * @param author - * @return - */ - public DocumentBuilder withAuthor(String author) { - this.document.author = author; - return this; - } - - /** - * Add a single metadata key and value pair on the document. See {@link Document#metadata} - * - * @param key - * @param metadataValue - * @return - */ - public DocumentBuilder withMetadataValue(String key, String metadataValue) { - this.setMetadataValue(key, metadataValue); - return this; - } - - /** - * Add a single metadata key and value pair on the document. See {@link Document#metadata} - * - * @param key - * @param metadataValue - * @return - */ - public DocumentBuilder withMetadataValue(String key, String[] metadataValue) { - this.setMetadataValue(key, metadataValue); - return this; - } - - /** - * Add a single metadata key and value pair on the document. See {@link Document#metadata} - * - * @param key - * @param metadataValue - * @return - */ - public DocumentBuilder withMetadataValue(String key, Integer metadataValue) { - this.setMetadataValue(key, metadataValue); - return this; - } - - /** - * Add a single metadata key and value pair on the document. See {@link Document#metadata} - * - * @param key - * @param metadataValue - * @return - */ - public DocumentBuilder withMetadataValue(String key, Integer[] metadataValue) { - this.setMetadataValue(key, metadataValue); - return this; - } - - /** - * Set metadata on the document. See {@link Document#metadata} - * - * @param metadata - * @return - */ - public DocumentBuilder withMetadata(Map metadata) { - metadata.forEach(this::setMetadataValue); - return this; - } - - /** - * Set allowed identities on the document. See {@link Document#permissions} - * - * @param allowedPermissions - * @return - */ - public DocumentBuilder withAllowedPermissions(SecurityIdentityBuilder allowedPermissions) { - this.document.permissions[0].allowedPermissions = allowedPermissions.build(); - return this; - } - - /** - * Set denied identities on the document. See {@link Document#permissions} - * - * @param deniedPermissions - * @return - */ - public DocumentBuilder withDeniedPermissions(SecurityIdentityBuilder deniedPermissions) { - this.document.permissions[0].deniedPermissions = deniedPermissions.build(); - return this; - } - - /** - * Set allowAnonymous for permissions on the document. See {@link Document#permissions} - * - * @param allowAnonymous - * @return - */ - public DocumentBuilder withAllowAnonymousUsers(Boolean allowAnonymous) { - this.document.permissions[0].allowAnonymous = allowAnonymous; - return this; - } - - /** - * Set the fully built out DocumentPermissions array. See {@Link Document#permissions} - * @param documentPermissions - * @return - */ - public DocumentBuilder withDocumentPermissions(DocumentPermissions[] documentPermissions) { - this.document.permissions = documentPermissions; - return this; - } - - /** - * Marshal the document into a JSON string accepted by the push API. - * - * @return - */ - public String marshal() { - return this.marshalJsonObject().toString(); - } - - /** - * Marshal the document into a JSON object accepted by the push API. - * - * @return - */ - public JsonObject marshalJsonObject() { - this.generatePermanentId(); - - JsonObject jsonDocument = new Gson().toJsonTree(this.document).getAsJsonObject(); - this.document.metadata.forEach((key, value) -> { - jsonDocument.add(key, new Gson().toJsonTree(value)); - }); - jsonDocument.remove("metadata"); - - if (this.document.compressedBinaryData != null) { - jsonDocument.addProperty("compressedBinaryData", this.document.compressedBinaryData.getData()); + private static final ArrayList reservedKeynames = + new ArrayList<>() { + { + add("compressedBinaryData"); + add("compressedBinaryDataFileId"); + add("parentId"); + add("fileExtension"); + add("data"); + add("permissions"); + add("documentId"); + add("orderingId"); } + }; + + private final Document document; + + /** + * @param uri the URI of the document. See {@link Document#uri} + * @param title the title of the document. See {@link Document#title} + */ + public DocumentBuilder(String uri, String title) { + this.document = new Document(); + this.document.uri = uri; + this.document.title = title; + } + + public Document getDocument() { + return this.document; + } + + /** + * Set the data of the document. See {@link Document#data} + * + * @param data + * @return + */ + public DocumentBuilder withData(String data) { + this.document.data = data; + return this; + } + + /** + * Set the date of the document. See {@link Document#date} + * + * @param date + * @return + */ + public DocumentBuilder withDate(String date) { + DateTime dt = DateTime.parse(date); + this.document.date = this.dateFormat(dt); + return this; + } + + /** + * Set the date of the document. See {@link Document#date} + * + * @param date + * @return + */ + public DocumentBuilder withDate(Long date) { + DateTime dt = new DateTime(date); + this.document.date = this.dateFormat(dt); + return this; + } + + /** + * Set the date of the document. See {@link Document#date} + * + * @param date + * @return + */ + public DocumentBuilder withDate(Date date) { + DateTime dt = new DateTime(date); + this.document.date = this.dateFormat(dt); + return this; + } + + /** + * Set the date of the document. See {@link Document#date} + * + * @param date + * @return + */ + public DocumentBuilder withDate(DateTime date) { + this.document.date = this.dateFormat(date); + return this; + } + + /** + * Set the modified date of the document. See {@link Document#modifiedDate} + * + * @param date + * @return + */ + public DocumentBuilder withModifiedDate(String date) { + DateTime dt = DateTime.parse(date); + this.document.modifiedDate = this.dateFormat(dt); + return this; + } + + /** + * Set the modified date of the document. See {@link Document#modifiedDate} + * + * @param date + * @return + */ + public DocumentBuilder withModifiedDate(Long date) { + DateTime dt = new DateTime(date); + this.document.modifiedDate = this.dateFormat(dt); + return this; + } + + /** + * Set the modified date of the document. See {@link Document#modifiedDate} + * + * @param date + * @return + */ + public DocumentBuilder withModifiedDate(DateTime date) { + this.document.modifiedDate = this.dateFormat(date); + return this; + } + + /** + * Set the modified date of the document. See {@link Document#modifiedDate} + * + * @param date + * @return + */ + public DocumentBuilder withModifiedDate(Date date) { + DateTime dt = new DateTime(date); + this.document.modifiedDate = this.dateFormat(dt); + return this; + } + + /** + * Set the permanentID of the document. See {@link Document#permanentId} + * + * @param permanentId + * @return + */ + public DocumentBuilder withPermanentId(String permanentId) { + this.document.permanentId = permanentId; + return this; + } + + /** + * Set the base64 encoded, compressed binary data of the document. See {@link + * Document#compressedBinaryData} + * + * @param compressedBinaryData + * @return + */ + public DocumentBuilder withCompressedBinaryData(CompressedBinaryData compressedBinaryData) { + this.document.compressedBinaryData = compressedBinaryData; + return this; + } + + /** + * Set the file container file ID for the compressed binary data of the document. See {@link + * Document#compressedBinaryDataFileId} + * + * @param compressedBinaryDataFileId + * @return + */ + public DocumentBuilder withCompressedBinaryDataFileId(String compressedBinaryDataFileId) { + this.document.compressedBinaryDataFileId = compressedBinaryDataFileId; + return this; + } + + /** + * Set the file extension on the document. See {@link Document#fileExtension} + * + * @param fileExtension + * @return + */ + public DocumentBuilder withFileExtension(String fileExtension) { + this.validateFileExtension(fileExtension); + this.document.fileExtension = fileExtension; + return this; + } + + /** + * Set the parentID on the document. See {@link Document#parentId} + * + * @param parentID + * @return + */ + public DocumentBuilder withParentID(String parentID) { + this.document.parentId = parentID; + return this; + } + + /** + * Set the clickableURI on the document. See {@link Document#clickableUri} + * + * @param clickableUri + * @return + */ + public DocumentBuilder withClickableUri(String clickableUri) { + this.document.clickableUri = clickableUri; + return this; + } + + /** + * Set the author on the document. See {@link Document#author} + * + * @param author + * @return + */ + public DocumentBuilder withAuthor(String author) { + this.document.author = author; + return this; + } + + /** + * Add a single metadata key and value pair on the document. See {@link Document#metadata} + * + * @param key + * @param metadataValue + * @return + */ + public DocumentBuilder withMetadataValue(String key, String metadataValue) { + this.setMetadataValue(key, metadataValue); + return this; + } + + /** + * Add a single metadata key and value pair on the document. See {@link Document#metadata} + * + * @param key + * @param metadataValue + * @return + */ + public DocumentBuilder withMetadataValue(String key, String[] metadataValue) { + this.setMetadataValue(key, metadataValue); + return this; + } + + /** + * Add a single metadata key and value pair on the document. See {@link Document#metadata} + * + * @param key + * @param metadataValue + * @return + */ + public DocumentBuilder withMetadataValue(String key, Integer metadataValue) { + this.setMetadataValue(key, metadataValue); + return this; + } + + /** + * Add a single metadata key and value pair on the document. See {@link Document#metadata} + * + * @param key + * @param metadataValue + * @return + */ + public DocumentBuilder withMetadataValue(String key, Integer[] metadataValue) { + this.setMetadataValue(key, metadataValue); + return this; + } + + /** + * Set metadata on the document. See {@link Document#metadata} + * + * @param metadata + * @return + */ + public DocumentBuilder withMetadata(Map metadata) { + metadata.forEach(this::setMetadataValue); + return this; + } + + /** + * Set allowed identities on the document. See {@link Document#permissions} + * + * @param allowedPermissions + * @return + */ + public DocumentBuilder withAllowedPermissions(SecurityIdentityBuilder allowedPermissions) { + this.document.permissions[0].allowedPermissions = allowedPermissions.build(); + return this; + } + + /** + * Set denied identities on the document. See {@link Document#permissions} + * + * @param deniedPermissions + * @return + */ + public DocumentBuilder withDeniedPermissions(SecurityIdentityBuilder deniedPermissions) { + this.document.permissions[0].deniedPermissions = deniedPermissions.build(); + return this; + } + + /** + * Set allowAnonymous for permissions on the document. See {@link Document#permissions} + * + * @param allowAnonymous + * @return + */ + public DocumentBuilder withAllowAnonymousUsers(Boolean allowAnonymous) { + this.document.permissions[0].allowAnonymous = allowAnonymous; + return this; + } + + /** + * Set the fully built out DocumentPermissions array. See {@Link Document#permissions} + * + * @param documentPermissions + * @return + */ + public DocumentBuilder withDocumentPermissions(DocumentPermissions[] documentPermissions) { + this.document.permissions = documentPermissions; + return this; + } + + /** + * Marshal the document into a JSON string accepted by the push API. + * + * @return + */ + public String marshal() { + return this.marshalJsonObject().toString(); + } + + /** + * Marshal the document into a JSON object accepted by the push API. + * + * @return + */ + public JsonObject marshalJsonObject() { + this.generatePermanentId(); + + JsonObject jsonDocument = new Gson().toJsonTree(this.document).getAsJsonObject(); + this.document.metadata.forEach( + (key, value) -> { + jsonDocument.add(key, new Gson().toJsonTree(value)); + }); + jsonDocument.remove("metadata"); - jsonDocument.addProperty("documentId", this.document.uri); - return jsonDocument; + if (this.document.compressedBinaryData != null) { + jsonDocument.addProperty( + "compressedBinaryData", this.document.compressedBinaryData.getData()); } - private String dateFormat(DateTime dt) { - return dt.toString(ISODateTimeFormat.dateTime()); - } + jsonDocument.addProperty("documentId", this.document.uri); + return jsonDocument; + } - private void setMetadataValue(String key, Object metadataValue) { - this.validateReservedMetadataKeyNames(key); - this.document.metadata.put(key, metadataValue); - } + private String dateFormat(DateTime dt) { + return dt.toString(ISODateTimeFormat.dateTime()); + } - private void validateFileExtension(String fileExtension) { - if (!fileExtension.startsWith(".")) { - throw new RuntimeException(String.format("%s is not a valid file extension. It should start with a leading .")); - } + private void setMetadataValue(String key, Object metadataValue) { + this.validateReservedMetadataKeyNames(key); + this.document.metadata.put(key, metadataValue); + } + + private void validateFileExtension(String fileExtension) { + if (!fileExtension.startsWith(".")) { + throw new RuntimeException( + String.format("%s is not a valid file extension. It should start with a leading .")); } + } - private void validateReservedMetadataKeyNames(String key) { - if (reservedKeynames.contains(key)) { - throw new RuntimeException(String.format("Cannot use %s as a metadata key: It is a reserved keynames. See https://docs.coveo.com/en/78/index-content/push-api-reference#json-document-reserved-key-names", key)); - } + private void validateReservedMetadataKeyNames(String key) { + if (reservedKeynames.contains(key)) { + throw new RuntimeException( + String.format( + "Cannot use %s as a metadata key: It is a reserved keynames. See https://docs.coveo.com/en/78/index-content/push-api-reference#json-document-reserved-key-names", + key)); } + } - private void generatePermanentId() { - if (this.document.permanentId == null) { - String md5 = DigestUtils.md5Hex(this.document.uri); - String sha1 = DigestUtils.sha1Hex(this.document.uri); - this.document.permanentId = md5.substring(0, 30) + sha1.substring(0, 30); - } + private void generatePermanentId() { + if (this.document.permanentId == null) { + String md5 = DigestUtils.md5Hex(this.document.uri); + String sha1 = DigestUtils.sha1Hex(this.document.uri); + this.document.permanentId = md5.substring(0, 30) + sha1.substring(0, 30); } + } } diff --git a/src/main/java/com/coveo/pushapiclient/DocumentPermissions.java b/src/main/java/com/coveo/pushapiclient/DocumentPermissions.java index 63a1c5c3..4cb5fc68 100644 --- a/src/main/java/com/coveo/pushapiclient/DocumentPermissions.java +++ b/src/main/java/com/coveo/pushapiclient/DocumentPermissions.java @@ -1,23 +1,18 @@ package com.coveo.pushapiclient; public class DocumentPermissions { - /** - * Whether to allow anonymous users in this permission set. - * Default value is false. - */ - public boolean allowAnonymous; - /** - * The list of allowed permissions for this permission set. - */ - public SecurityIdentity[] allowedPermissions; - /** - * The list of denied permissions for this permission set. - */ - public SecurityIdentity[] deniedPermissions; + /** Whether to allow anonymous users in this permission set. Default value is false. */ + public boolean allowAnonymous; - public DocumentPermissions() { - this.allowAnonymous = true; - this.allowedPermissions = new SecurityIdentity[]{}; - this.deniedPermissions = new SecurityIdentity[]{}; - } + /** The list of allowed permissions for this permission set. */ + public SecurityIdentity[] allowedPermissions; + + /** The list of denied permissions for this permission set. */ + public SecurityIdentity[] deniedPermissions; + + public DocumentPermissions() { + this.allowAnonymous = true; + this.allowedPermissions = new SecurityIdentity[] {}; + this.deniedPermissions = new SecurityIdentity[] {}; + } } diff --git a/src/main/java/com/coveo/pushapiclient/DocumentUploadQueue.java b/src/main/java/com/coveo/pushapiclient/DocumentUploadQueue.java index 79014137..9aaa5a83 100644 --- a/src/main/java/com/coveo/pushapiclient/DocumentUploadQueue.java +++ b/src/main/java/com/coveo/pushapiclient/DocumentUploadQueue.java @@ -3,103 +3,97 @@ import java.io.IOException; import java.util.ArrayList; -/** - * Represents a queue for uploading documents using a specified upload strategy - */ +/** Represents a queue for uploading documents using a specified upload strategy */ class DocumentUploadQueue { - private final UploadStrategy uploader; - private final int maxQueueSize = 5 * 1024 * 1024; - private ArrayList documentToAddList; - private ArrayList documentToDeleteList; - private int size; + private final UploadStrategy uploader; + private final int maxQueueSize = 5 * 1024 * 1024; + private ArrayList documentToAddList; + private ArrayList documentToDeleteList; + private int size; - /** - * Constructs a new DocumentUploadQueue object with a default maximum queue size - * limit of 5MB. - * - * @param uploader The upload strategy to be used for document uploads. - */ - public DocumentUploadQueue(UploadStrategy uploader) { - this.documentToAddList = new ArrayList<>(); - this.documentToDeleteList = new ArrayList<>(); - this.uploader = uploader; - } + /** + * Constructs a new DocumentUploadQueue object with a default maximum queue size limit of 5MB. + * + * @param uploader The upload strategy to be used for document uploads. + */ + public DocumentUploadQueue(UploadStrategy uploader) { + this.documentToAddList = new ArrayList<>(); + this.documentToDeleteList = new ArrayList<>(); + this.uploader = uploader; + } - /** - * Flushes the accumulated documents by applying the upload strategy. - * - * @throws IOException If an I/O error occurs during the upload. - * @throws InterruptedException If the upload process is interrupted. - */ - public void flush() throws IOException, InterruptedException { - if (this.isEmpty()) { - return; - } - BatchUpdate batch = this.getBatch(); - // TODO: LENS-871: support concurrent requests - this.uploader.apply(batch); - this.size = 0; - this.documentToAddList.clear(); - this.documentToDeleteList.clear(); + /** + * Flushes the accumulated documents by applying the upload strategy. + * + * @throws IOException If an I/O error occurs during the upload. + * @throws InterruptedException If the upload process is interrupted. + */ + public void flush() throws IOException, InterruptedException { + if (this.isEmpty()) { + return; } + BatchUpdate batch = this.getBatch(); + // TODO: LENS-871: support concurrent requests + this.uploader.apply(batch); + this.size = 0; + this.documentToAddList.clear(); + this.documentToDeleteList.clear(); + } - /** - * Adds a {@link DocumentBuilder} to the upload queue and flushes the queue if - * it exceeds the maximum content length. - * See {@link DocumentUploadQueue#flush}. - * - * @param document The document to be added to the index. - * @throws IOException If an I/O error occurs during the upload. - * @throws InterruptedException If the upload process is interrupted. - */ - public void add(DocumentBuilder document) throws IOException, InterruptedException { - if (document == null) { - return; - } - - final int sizeOfDoc = document.marshal().getBytes().length; - if (this.size + sizeOfDoc >= this.maxQueueSize) { - this.flush(); - } - if (document != null) { - documentToAddList.add(document); - this.size += sizeOfDoc; - } + /** + * Adds a {@link DocumentBuilder} to the upload queue and flushes the queue if it exceeds the + * maximum content length. See {@link DocumentUploadQueue#flush}. + * + * @param document The document to be added to the index. + * @throws IOException If an I/O error occurs during the upload. + * @throws InterruptedException If the upload process is interrupted. + */ + public void add(DocumentBuilder document) throws IOException, InterruptedException { + if (document == null) { + return; } - /** - * Adds a {@link DeleteDocument} to the upload queue and flushes the queue if - * it exceeds the maximum content length. - * See {@link DocumentUploadQueue#flush}. - * - * @param document The document to be delete from the index. - * @throws IOException If an I/O error occurs during the upload. - * @throws InterruptedException If the upload process is interrupted. - */ - public void add(DeleteDocument document) throws IOException, InterruptedException { - if (document == null) { - return; - } - - final int sizeOfDoc = document.marshalJsonObject().toString().getBytes().length; - if (this.size + sizeOfDoc >= this.maxQueueSize) { - this.flush(); - } - if (document != null) { - documentToDeleteList.add(document); - this.size += sizeOfDoc; - } + final int sizeOfDoc = document.marshal().getBytes().length; + if (this.size + sizeOfDoc >= this.maxQueueSize) { + this.flush(); } + if (document != null) { + documentToAddList.add(document); + this.size += sizeOfDoc; + } + } - public BatchUpdate getBatch() { - return new BatchUpdate( - new ArrayList(this.documentToAddList), - new ArrayList(this.documentToDeleteList)); + /** + * Adds a {@link DeleteDocument} to the upload queue and flushes the queue if it exceeds the + * maximum content length. See {@link DocumentUploadQueue#flush}. + * + * @param document The document to be delete from the index. + * @throws IOException If an I/O error occurs during the upload. + * @throws InterruptedException If the upload process is interrupted. + */ + public void add(DeleteDocument document) throws IOException, InterruptedException { + if (document == null) { + return; } - public boolean isEmpty() { - // TODO: LENS-843: include partial document updates - return documentToAddList.isEmpty() && documentToDeleteList.isEmpty(); + final int sizeOfDoc = document.marshalJsonObject().toString().getBytes().length; + if (this.size + sizeOfDoc >= this.maxQueueSize) { + this.flush(); + } + if (document != null) { + documentToDeleteList.add(document); + this.size += sizeOfDoc; } + } + + public BatchUpdate getBatch() { + return new BatchUpdate( + new ArrayList(this.documentToAddList), + new ArrayList(this.documentToDeleteList)); + } + public boolean isEmpty() { + // TODO: LENS-843: include partial document updates + return documentToAddList.isEmpty() && documentToDeleteList.isEmpty(); + } } diff --git a/src/main/java/com/coveo/pushapiclient/Environment.java b/src/main/java/com/coveo/pushapiclient/Environment.java index b42e0176..fb175c7f 100644 --- a/src/main/java/com/coveo/pushapiclient/Environment.java +++ b/src/main/java/com/coveo/pushapiclient/Environment.java @@ -1,21 +1,19 @@ package com.coveo.pushapiclient; -/** - * Available environments to use as the host for the PushAPI. - */ +/** Available environments to use as the host for the PushAPI. */ public enum Environment { - PRODUCTION( "prod"), - HIPAA("hipaa"), - DEVELOPMENT("dev"), - STAGING("stg"); + PRODUCTION("prod"), + HIPAA("hipaa"), + DEVELOPMENT("dev"), + STAGING("stg"); - private String value; + private String value; - Environment(String value) { - this.value = value; - } + Environment(String value) { + this.value = value; + } - public String getValue() { - return this.value; - } + public String getValue() { + return this.value; + } } diff --git a/src/main/java/com/coveo/pushapiclient/FileContainer.java b/src/main/java/com/coveo/pushapiclient/FileContainer.java index 2d67b8db..57920c7b 100644 --- a/src/main/java/com/coveo/pushapiclient/FileContainer.java +++ b/src/main/java/com/coveo/pushapiclient/FileContainer.java @@ -2,11 +2,9 @@ import java.util.Map; -/** - * See [Creating a FileContainer](https://docs.coveo.com/en/43) - */ +/** See [Creating a FileContainer](https://docs.coveo.com/en/43) */ public class FileContainer { - public String uploadUri; - public String fileId; - public Map requiredHeaders; + public String uploadUri; + public String fileId; + public Map requiredHeaders; } diff --git a/src/main/java/com/coveo/pushapiclient/GroupSecurityIdentityBuilder.java b/src/main/java/com/coveo/pushapiclient/GroupSecurityIdentityBuilder.java index 6a2077a0..0beb6dc7 100644 --- a/src/main/java/com/coveo/pushapiclient/GroupSecurityIdentityBuilder.java +++ b/src/main/java/com/coveo/pushapiclient/GroupSecurityIdentityBuilder.java @@ -5,63 +5,70 @@ /** * Build a security identity of type `GROUP`. - *

- * Typically used in conjunction with {@link DocumentBuilder#withAllowedPermissions} or {@link DocumentBuilder#withDeniedPermissions}. - *

- * See {@link SecurityIdentity}. + * + *

Typically used in conjunction with {@link DocumentBuilder#withAllowedPermissions} or {@link + * DocumentBuilder#withDeniedPermissions}. + * + *

See {@link SecurityIdentity}. */ public class GroupSecurityIdentityBuilder implements SecurityIdentityBuilder { - private final String[] identities; - private final String securityProvider; + private final String[] identities; + private final String securityProvider; - public GroupSecurityIdentityBuilder(String[] identities, String securityProvider) { - this.identities = identities; - this.securityProvider = securityProvider; - } + public GroupSecurityIdentityBuilder(String[] identities, String securityProvider) { + this.identities = identities; + this.securityProvider = securityProvider; + } - /** - * Construct a GroupSecurityIdentityBuilder with a single identity - * - * @param identity - * @param securityProvider - */ - public GroupSecurityIdentityBuilder(String identity, String securityProvider) { - this(new String[]{identity}, securityProvider); - } + /** + * Construct a GroupSecurityIdentityBuilder with a single identity + * + * @param identity + * @param securityProvider + */ + public GroupSecurityIdentityBuilder(String identity, String securityProvider) { + this(new String[] {identity}, securityProvider); + } - public SecurityIdentity[] build() { - return new AnySecurityIdentityBuilder(this.identities, SecurityIdentityType.GROUP, this.securityProvider).build(); - } + public SecurityIdentity[] build() { + return new AnySecurityIdentityBuilder( + this.identities, SecurityIdentityType.GROUP, this.securityProvider) + .build(); + } - public String[] getIdentities() { - return identities; - } + public String[] getIdentities() { + return identities; + } - public String getSecurityProvider() { - return securityProvider; - } + public String getSecurityProvider() { + return securityProvider; + } - @Override - public String toString() { - return "GroupSecurityIdentityBuilder[" + - "identities=" + Arrays.toString(identities) + - ", securityProvider='" + securityProvider + '\'' + - ']'; - } + @Override + public String toString() { + return "GroupSecurityIdentityBuilder[" + + "identities=" + + Arrays.toString(identities) + + ", securityProvider='" + + securityProvider + + '\'' + + ']'; + } - @Override - public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null || getClass() != obj.getClass()) return false; - GroupSecurityIdentityBuilder that = (GroupSecurityIdentityBuilder) obj; - return Arrays.equals(identities, that.identities) && Objects.equals(securityProvider, that.securityProvider); - } + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null || getClass() != obj.getClass()) return false; + GroupSecurityIdentityBuilder that = (GroupSecurityIdentityBuilder) obj; + return Arrays.equals(identities, that.identities) + && Objects.equals(securityProvider, that.securityProvider); + } - @Override - public int hashCode() { - int result = Objects.hash(securityProvider); - result = 31 * result + Arrays.hashCode(identities); - return result; - } + @Override + public int hashCode() { + int result = Objects.hash(securityProvider); + result = 31 * result + Arrays.hashCode(identities); + return result; + } } diff --git a/src/main/java/com/coveo/pushapiclient/IdentityModel.java b/src/main/java/com/coveo/pushapiclient/IdentityModel.java index 35ec0ddd..42eebd88 100644 --- a/src/main/java/com/coveo/pushapiclient/IdentityModel.java +++ b/src/main/java/com/coveo/pushapiclient/IdentityModel.java @@ -3,13 +3,13 @@ import java.util.Map; public class IdentityModel { - public final Map additionalInfo; - public final String name; - public final SecurityIdentityType type; + public final Map additionalInfo; + public final String name; + public final SecurityIdentityType type; - public IdentityModel(String name, SecurityIdentityType type, Map additionalInfo) { - this.name = name; - this.type = type; - this.additionalInfo = additionalInfo; - } + public IdentityModel(String name, SecurityIdentityType type, Map additionalInfo) { + this.name = name; + this.type = type; + this.additionalInfo = additionalInfo; + } } diff --git a/src/main/java/com/coveo/pushapiclient/PlatformClient.java b/src/main/java/com/coveo/pushapiclient/PlatformClient.java index aa5e2035..ba28dc78 100644 --- a/src/main/java/com/coveo/pushapiclient/PlatformClient.java +++ b/src/main/java/com/coveo/pushapiclient/PlatformClient.java @@ -2,7 +2,6 @@ import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; - import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; @@ -12,489 +11,583 @@ import java.util.HashMap; import java.util.stream.Stream; -/** - * PlatformClient handles network requests to the Coveo platform - */ +/** PlatformClient handles network requests to the Coveo platform */ public class PlatformClient { - private final String apiKey; - private final String organizationId; - private final HttpClient httpClient; - private final PlatformUrl platformUrl; - - /** - * Construct a PlatformClient - * - * @param apiKey An apiKey capable of pushing documents and managing sources in a Coveo organization. See [Manage API Keys](https://docs.coveo.com/en/1718). - * @param organizationId The Coveo Organization identifier. - */ - public PlatformClient(String apiKey, String organizationId) { - this(apiKey, organizationId, new PlatformUrlBuilder().build()); - } - - /** - * Construct a PlatformClient - * - * @param apiKey An apiKey capable of pushing documents and managing sources in a Coveo organization. See [Manage API Keys](https://docs.coveo.com/en/1718). - * @param organizationId The Coveo Organization identifier. - * @param platformUrl The PlatformUrl. - */ - public PlatformClient(String apiKey, String organizationId, PlatformUrl platformUrl) { - this.apiKey = apiKey; - this.organizationId = organizationId; - this.httpClient = HttpClient.newHttpClient(); - this.platformUrl = platformUrl; - } - - /** - * Construct a PlatformClient - * - * @param apiKey An apiKey capable of pushing documents and managing sources in a Coveo organization. See [Manage API Keys](https://docs.coveo.com/en/1718). - * @param organizationId The Coveo Organization identifier. - * @param httpClient The HttpClient. - */ - public PlatformClient(String apiKey, String organizationId, HttpClient httpClient) { - this.apiKey = apiKey; - this.organizationId = organizationId; - this.httpClient = httpClient; - this.platformUrl = new PlatformUrlBuilder().build(); - } - - - /** - * @deprecated Please now use PlatformUrl to define your Platform environment - * @see PlatformUrl Construct a PlatformUrl - * - * @param apiKey An apiKey capable of pushing documents and managing sources in a Coveo organization. See [Manage API Keys](https://docs.coveo.com/en/1718). - * @param organizationId The Coveo Organization identifier. - * @param environment The Environment to be used. - */ - @Deprecated - public PlatformClient(String apiKey, String organizationId, Environment environment) { - this.apiKey = apiKey; - this.organizationId = organizationId; - this.httpClient = HttpClient.newHttpClient(); - this.platformUrl = new PlatformUrlBuilder() - .withEnvironment(environment) - .build(); - } - - /** - * Create a new push source - * @deprecated - * Please use {@link PlatformClient#createSource(String, SourceType, SourceVisibility)} instead - * - * @param name - * @param sourceVisibility - * @return - * @throws IOException - * @throws InterruptedException - */ - @Deprecated - public HttpResponse createSource(String name, SourceVisibility sourceVisibility) throws IOException, InterruptedException { - return createSource(name,SourceType.PUSH,sourceVisibility); - } - - /** - * Create a new source - * - * @param name The name of the source to create - * @param sourceType The type of the source to create - * @param sourceVisibility The security option that should be applied to the content of the source. See [Content Security](https://docs.coveo.com/en/1779). - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse createSource(String name, final SourceType sourceType, SourceVisibility sourceVisibility) throws IOException, InterruptedException { - String[] headers = this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); - - String json = this.toJSON(new HashMap<>() {{ - put("sourceType", sourceType.toString()); - put("pushEnabled", sourceType.isPushEnabled()); - put("streamEnabled", sourceType.isStreamEnabled()); - put("name", name); - put("sourceVisibility", sourceVisibility); - }}); - - HttpRequest request = HttpRequest.newBuilder() - .headers(headers) - .POST(HttpRequest.BodyPublishers.ofString(json)) - .uri(URI.create(this.getBaseSourceURL())) - .build(); - - return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - } - - /** - * Create or update a security identity. See [Adding a Single Security Identity](https://docs.coveo.com/en/167) and [Security Identity Models](https://docs.coveo.com/en/139). - * - * @param securityProviderId - * @param securityIdentityModel - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse createOrUpdateSecurityIdentity(String securityProviderId, SecurityIdentityModel securityIdentityModel) throws IOException, InterruptedException { - String[] headers = this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); - URI uri = URI.create(this.getBaseProviderURL(securityProviderId) + "/permissions"); - - String json = new Gson().toJson(securityIdentityModel); - - HttpRequest request = HttpRequest.newBuilder() - .headers(headers) - .PUT(HttpRequest.BodyPublishers.ofString(json)) - .uri(uri) - .build(); - - return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - } - - /** - * Create or update a security identity alias. See [Adding a Single Alias](https://docs.coveo.com/en/142) and [User Alias Definition Examples](https://docs.coveo.com/en/46). - * - * @param securityProviderId - * @param securityIdentityAlias - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse createOrUpdateSecurityIdentityAlias(String securityProviderId, SecurityIdentityAliasModel securityIdentityAlias) throws IOException, InterruptedException { - String[] headers = this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); - URI uri = URI.create(this.getBaseProviderURL(securityProviderId) + "/mappings"); - - String json = new Gson().toJson(securityIdentityAlias); - - HttpRequest request = HttpRequest.newBuilder() - .headers(headers) - .PUT(HttpRequest.BodyPublishers.ofString(json)) - .uri(uri) - .build(); - - return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - } - - /** - * Delete a security identity. See [Disabling a Single Security Identity](https://docs.coveo.com/en/84). - * - * @param securityProviderId - * @param securityIdentityToDelete - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse deleteSecurityIdentity(String securityProviderId, SecurityIdentityDelete securityIdentityToDelete) throws IOException, InterruptedException { - String[] headers = this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); - URI uri = URI.create(this.getBaseProviderURL(securityProviderId) + "/permissions"); - - String json = new Gson().toJson(securityIdentityToDelete); - - HttpRequest request = HttpRequest.newBuilder() - .headers(headers) - .method("DELETE", HttpRequest.BodyPublishers.ofString(json)) - .uri(uri) - .build(); - - return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - } - - /** - * Delete old security identities. See [Disabling Old Security Identities](https://docs.coveo.com/en/33). - * - * @param securityProviderId - * @param batchDelete - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse deleteOldSecurityIdentities(String securityProviderId, SecurityIdentityDeleteOptions batchDelete) throws IOException, InterruptedException { - String[] headers = this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); - URI uri = URI.create(this.getBaseProviderURL(securityProviderId) + String.format("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/permissions/olderthan?queueDelay=%s%s", batchDelete.getQueueDelay(), appendOrderingId(batchDelete.getOrderingId()))); - - HttpRequest request = HttpRequest.newBuilder() - .headers(headers) - .DELETE() - .uri(uri) - .build(); - - return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - } - - /** - * Returns the orderingId for the query string only when a valid orderingId is available. - * - * @param orderingId - * @return - */ - public String appendOrderingId(long orderingId) { - if (orderingId > 0) { - return String.format("&orderingId=%s", orderingId); - } - return ""; - } - - /** - * Manage batches of security identities. See [Manage Batches of Security Identities](https://docs.coveo.com/en/55). - * - * @param securityProviderId - * @param batchConfig - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse manageSecurityIdentities(String securityProviderId, SecurityIdentityBatchConfig batchConfig) throws IOException, InterruptedException { - String[] headers = this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); - URI uri = URI.create(this.getBaseProviderURL(securityProviderId) + String.format("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/permissions/batch?fileId=%s%s", batchConfig.getFileId(), appendOrderingId(batchConfig.getOrderingId()))); - - HttpRequest request = HttpRequest.newBuilder() - .headers(headers) - .PUT(HttpRequest.BodyPublishers.noBody()) - .uri(uri) - .build(); - - return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - } - - /** - * Adds or updates an individual item in a push source. See [Adding a Single Item in a Push Source](https://docs.coveo.com/en/133). - * - * @param sourceId - * @param documentJSON - * @param documentId - * @param compressionType - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse pushDocument(String sourceId, String documentJSON, String documentId, CompressionType compressionType) throws IOException, InterruptedException { - String[] headers = this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); - URI uri = URI.create(this.getBasePushURL() + String.format("/sources/%s/documents?documentId=%s&compressionType=%s", sourceId, documentId, compressionType.toString())); - - HttpRequest request = HttpRequest.newBuilder() - .headers(headers) - .PUT(HttpRequest.BodyPublishers.ofString(documentJSON)) - .uri(uri) - .build(); - - return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - } - - /** - * Deletes a specific item from a Push source. Optionally, the child items of that item can also be deleted. See [Deleting an Item in a Push Source](https://docs.coveo.com/en/171). - * - * @param sourceId - * @param documentId - * @param deleteChildren - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse deleteDocument(String sourceId, String documentId, Boolean deleteChildren) throws IOException, InterruptedException { - String[] headers = this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); - URI uri = URI.create(this.getBasePushURL() + String.format("/sources/%s/documents?documentId=%s&deleteChildren=%s", sourceId, documentId, deleteChildren)); - - HttpRequest request = HttpRequest.newBuilder() - .headers(headers) - .DELETE() - .uri(uri) - .build(); - - return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - } - - public HttpResponse openStream(String sourceId) throws IOException, InterruptedException { - String[] headers = this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); - // TODO: LENS-875: standardize string manipulation - URI uri = URI.create(this.getBasePushURL() + String.format("/sources/%s/stream/open", sourceId)); - - // TODO: LENS-876: reduce code duplication - HttpRequest request = HttpRequest.newBuilder() - .headers(headers) - .uri(uri) - .POST(HttpRequest.BodyPublishers.ofString("")) - .build(); - - return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - } - - public HttpResponse closeStream(String sourceId, String streamId) throws IOException, InterruptedException { - String[] headers = this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); - URI uri = URI.create(this.getBasePushURL() + String.format("/sources/%s/stream/%s/close", sourceId, streamId)); - - HttpRequest request = HttpRequest.newBuilder() - .headers(headers) - .uri(uri) - .POST(HttpRequest.BodyPublishers.ofString("")) - .build(); - - return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - } - - public HttpResponse requireStreamChunk(String sourceId, String streamId) throws IOException, InterruptedException { - String[] headers = this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); - URI uri = URI.create(this.getBasePushURL() + String.format("/sources/%s/stream/%s/chunk", sourceId, streamId)); - - HttpRequest request = HttpRequest.newBuilder() - .headers(headers) - .uri(uri) - .POST(HttpRequest.BodyPublishers.ofString("")) - .build(); - - return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - } - - /** - * Create a file container. See [Creating a File Container](https://docs.coveo.com/en/43). - * - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse createFileContainer() throws IOException, InterruptedException { - String[] headers = this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); - URI uri = URI.create(this.getBasePushURL() + "/files"); - - HttpRequest request = HttpRequest.newBuilder() - .headers(headers) - .uri(uri) - .POST(HttpRequest.BodyPublishers.ofString("")) - .build(); - - return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - } - - /** - * Update the status of a Push source. See [Updating the Status of a Push Source](https://docs.coveo.com/en/35). - * - * @param status - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse updateSourceStatus(String sourceId, PushAPIStatus status) throws IOException, InterruptedException { - String[] headers = this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); - URI uri = URI.create(this.getBasePushURL() + String.format("/sources/%s/status?statusType=%s", sourceId, status.toString())); - - HttpRequest request = HttpRequest.newBuilder() - .headers(headers) - .uri(uri) - .POST(HttpRequest.BodyPublishers.ofString("")) - .build(); - - return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - } - - /** - * Upload content update into a file container. See [Upload the Content Update into the File Container](https://docs.coveo.com/en/90/index-content/manage-batches-of-items-in-a-push-source#step-2-upload-the-content-update-into-the-file-container). - * - * @param fileContainer - * @param batchUpdateJson - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse uploadContentToFileContainer(FileContainer fileContainer, String batchUpdateJson) throws IOException, InterruptedException { - String[] headers = fileContainer.requiredHeaders.entrySet() - .stream() - .flatMap(entry -> Stream.of(entry.getKey(), entry.getValue())) - .toArray(String[]::new); - URI uri = URI.create(fileContainer.uploadUri); - - - HttpRequest request = HttpRequest.newBuilder() - .headers(headers) - .uri(uri) - .PUT(HttpRequest.BodyPublishers.ofString(batchUpdateJson)) - .build(); - - return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - } - - /** - * Push a file container into a push source. See [Push the File Container into a Push Source](https://docs.coveo.com/en/90/index-content/manage-batches-of-items-in-a-push-source#step-3-push-the-file-container-into-a-push-source). - * - * @param sourceId - * @param fileContainer - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse pushFileContainerContent(String sourceId, FileContainer fileContainer) throws IOException, InterruptedException { - String[] headers = this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); - URI uri = URI.create(this.getBasePushURL() + String.format("/sources/%s/documents/batch?fileId=%s", sourceId, fileContainer.fileId)); - - HttpRequest request = HttpRequest.newBuilder() - .headers(headers) - .uri(uri) - .PUT(HttpRequest.BodyPublishers.ofString("")) - .build(); - - return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - } - - /** - * Push a binary to a File Container. See [Upload the Item Data Into the File Container](https://docs.coveo.com/en/69#step-2-upload-the-item-data-into-the-file-container) - * - * @param fileContainer - * @param fileAsBytes - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse pushBinaryToFileContainer(FileContainer fileContainer, byte[] fileAsBytes) throws IOException, InterruptedException { - String[] headers = this.getHeaders(this.getAes256Header(), this.getContentTypeApplicationOctetStreamHeader()); - URI uri = URI.create(fileContainer.uploadUri); - - HttpRequest request = HttpRequest.newBuilder() - .headers(headers) - .uri(uri) - .PUT(HttpRequest.BodyPublishers.ofByteArray(fileAsBytes)) - .build(); - - return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - } - - private String getBaseSourceURL() { - return String.format("%s/sources", this.getBasePlatformURL()); - } - - private String getBasePlatformURL() { - return String.format("%s/rest/organizations/%s", this.platformUrl.getPlatformUrl(),this.organizationId); - } - - private String getBasePushURL() { - return String.format("%s/push/v1/organizations/%s", this.platformUrl.getApiUrl(), this.organizationId); - } - - private String getBaseProviderURL(String providerId) { - return String.format("%s/providers/%s", this.getBasePushURL(), providerId); - } - - private String[] getHeaders(String[]... headers) { - String[] out = new String[]{}; - for (String[] header : headers) { - out = Stream.concat(Arrays.stream(out), Arrays.stream(header)) - .toArray(String[]::new); - } - return out; - } - - private String[] getAuthorizationHeader() { - return new String[]{"Authorization", String.format("Bearer %s", this.apiKey)}; - } - - private String[] getContentTypeApplicationJSONHeader() { - return new String[]{"Content-Type", "application/json", "Accept", "application/json"}; - } - - private String[] getAes256Header() { - return new String[]{"x-amz-server-side-encryption", "AES256"}; - } - - private String[] getContentTypeApplicationOctetStreamHeader() { - return new String[]{"Content-Type", "application/octet-stream"}; - } - - private String toJSON(HashMap hashMap) { - return new Gson().toJson(hashMap, new TypeToken>() { - }.getType()); - } + private final String apiKey; + private final String organizationId; + private final HttpClient httpClient; + private final PlatformUrl platformUrl; + + /** + * Construct a PlatformClient + * + * @param apiKey An apiKey capable of pushing documents and managing sources in a Coveo + * organization. See [Manage API Keys](https://docs.coveo.com/en/1718). + * @param organizationId The Coveo Organization identifier. + */ + public PlatformClient(String apiKey, String organizationId) { + this(apiKey, organizationId, new PlatformUrlBuilder().build()); + } + + /** + * Construct a PlatformClient + * + * @param apiKey An apiKey capable of pushing documents and managing sources in a Coveo + * organization. See [Manage API Keys](https://docs.coveo.com/en/1718). + * @param organizationId The Coveo Organization identifier. + * @param platformUrl The PlatformUrl. + */ + public PlatformClient(String apiKey, String organizationId, PlatformUrl platformUrl) { + this.apiKey = apiKey; + this.organizationId = organizationId; + this.httpClient = HttpClient.newHttpClient(); + this.platformUrl = platformUrl; + } + + /** + * Construct a PlatformClient + * + * @param apiKey An apiKey capable of pushing documents and managing sources in a Coveo + * organization. See [Manage API Keys](https://docs.coveo.com/en/1718). + * @param organizationId The Coveo Organization identifier. + * @param httpClient The HttpClient. + */ + public PlatformClient(String apiKey, String organizationId, HttpClient httpClient) { + this.apiKey = apiKey; + this.organizationId = organizationId; + this.httpClient = httpClient; + this.platformUrl = new PlatformUrlBuilder().build(); + } + + /** + * @deprecated Please now use PlatformUrl to define your Platform environment + * @see PlatformUrl Construct a PlatformUrl + * @param apiKey An apiKey capable of pushing documents and managing sources in a Coveo + * organization. See [Manage API Keys](https://docs.coveo.com/en/1718). + * @param organizationId The Coveo Organization identifier. + * @param environment The Environment to be used. + */ + @Deprecated + public PlatformClient(String apiKey, String organizationId, Environment environment) { + this.apiKey = apiKey; + this.organizationId = organizationId; + this.httpClient = HttpClient.newHttpClient(); + this.platformUrl = new PlatformUrlBuilder().withEnvironment(environment).build(); + } + + /** + * Create a new push source + * + * @deprecated Please use {@link PlatformClient#createSource(String, SourceType, + * SourceVisibility)} instead + * @param name + * @param sourceVisibility + * @return + * @throws IOException + * @throws InterruptedException + */ + @Deprecated + public HttpResponse createSource(String name, SourceVisibility sourceVisibility) + throws IOException, InterruptedException { + return createSource(name, SourceType.PUSH, sourceVisibility); + } + + /** + * Create a new source + * + * @param name The name of the source to create + * @param sourceType The type of the source to create + * @param sourceVisibility The security option that should be applied to the content of the + * source. See [Content Security](https://docs.coveo.com/en/1779). + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse createSource( + String name, final SourceType sourceType, SourceVisibility sourceVisibility) + throws IOException, InterruptedException { + String[] headers = + this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); + + String json = + this.toJSON( + new HashMap<>() { + { + put("sourceType", sourceType.toString()); + put("pushEnabled", sourceType.isPushEnabled()); + put("streamEnabled", sourceType.isStreamEnabled()); + put("name", name); + put("sourceVisibility", sourceVisibility); + } + }); + + HttpRequest request = + HttpRequest.newBuilder() + .headers(headers) + .POST(HttpRequest.BodyPublishers.ofString(json)) + .uri(URI.create(this.getBaseSourceURL())) + .build(); + + return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + } + + /** + * Create or update a security identity. See [Adding a Single Security + * Identity](https://docs.coveo.com/en/167) and [Security Identity + * Models](https://docs.coveo.com/en/139). + * + * @param securityProviderId + * @param securityIdentityModel + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse createOrUpdateSecurityIdentity( + String securityProviderId, SecurityIdentityModel securityIdentityModel) + throws IOException, InterruptedException { + String[] headers = + this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); + URI uri = URI.create(this.getBaseProviderURL(securityProviderId) + "/permissions"); + + String json = new Gson().toJson(securityIdentityModel); + + HttpRequest request = + HttpRequest.newBuilder() + .headers(headers) + .PUT(HttpRequest.BodyPublishers.ofString(json)) + .uri(uri) + .build(); + + return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + } + + /** + * Create or update a security identity alias. See [Adding a Single + * Alias](https://docs.coveo.com/en/142) and [User Alias Definition + * Examples](https://docs.coveo.com/en/46). + * + * @param securityProviderId + * @param securityIdentityAlias + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse createOrUpdateSecurityIdentityAlias( + String securityProviderId, SecurityIdentityAliasModel securityIdentityAlias) + throws IOException, InterruptedException { + String[] headers = + this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); + URI uri = URI.create(this.getBaseProviderURL(securityProviderId) + "/mappings"); + + String json = new Gson().toJson(securityIdentityAlias); + + HttpRequest request = + HttpRequest.newBuilder() + .headers(headers) + .PUT(HttpRequest.BodyPublishers.ofString(json)) + .uri(uri) + .build(); + + return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + } + + /** + * Delete a security identity. See [Disabling a Single Security + * Identity](https://docs.coveo.com/en/84). + * + * @param securityProviderId + * @param securityIdentityToDelete + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse deleteSecurityIdentity( + String securityProviderId, SecurityIdentityDelete securityIdentityToDelete) + throws IOException, InterruptedException { + String[] headers = + this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); + URI uri = URI.create(this.getBaseProviderURL(securityProviderId) + "/permissions"); + + String json = new Gson().toJson(securityIdentityToDelete); + + HttpRequest request = + HttpRequest.newBuilder() + .headers(headers) + .method("DELETE", HttpRequest.BodyPublishers.ofString(json)) + .uri(uri) + .build(); + + return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + } + + /** + * Delete old security identities. See [Disabling Old Security + * Identities](https://docs.coveo.com/en/33). + * + * @param securityProviderId + * @param batchDelete + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse deleteOldSecurityIdentities( + String securityProviderId, SecurityIdentityDeleteOptions batchDelete) + throws IOException, InterruptedException { + String[] headers = + this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); + URI uri = + URI.create( + this.getBaseProviderURL(securityProviderId) + + String.format( + "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/permissions/olderthan?queueDelay=%s%s", + batchDelete.getQueueDelay(), appendOrderingId(batchDelete.getOrderingId()))); + + HttpRequest request = HttpRequest.newBuilder().headers(headers).DELETE().uri(uri).build(); + + return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + } + + /** + * Returns the orderingId for the query string only when a valid orderingId is available. + * + * @param orderingId + * @return + */ + public String appendOrderingId(long orderingId) { + if (orderingId > 0) { + return String.format("&orderingId=%s", orderingId); + } + return ""; + } + + /** + * Manage batches of security identities. See [Manage Batches of Security + * Identities](https://docs.coveo.com/en/55). + * + * @param securityProviderId + * @param batchConfig + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse manageSecurityIdentities( + String securityProviderId, SecurityIdentityBatchConfig batchConfig) + throws IOException, InterruptedException { + String[] headers = + this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); + URI uri = + URI.create( + this.getBaseProviderURL(securityProviderId) + + String.format( + "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/permissions/batch?fileId=%s%s", + batchConfig.getFileId(), appendOrderingId(batchConfig.getOrderingId()))); + + HttpRequest request = + HttpRequest.newBuilder() + .headers(headers) + .PUT(HttpRequest.BodyPublishers.noBody()) + .uri(uri) + .build(); + + return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + } + + /** + * Adds or updates an individual item in a push source. See [Adding a Single Item in a Push + * Source](https://docs.coveo.com/en/133). + * + * @param sourceId + * @param documentJSON + * @param documentId + * @param compressionType + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse pushDocument( + String sourceId, String documentJSON, String documentId, CompressionType compressionType) + throws IOException, InterruptedException { + String[] headers = + this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); + URI uri = + URI.create( + this.getBasePushURL() + + String.format( + "/sources/%s/documents?documentId=%s&compressionType=%s", + sourceId, documentId, compressionType.toString())); + + HttpRequest request = + HttpRequest.newBuilder() + .headers(headers) + .PUT(HttpRequest.BodyPublishers.ofString(documentJSON)) + .uri(uri) + .build(); + + return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + } + + /** + * Deletes a specific item from a Push source. Optionally, the child items of that item can also + * be deleted. See [Deleting an Item in a Push Source](https://docs.coveo.com/en/171). + * + * @param sourceId + * @param documentId + * @param deleteChildren + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse deleteDocument( + String sourceId, String documentId, Boolean deleteChildren) + throws IOException, InterruptedException { + String[] headers = + this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); + URI uri = + URI.create( + this.getBasePushURL() + + String.format( + "/sources/%s/documents?documentId=%s&deleteChildren=%s", + sourceId, documentId, deleteChildren)); + + HttpRequest request = HttpRequest.newBuilder().headers(headers).DELETE().uri(uri).build(); + + return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + } + + public HttpResponse openStream(String sourceId) throws IOException, InterruptedException { + String[] headers = + this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); + // TODO: LENS-875: standardize string manipulation + URI uri = + URI.create(this.getBasePushURL() + String.format("/sources/%s/stream/open", sourceId)); + + // TODO: LENS-876: reduce code duplication + HttpRequest request = + HttpRequest.newBuilder() + .headers(headers) + .uri(uri) + .POST(HttpRequest.BodyPublishers.ofString("")) + .build(); + + return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + } + + public HttpResponse closeStream(String sourceId, String streamId) + throws IOException, InterruptedException { + String[] headers = + this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); + URI uri = + URI.create( + this.getBasePushURL() + + String.format("/sources/%s/stream/%s/close", sourceId, streamId)); + + HttpRequest request = + HttpRequest.newBuilder() + .headers(headers) + .uri(uri) + .POST(HttpRequest.BodyPublishers.ofString("")) + .build(); + + return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + } + + public HttpResponse requireStreamChunk(String sourceId, String streamId) + throws IOException, InterruptedException { + String[] headers = + this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); + URI uri = + URI.create( + this.getBasePushURL() + + String.format("/sources/%s/stream/%s/chunk", sourceId, streamId)); + + HttpRequest request = + HttpRequest.newBuilder() + .headers(headers) + .uri(uri) + .POST(HttpRequest.BodyPublishers.ofString("")) + .build(); + + return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + } + + /** + * Create a file container. See [Creating a File Container](https://docs.coveo.com/en/43). + * + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse createFileContainer() throws IOException, InterruptedException { + String[] headers = + this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); + URI uri = URI.create(this.getBasePushURL() + "/files"); + + HttpRequest request = + HttpRequest.newBuilder() + .headers(headers) + .uri(uri) + .POST(HttpRequest.BodyPublishers.ofString("")) + .build(); + + return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + } + + /** + * Update the status of a Push source. See [Updating the Status of a Push + * Source](https://docs.coveo.com/en/35). + * + * @param status + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse updateSourceStatus(String sourceId, PushAPIStatus status) + throws IOException, InterruptedException { + String[] headers = + this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); + URI uri = + URI.create( + this.getBasePushURL() + + String.format("/sources/%s/status?statusType=%s", sourceId, status.toString())); + + HttpRequest request = + HttpRequest.newBuilder() + .headers(headers) + .uri(uri) + .POST(HttpRequest.BodyPublishers.ofString("")) + .build(); + + return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + } + + /** + * Upload content update into a file container. See [Upload the Content Update into the File + * Container](https://docs.coveo.com/en/90/index-content/manage-batches-of-items-in-a-push-source#step-2-upload-the-content-update-into-the-file-container). + * + * @param fileContainer + * @param batchUpdateJson + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse uploadContentToFileContainer( + FileContainer fileContainer, String batchUpdateJson) + throws IOException, InterruptedException { + String[] headers = + fileContainer.requiredHeaders.entrySet().stream() + .flatMap(entry -> Stream.of(entry.getKey(), entry.getValue())) + .toArray(String[]::new); + URI uri = URI.create(fileContainer.uploadUri); + + HttpRequest request = + HttpRequest.newBuilder() + .headers(headers) + .uri(uri) + .PUT(HttpRequest.BodyPublishers.ofString(batchUpdateJson)) + .build(); + + return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + } + + /** + * Push a file container into a push source. See [Push the File Container into a Push + * Source](https://docs.coveo.com/en/90/index-content/manage-batches-of-items-in-a-push-source#step-3-push-the-file-container-into-a-push-source). + * + * @param sourceId + * @param fileContainer + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse pushFileContainerContent(String sourceId, FileContainer fileContainer) + throws IOException, InterruptedException { + String[] headers = + this.getHeaders(this.getAuthorizationHeader(), this.getContentTypeApplicationJSONHeader()); + URI uri = + URI.create( + this.getBasePushURL() + + String.format( + "/sources/%s/documents/batch?fileId=%s", sourceId, fileContainer.fileId)); + + HttpRequest request = + HttpRequest.newBuilder() + .headers(headers) + .uri(uri) + .PUT(HttpRequest.BodyPublishers.ofString("")) + .build(); + + return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + } + + /** + * Push a binary to a File Container. See [Upload the Item Data Into the File + * Container](https://docs.coveo.com/en/69#step-2-upload-the-item-data-into-the-file-container) + * + * @param fileContainer + * @param fileAsBytes + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse pushBinaryToFileContainer( + FileContainer fileContainer, byte[] fileAsBytes) throws IOException, InterruptedException { + String[] headers = + this.getHeaders(this.getAes256Header(), this.getContentTypeApplicationOctetStreamHeader()); + URI uri = URI.create(fileContainer.uploadUri); + + HttpRequest request = + HttpRequest.newBuilder() + .headers(headers) + .uri(uri) + .PUT(HttpRequest.BodyPublishers.ofByteArray(fileAsBytes)) + .build(); + + return this.httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + } + + private String getBaseSourceURL() { + return String.format("%s/sources", this.getBasePlatformURL()); + } + + private String getBasePlatformURL() { + return String.format( + "%s/rest/organizations/%s", this.platformUrl.getPlatformUrl(), this.organizationId); + } + + private String getBasePushURL() { + return String.format( + "%s/push/v1/organizations/%s", this.platformUrl.getApiUrl(), this.organizationId); + } + + private String getBaseProviderURL(String providerId) { + return String.format("%s/providers/%s", this.getBasePushURL(), providerId); + } + + private String[] getHeaders(String[]... headers) { + String[] out = new String[] {}; + for (String[] header : headers) { + out = Stream.concat(Arrays.stream(out), Arrays.stream(header)).toArray(String[]::new); + } + return out; + } + + private String[] getAuthorizationHeader() { + return new String[] {"Authorization", String.format("Bearer %s", this.apiKey)}; + } + + private String[] getContentTypeApplicationJSONHeader() { + return new String[] {"Content-Type", "application/json", "Accept", "application/json"}; + } + + private String[] getAes256Header() { + return new String[] {"x-amz-server-side-encryption", "AES256"}; + } + + private String[] getContentTypeApplicationOctetStreamHeader() { + return new String[] {"Content-Type", "application/octet-stream"}; + } + + private String toJSON(HashMap hashMap) { + return new Gson().toJson(hashMap, new TypeToken>() {}.getType()); + } } diff --git a/src/main/java/com/coveo/pushapiclient/PlatformUrl.java b/src/main/java/com/coveo/pushapiclient/PlatformUrl.java index 5f6830f8..7062dc11 100644 --- a/src/main/java/com/coveo/pushapiclient/PlatformUrl.java +++ b/src/main/java/com/coveo/pushapiclient/PlatformUrl.java @@ -2,41 +2,39 @@ public class PlatformUrl { - public static final Environment DEFAULT_ENVIRONMENT = Environment.PRODUCTION; - public static final Region DEFAULT_REGION = Region.US; - - private final Environment environment; - private final Region region; - - /** - * @param environment The environment platform of your organization - * @param region The physical center of your organization - * - * @see https://docs.coveo.com/en/2976 - */ - public PlatformUrl(Environment environment, Region region) { - this.environment = environment; - this.region = region; - } - - public String getPlatformUrl() { - return String.format("https://platform%s%s.cloud.coveo.com", this.getUrlEnvironment(), this.getUrlRegion()); - } - - public String getApiUrl() { - return String.format("https://api%s%s.cloud.coveo.com", this.getUrlEnvironment(), this.getUrlRegion()); - } - - private String getUrlEnvironment() { - return this.environment == PlatformUrl.DEFAULT_ENVIRONMENT - ? "" - : this.environment.getValue(); - } - - private String getUrlRegion() { - return this.region == PlatformUrl.DEFAULT_REGION - ? "" - : String.format("-%s", this.region.getValue()); - } - + public static final Environment DEFAULT_ENVIRONMENT = Environment.PRODUCTION; + public static final Region DEFAULT_REGION = Region.US; + + private final Environment environment; + private final Region region; + + /** + * @param environment The environment platform of your organization + * @param region The physical center of your organization + * @see https://docs.coveo.com/en/2976 + */ + public PlatformUrl(Environment environment, Region region) { + this.environment = environment; + this.region = region; + } + + public String getPlatformUrl() { + return String.format( + "https://platform%s%s.cloud.coveo.com", this.getUrlEnvironment(), this.getUrlRegion()); + } + + public String getApiUrl() { + return String.format( + "https://api%s%s.cloud.coveo.com", this.getUrlEnvironment(), this.getUrlRegion()); + } + + private String getUrlEnvironment() { + return this.environment == PlatformUrl.DEFAULT_ENVIRONMENT ? "" : this.environment.getValue(); + } + + private String getUrlRegion() { + return this.region == PlatformUrl.DEFAULT_REGION + ? "" + : String.format("-%s", this.region.getValue()); + } } diff --git a/src/main/java/com/coveo/pushapiclient/PlatformUrlBuilder.java b/src/main/java/com/coveo/pushapiclient/PlatformUrlBuilder.java index 3d05ff09..45f26be3 100644 --- a/src/main/java/com/coveo/pushapiclient/PlatformUrlBuilder.java +++ b/src/main/java/com/coveo/pushapiclient/PlatformUrlBuilder.java @@ -2,20 +2,20 @@ public class PlatformUrlBuilder { - private Environment environment = PlatformUrl.DEFAULT_ENVIRONMENT; - private Region region = PlatformUrl.DEFAULT_REGION; + private Environment environment = PlatformUrl.DEFAULT_ENVIRONMENT; + private Region region = PlatformUrl.DEFAULT_REGION; - public PlatformUrlBuilder withEnvironment(Environment environment) { - this.environment = environment; - return this; - } + public PlatformUrlBuilder withEnvironment(Environment environment) { + this.environment = environment; + return this; + } - public PlatformUrlBuilder withRegion(Region region) { - this.region = region; - return this; - } + public PlatformUrlBuilder withRegion(Region region) { + this.region = region; + return this; + } - public PlatformUrl build() { - return new PlatformUrl(this.environment, this.region); - } + public PlatformUrl build() { + return new PlatformUrl(this.environment, this.region); + } } diff --git a/src/main/java/com/coveo/pushapiclient/PushAPIStatus.java b/src/main/java/com/coveo/pushapiclient/PushAPIStatus.java index 7b6a90ee..ad1adacb 100644 --- a/src/main/java/com/coveo/pushapiclient/PushAPIStatus.java +++ b/src/main/java/com/coveo/pushapiclient/PushAPIStatus.java @@ -1,11 +1,12 @@ package com.coveo.pushapiclient; /** - * Enum for possible PushAPI statuses. See [Updating the Status of a Push Source](https://docs.coveo.com/en/35). + * Enum for possible PushAPI statuses. See [Updating the Status of a Push + * Source](https://docs.coveo.com/en/35). */ public enum PushAPIStatus { - IDLE, - REBUILD, - INCREMENTAL, - REFRESH; + IDLE, + REBUILD, + INCREMENTAL, + REFRESH; } diff --git a/src/main/java/com/coveo/pushapiclient/PushEnabledSource.java b/src/main/java/com/coveo/pushapiclient/PushEnabledSource.java index b90b5f1e..e5fa4809 100644 --- a/src/main/java/com/coveo/pushapiclient/PushEnabledSource.java +++ b/src/main/java/com/coveo/pushapiclient/PushEnabledSource.java @@ -1,6 +1,4 @@ package com.coveo.pushapiclient; // Marker Interface -public interface PushEnabledSource extends BaseSource { - -} +public interface PushEnabledSource extends BaseSource {} diff --git a/src/main/java/com/coveo/pushapiclient/PushSource.java b/src/main/java/com/coveo/pushapiclient/PushSource.java index b84bf354..b45b2c30 100644 --- a/src/main/java/com/coveo/pushapiclient/PushSource.java +++ b/src/main/java/com/coveo/pushapiclient/PushSource.java @@ -1,7 +1,6 @@ package com.coveo.pushapiclient; import com.google.gson.Gson; - import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; @@ -9,322 +8,289 @@ // TODO: LENS-851 - Make public when ready class PushSource implements PushEnabledSource { - private final String apiKey; - private final ApiUrl urlExtractor; - private final PlatformClient platformClient; - - @Override - public String getOrganizationId() { - return this.urlExtractor.getOrganizationId(); - } - - @Override - public PlatformUrl getPlatformUrl() { - return this.urlExtractor.getPlatformUrl(); - } + private final String apiKey; + private final ApiUrl urlExtractor; + private final PlatformClient platformClient; - @Override - public String getId() { - return this.urlExtractor.getSourceId(); - } + @Override + public String getOrganizationId() { + return this.urlExtractor.getOrganizationId(); + } - @Override - public String getApiKey() { - return this.apiKey; - } + @Override + public PlatformUrl getPlatformUrl() { + return this.urlExtractor.getPlatformUrl(); + } - /** - * Creates a push Source in Coveo Org - * - * @param platformClient - * @param name - * @param name The name of the source to create - * @param sourceVisibility The security option that should be applied to the content of the source. See [Content Security](https://docs.coveo.com/en/1779). - * @return - * @throws IOException - * @throws InterruptedException - */ - public static HttpResponse create(PlatformClient platformClient, String name, SourceVisibility sourceVisibility) throws IOException, InterruptedException { - return platformClient.createSource(name, SourceType.PUSH, sourceVisibility); - } + @Override + public String getId() { + return this.urlExtractor.getSourceId(); + } - /** - * Create a Push source instance from its - * Push API URL - * - * @param apiKey The API key used for all operations regarding your source. - *

- * Ensure your API key has the required privileges for the - * operation you will be performing - * * - *

- * For more information about which privileges are required, - * see - * Privilege - * Reference. - * - * @param sourceUrl The URL available when you edit your source in the Coveo - * Administration Console. The URL should contain your - * ORGANIZATION_ID and SOURCE_ID, - * which are required parameters for all operations regarding - * your source. - *

- * Some examples of valid source URLs: - * - *

-     * https://api.cloud.coveo.com/push/v1/organizations/my-org-if/sources/my-source-id/documents
-     * https://api-eu.cloud.coveo.com/push/v1/organizations/my-org-if/sources/my-source-id/documents
-     *                  
- * - * @throws MalformedURLException - */ - public PushSource(String apiKey, URL sourceUrl) throws MalformedURLException { - this.apiKey = apiKey; - this.urlExtractor = new ApiUrl(sourceUrl); - String organizationId = urlExtractor.getOrganizationId(); - PlatformUrl platformUrl = urlExtractor.getPlatformUrl(); - this.platformClient = new PlatformClient(apiKey, organizationId, platformUrl); - } + @Override + public String getApiKey() { + return this.apiKey; + } - /** - * Create a Push source instance - * - * @param apiKey The API key used for all operations regarding your - * source. - *

- * Ensure your API key has the required privileges for the - * operation you will be performing - * * - *

- * For more information about which privileges are - * required, - * see - * Privilege - * Reference. - * - * @param organizationId The unique identifier of your organization. - *

- * The Organization Id can be retrieved in the URL of your - * Coveo organization. - * - * @param sourceId The unique identifier of the target Push source. - *

- * The Source Id can be retrieved when you edit your - * source in the Coveo - * Administration Console - * - */ - public static PushSource fromPlatformUrl(String apiKey, String organizationId, String sourceId) { - PlatformUrl platformUrl = new PlatformUrl(PlatformUrl.DEFAULT_ENVIRONMENT, PlatformUrl.DEFAULT_REGION); - return new PushSource(apiKey, organizationId, sourceId, platformUrl); - } + /** + * Creates a push Source + * in Coveo Org + * + * @param platformClient + * @param name + * @param name The name of the source to create + * @param sourceVisibility The security option that should be applied to the content of the + * source. See [Content Security](https://docs.coveo.com/en/1779). + * @return + * @throws IOException + * @throws InterruptedException + */ + public static HttpResponse create( + PlatformClient platformClient, String name, SourceVisibility sourceVisibility) + throws IOException, InterruptedException { + return platformClient.createSource(name, SourceType.PUSH, sourceVisibility); + } - /** - * Create a Push source instance - * - * @param apiKey The API key used for all operations regarding your - * source. - *

- * Ensure your API key has the required privileges for the - * operation you will be performing - * * - *

- * For more information about which privileges are - * required, - * see - * Privilege - * Reference. - * - * @param organizationId The unique identifier of your organization. - *

- * The Organization Id can be retrieved in the URL of your - * Coveo organization. - * - * @param sourceId The unique identifier of the target Push source. - *

- * The Source Id can be retrieved when you edit your - * source in the Coveo - * Administration Console - * - * @param platformUrl The object containing additional information on the - * URL endpoint. - * You can use the {@link PlatformUrl} when your - * organization is located in a non-default Coveo - * environement and/or region. When not specified, the - * default platform URL values will be used: - * {@link PlatformUrl#DEFAULT_ENVIRONMENT} and - * {@link PlatformUrl#DEFAULT_REGION} - * - */ - public static PushSource fromPlatformUrl(String apiKey, String organizationId, String sourceId, - PlatformUrl platformUrl) { - return new PushSource(apiKey, organizationId, sourceId, platformUrl); - } + /** + * Create a Push source instance from its Push API URL + * + * @param apiKey The API key used for all operations regarding your source. + *

Ensure your API key has the required privileges for the operation you will be performing + * * + *

For more information about which privileges are required, see Privilege Reference. + * @param sourceUrl The URL available when you edit your source in the Coveo Administration + * Console. The URL should contain your ORGANIZATION_ID and SOURCE_ID + * , which are required parameters for all operations regarding your source. + *

Some examples of valid source URLs: + *

+   * https://api.cloud.coveo.com/push/v1/organizations/my-org-if/sources/my-source-id/documents
+   * https://api-eu.cloud.coveo.com/push/v1/organizations/my-org-if/sources/my-source-id/documents
+   *                  
+ * + * @throws MalformedURLException + */ + public PushSource(String apiKey, URL sourceUrl) throws MalformedURLException { + this.apiKey = apiKey; + this.urlExtractor = new ApiUrl(sourceUrl); + String organizationId = urlExtractor.getOrganizationId(); + PlatformUrl platformUrl = urlExtractor.getPlatformUrl(); + this.platformClient = new PlatformClient(apiKey, organizationId, platformUrl); + } - private PushSource(String apiKey, String organizationId, String sourceId, PlatformUrl platformUrl) { - this.apiKey = apiKey; - this.urlExtractor = new ApiUrl(organizationId, sourceId, platformUrl); - this.platformClient = new PlatformClient(apiKey, organizationId, platformUrl); - } + /** + * Create a Push source instance + * + * @param apiKey The API key used for all operations regarding your source. + *

Ensure your API key has the required privileges for the operation you will be performing + * * + *

For more information about which privileges are required, see Privilege Reference. + * @param organizationId The unique identifier of your organization. + *

The Organization Id can be retrieved in the URL of your Coveo organization. + * @param sourceId The unique identifier of the target Push source. + *

The Source Id can be retrieved when you edit your source in the Coveo Administration + * Console + */ + public static PushSource fromPlatformUrl(String apiKey, String organizationId, String sourceId) { + PlatformUrl platformUrl = + new PlatformUrl(PlatformUrl.DEFAULT_ENVIRONMENT, PlatformUrl.DEFAULT_REGION); + return new PushSource(apiKey, organizationId, sourceId, platformUrl); + } - /** - * Create or update a security identity. See [Adding a Single Security - * Identity](https://docs.coveo.com/en/167) and [Security Identity - * Models](https://docs.coveo.com/en/139). - * - * @param securityProviderId - * @param securityIdentityModel - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse createOrUpdateSecurityIdentity(String securityProviderId, - SecurityIdentityModel securityIdentityModel) throws IOException, InterruptedException { - return this.platformClient.createOrUpdateSecurityIdentity(securityProviderId, securityIdentityModel); - } + /** + * Create a Push source instance + * + * @param apiKey The API key used for all operations regarding your source. + *

Ensure your API key has the required privileges for the operation you will be performing + * * + *

For more information about which privileges are required, see Privilege Reference. + * @param organizationId The unique identifier of your organization. + *

The Organization Id can be retrieved in the URL of your Coveo organization. + * @param sourceId The unique identifier of the target Push source. + *

The Source Id can be retrieved when you edit your source in the Coveo Administration + * Console + * @param platformUrl The object containing additional information on the URL endpoint. You can + * use the {@link PlatformUrl} when your organization is located in a non-default Coveo + * environement and/or region. When not specified, the default platform URL values will be + * used: {@link PlatformUrl#DEFAULT_ENVIRONMENT} and {@link PlatformUrl#DEFAULT_REGION} + */ + public static PushSource fromPlatformUrl( + String apiKey, String organizationId, String sourceId, PlatformUrl platformUrl) { + return new PushSource(apiKey, organizationId, sourceId, platformUrl); + } - /** - * Create or update a security identity alias. See [Adding a Single - * Alias](https://docs.coveo.com/en/142) and [User Alias Definition - * Examples](https://docs.coveo.com/en/46). - * - * @param securityProviderId - * @param securityIdentityAliasModel - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse createOrUpdateSecurityIdentityAlias(String securityProviderId, - SecurityIdentityAliasModel securityIdentityAliasModel) throws IOException, InterruptedException { - return this.platformClient.createOrUpdateSecurityIdentityAlias(securityProviderId, securityIdentityAliasModel); - } + private PushSource( + String apiKey, String organizationId, String sourceId, PlatformUrl platformUrl) { + this.apiKey = apiKey; + this.urlExtractor = new ApiUrl(organizationId, sourceId, platformUrl); + this.platformClient = new PlatformClient(apiKey, organizationId, platformUrl); + } - /** - * Delete a security identity. See [Disabling a Single Security - * Identity](https://docs.coveo.com/en/84). - * - * @param securityProviderId - * @param securityIdentityDelete - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse deleteSecurityIdentity(String securityProviderId, - SecurityIdentityDelete securityIdentityDelete) throws IOException, InterruptedException { - return this.platformClient.deleteSecurityIdentity(securityProviderId, securityIdentityDelete); - } + /** + * Create or update a security identity. See [Adding a Single Security + * Identity](https://docs.coveo.com/en/167) and [Security Identity + * Models](https://docs.coveo.com/en/139). + * + * @param securityProviderId + * @param securityIdentityModel + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse createOrUpdateSecurityIdentity( + String securityProviderId, SecurityIdentityModel securityIdentityModel) + throws IOException, InterruptedException { + return this.platformClient.createOrUpdateSecurityIdentity( + securityProviderId, securityIdentityModel); + } - /** - * Update the status of a Push source. See [Updating the Status of a Push - * Source](https://docs.coveo.com/en/35). - * - * @param status - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse updateSourceStatus(PushAPIStatus status) - throws IOException, InterruptedException { - return this.platformClient.updateSourceStatus(this.getId(), status); - } + /** + * Create or update a security identity alias. See [Adding a Single + * Alias](https://docs.coveo.com/en/142) and [User Alias Definition + * Examples](https://docs.coveo.com/en/46). + * + * @param securityProviderId + * @param securityIdentityAliasModel + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse createOrUpdateSecurityIdentityAlias( + String securityProviderId, SecurityIdentityAliasModel securityIdentityAliasModel) + throws IOException, InterruptedException { + return this.platformClient.createOrUpdateSecurityIdentityAlias( + securityProviderId, securityIdentityAliasModel); + } - /** - * Delete old security identities. See [Disabling Old Security - * Identities](https://docs.coveo.com/en/33). - * - * @param securityProviderId - * @param batchDelete - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse deleteOldSecurityIdentities(String securityProviderId, - SecurityIdentityDeleteOptions batchDelete) throws IOException, InterruptedException { - return this.platformClient.deleteOldSecurityIdentities(securityProviderId, batchDelete); - } + /** + * Delete a security identity. See [Disabling a Single Security + * Identity](https://docs.coveo.com/en/84). + * + * @param securityProviderId + * @param securityIdentityDelete + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse deleteSecurityIdentity( + String securityProviderId, SecurityIdentityDelete securityIdentityDelete) + throws IOException, InterruptedException { + return this.platformClient.deleteSecurityIdentity(securityProviderId, securityIdentityDelete); + } - /** - * Manage batches of security identities. See [Manage Batches of Security - * Identities](https://docs.coveo.com/en/55). - * - * @param securityProviderId - * @param batchConfig - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse manageSecurityIdentities(String securityProviderId, - SecurityIdentityBatchConfig batchConfig) throws IOException, InterruptedException { - return this.platformClient.manageSecurityIdentities(securityProviderId, batchConfig); - } + /** + * Update the status of a Push source. See [Updating the Status of a Push + * Source](https://docs.coveo.com/en/35). + * + * @param status + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse updateSourceStatus(PushAPIStatus status) + throws IOException, InterruptedException { + return this.platformClient.updateSourceStatus(this.getId(), status); + } - /** - * Manages pushing batches of Security Identities to a File Container, then into - * Coveo. See [Manage Batches of Security - * Identities](https://docs.coveo.com/en/55) - * - * @param securityProviderId - * @param batchIdentity - * @return - * @throws IOException - * @throws InterruptedException - */ - public SecurityIdentityBatchResponse batchUpdateSecurityIdentities(String securityProviderId, - BatchIdentity batchIdentity) throws IOException, InterruptedException { - SecurityIdentityBatchResponse securityIdentityBatchResponse = new SecurityIdentityBatchResponse(); - HttpResponse resFileContainer = this.platformClient.createFileContainer(); - FileContainer fileContainer = new Gson().fromJson(resFileContainer.body(), FileContainer.class); - String batchIdJson = new Gson().toJson(batchIdentity.marshal()); - securityIdentityBatchResponse.s3Response = this.platformClient.uploadContentToFileContainer(fileContainer, - batchIdJson); - if (securityIdentityBatchResponse.s3Response.statusCode() >= 200 - && securityIdentityBatchResponse.s3Response.statusCode() <= 299) { // maybe just 200 or 202 - SecurityIdentityBatchConfig batchConfig = new SecurityIdentityBatchConfig(fileContainer.fileId, 0l); - securityIdentityBatchResponse.batchResponse = this.manageSecurityIdentities(securityProviderId, - batchConfig); - } - return securityIdentityBatchResponse; - } + /** + * Delete old security identities. See [Disabling Old Security + * Identities](https://docs.coveo.com/en/33). + * + * @param securityProviderId + * @param batchDelete + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse deleteOldSecurityIdentities( + String securityProviderId, SecurityIdentityDeleteOptions batchDelete) + throws IOException, InterruptedException { + return this.platformClient.deleteOldSecurityIdentities(securityProviderId, batchDelete); + } - /** - * Adds or updates an individual item in a push source. See [Adding a Single - * Item in a Push Source](https://docs.coveo.com/en/133). - * - * @param docBuilder - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse addOrUpdateDocument(DocumentBuilder docBuilder) - throws IOException, InterruptedException { - CompressionType compressionType = docBuilder.getDocument().compressedBinaryData != null - ? docBuilder.getDocument().compressedBinaryData.getCompressionType() - : CompressionType.UNCOMPRESSED; - return this.platformClient.pushDocument(this.getId(), docBuilder.marshal(), docBuilder.getDocument().uri, - compressionType); - } + /** + * Manage batches of security identities. See [Manage Batches of Security + * Identities](https://docs.coveo.com/en/55). + * + * @param securityProviderId + * @param batchConfig + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse manageSecurityIdentities( + String securityProviderId, SecurityIdentityBatchConfig batchConfig) + throws IOException, InterruptedException { + return this.platformClient.manageSecurityIdentities(securityProviderId, batchConfig); + } - /** - * Deletes a specific item from a Push source. Optionally, the child items of - * that item can also be deleted. See [Deleting an Item in a Push - * Source](https://docs.coveo.com/en/171). - * - * @param documentId - * @param deleteChildren - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse deleteDocument(String documentId, Boolean deleteChildren) - throws IOException, InterruptedException { - return this.platformClient.deleteDocument(this.getId(), documentId, deleteChildren); + /** + * Manages pushing batches of Security Identities to a File Container, then into Coveo. See + * [Manage Batches of Security Identities](https://docs.coveo.com/en/55) + * + * @param securityProviderId + * @param batchIdentity + * @return + * @throws IOException + * @throws InterruptedException + */ + public SecurityIdentityBatchResponse batchUpdateSecurityIdentities( + String securityProviderId, BatchIdentity batchIdentity) + throws IOException, InterruptedException { + SecurityIdentityBatchResponse securityIdentityBatchResponse = + new SecurityIdentityBatchResponse(); + HttpResponse resFileContainer = this.platformClient.createFileContainer(); + FileContainer fileContainer = new Gson().fromJson(resFileContainer.body(), FileContainer.class); + String batchIdJson = new Gson().toJson(batchIdentity.marshal()); + securityIdentityBatchResponse.s3Response = + this.platformClient.uploadContentToFileContainer(fileContainer, batchIdJson); + if (securityIdentityBatchResponse.s3Response.statusCode() >= 200 + && securityIdentityBatchResponse.s3Response.statusCode() <= 299) { // maybe just 200 or 202 + SecurityIdentityBatchConfig batchConfig = + new SecurityIdentityBatchConfig(fileContainer.fileId, 0l); + securityIdentityBatchResponse.batchResponse = + this.manageSecurityIdentities(securityProviderId, batchConfig); } + return securityIdentityBatchResponse; + } + /** + * Adds or updates an individual item in a push source. See [Adding a Single Item in a Push + * Source](https://docs.coveo.com/en/133). + * + * @param docBuilder + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse addOrUpdateDocument(DocumentBuilder docBuilder) + throws IOException, InterruptedException { + CompressionType compressionType = + docBuilder.getDocument().compressedBinaryData != null + ? docBuilder.getDocument().compressedBinaryData.getCompressionType() + : CompressionType.UNCOMPRESSED; + return this.platformClient.pushDocument( + this.getId(), docBuilder.marshal(), docBuilder.getDocument().uri, compressionType); + } + /** + * Deletes a specific item from a Push source. Optionally, the child items of that item can also + * be deleted. See [Deleting an Item in a Push Source](https://docs.coveo.com/en/171). + * + * @param documentId + * @param deleteChildren + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse deleteDocument(String documentId, Boolean deleteChildren) + throws IOException, InterruptedException { + return this.platformClient.deleteDocument(this.getId(), documentId, deleteChildren); + } } diff --git a/src/main/java/com/coveo/pushapiclient/Region.java b/src/main/java/com/coveo/pushapiclient/Region.java index 6e6a6df9..2c42691e 100644 --- a/src/main/java/com/coveo/pushapiclient/Region.java +++ b/src/main/java/com/coveo/pushapiclient/Region.java @@ -1,20 +1,18 @@ package com.coveo.pushapiclient; -/** - * Available Platform regions to connect to - */ +/** Available Platform regions to connect to */ public enum Region { - US("us"), - EU("eu"), - AU("au"); + US("us"), + EU("eu"), + AU("au"); - private String value; + private String value; - Region(String value) { - this.value = value; - } + Region(String value) { + this.value = value; + } - public String getValue() { - return this.value; - } -} \ No newline at end of file + public String getValue() { + return this.value; + } +} diff --git a/src/main/java/com/coveo/pushapiclient/SecurityIdentity.java b/src/main/java/com/coveo/pushapiclient/SecurityIdentity.java index 998cd4e3..a53dfd5f 100644 --- a/src/main/java/com/coveo/pushapiclient/SecurityIdentity.java +++ b/src/main/java/com/coveo/pushapiclient/SecurityIdentity.java @@ -1,33 +1,33 @@ package com.coveo.pushapiclient; public class SecurityIdentity { - /** - * The name of the security identity. - *

- * Examples: - * - `asmith@example.com` - * - `SampleTeam2` - */ - public String identity; - /** - * The type of the identity. - * Valid values: - * - `UNKNOWN` - * - `USER` : Defines a single user. - * - `GROUP` : Defines an existing group of identities within the indexed system. Individual members of this group can be of any valid identity Type (USER, GROUP, or VIRTUAL_GROUP). - * - `VIRTUAL_GROUP` : Defines a group that doesn't exist within the indexed system. Mechanically, a `VIRTUAL_GROUP` is identical to a `GROUP`. - */ - public SecurityIdentityType identityType; - /** - * The security identity provider through which the security identity is updated. - *

- * Defaults to the first security identity provider associated with the target Push source. - */ - public String securityProvider; + /** + * The name of the security identity. + * + *

Examples: - `asmith@example.com` - `SampleTeam2` + */ + public String identity; - public SecurityIdentity(String identity, SecurityIdentityType securityIdentityType, String securityProvider) { - this.identity = identity; - this.identityType = securityIdentityType; - this.securityProvider = securityProvider; - } -} \ No newline at end of file + /** + * The type of the identity. Valid values: - `UNKNOWN` - `USER` : Defines a single user. - `GROUP` + * : Defines an existing group of identities within the indexed system. Individual members of this + * group can be of any valid identity Type (USER, GROUP, or VIRTUAL_GROUP). - `VIRTUAL_GROUP` : + * Defines a group that doesn't exist within the indexed system. Mechanically, a `VIRTUAL_GROUP` + * is identical to a `GROUP`. + */ + public SecurityIdentityType identityType; + + /** + * The security identity provider through which the security identity is updated. + * + *

Defaults to the first security identity provider associated with the target Push source. + */ + public String securityProvider; + + public SecurityIdentity( + String identity, SecurityIdentityType securityIdentityType, String securityProvider) { + this.identity = identity; + this.identityType = securityIdentityType; + this.securityProvider = securityProvider; + } +} diff --git a/src/main/java/com/coveo/pushapiclient/SecurityIdentityAliasModel.java b/src/main/java/com/coveo/pushapiclient/SecurityIdentityAliasModel.java index 631e8940..4d66a4a5 100644 --- a/src/main/java/com/coveo/pushapiclient/SecurityIdentityAliasModel.java +++ b/src/main/java/com/coveo/pushapiclient/SecurityIdentityAliasModel.java @@ -1,13 +1,12 @@ package com.coveo.pushapiclient; -/** - * See [User Alias Definition Examples](https://docs.coveo.com/en/46). - */ +/** See [User Alias Definition Examples](https://docs.coveo.com/en/46). */ public class SecurityIdentityAliasModel extends SecurityIdentityModelBase { - public final AliasMapping[] mappings; + public final AliasMapping[] mappings; - public SecurityIdentityAliasModel(AliasMapping[] mappings, IdentityModel identity, IdentityModel[] wellKnowns) { - super(identity, wellKnowns); - this.mappings = mappings; - } + public SecurityIdentityAliasModel( + AliasMapping[] mappings, IdentityModel identity, IdentityModel[] wellKnowns) { + super(identity, wellKnowns); + this.mappings = mappings; + } } diff --git a/src/main/java/com/coveo/pushapiclient/SecurityIdentityBatchConfig.java b/src/main/java/com/coveo/pushapiclient/SecurityIdentityBatchConfig.java index 1fc99d63..74cb66b4 100644 --- a/src/main/java/com/coveo/pushapiclient/SecurityIdentityBatchConfig.java +++ b/src/main/java/com/coveo/pushapiclient/SecurityIdentityBatchConfig.java @@ -2,45 +2,46 @@ import java.util.Objects; -/** - * See [Manage Batches of Security Identities](https://docs.coveo.com/en/55). - */ +/** See [Manage Batches of Security Identities](https://docs.coveo.com/en/55). */ public class SecurityIdentityBatchConfig { - private final String fileId; - private final Long orderingId; - - public SecurityIdentityBatchConfig(String fileId, Long orderingId) { - this.fileId = fileId; - this.orderingId = orderingId; - } - - public String getFileId() { - return fileId; - } - - public Long getOrderingId() { - return orderingId; - } - - @Override - public String toString() { - return "SecurityIdentityBatchConfig[" + - "fileId='" + fileId + '\'' + - ", orderingId=" + orderingId + - ']'; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null || getClass() != obj.getClass()) return false; - SecurityIdentityBatchConfig that = (SecurityIdentityBatchConfig) obj; - return Objects.equals(fileId, that.fileId) && Objects.equals(orderingId, that.orderingId); - } - - @Override - public int hashCode() { - return Objects.hash(fileId, orderingId); - } + private final String fileId; + private final Long orderingId; + + public SecurityIdentityBatchConfig(String fileId, Long orderingId) { + this.fileId = fileId; + this.orderingId = orderingId; + } + + public String getFileId() { + return fileId; + } + + public Long getOrderingId() { + return orderingId; + } + + @Override + public String toString() { + return "SecurityIdentityBatchConfig[" + + "fileId='" + + fileId + + '\'' + + ", orderingId=" + + orderingId + + ']'; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null || getClass() != obj.getClass()) return false; + SecurityIdentityBatchConfig that = (SecurityIdentityBatchConfig) obj; + return Objects.equals(fileId, that.fileId) && Objects.equals(orderingId, that.orderingId); + } + + @Override + public int hashCode() { + return Objects.hash(fileId, orderingId); + } } diff --git a/src/main/java/com/coveo/pushapiclient/SecurityIdentityBatchResponse.java b/src/main/java/com/coveo/pushapiclient/SecurityIdentityBatchResponse.java index 58694f34..f8f51848 100644 --- a/src/main/java/com/coveo/pushapiclient/SecurityIdentityBatchResponse.java +++ b/src/main/java/com/coveo/pushapiclient/SecurityIdentityBatchResponse.java @@ -3,26 +3,27 @@ import java.net.http.HttpResponse; /** - * Used for the responses when pushing batches of Security Identities. See [Manage Batches of Security Identities](https://docs.coveo.com/en/55) + * Used for the responses when pushing batches of Security Identities. See [Manage Batches of + * Security Identities](https://docs.coveo.com/en/55) */ public class SecurityIdentityBatchResponse { - protected HttpResponse s3Response; - protected HttpResponse batchResponse; + protected HttpResponse s3Response; + protected HttpResponse batchResponse; - public HttpResponse getS3Response() { - return s3Response; - } + public HttpResponse getS3Response() { + return s3Response; + } - public void setS3Response(HttpResponse s3Response) { - this.s3Response = s3Response; - } + public void setS3Response(HttpResponse s3Response) { + this.s3Response = s3Response; + } - public HttpResponse getBatchResponse() { - return batchResponse; - } + public HttpResponse getBatchResponse() { + return batchResponse; + } - public void setBatchResponse(HttpResponse batchResponse) { - this.batchResponse = batchResponse; - } + public void setBatchResponse(HttpResponse batchResponse) { + this.batchResponse = batchResponse; + } } diff --git a/src/main/java/com/coveo/pushapiclient/SecurityIdentityBuilder.java b/src/main/java/com/coveo/pushapiclient/SecurityIdentityBuilder.java index 6b69ddcc..e8884ecf 100644 --- a/src/main/java/com/coveo/pushapiclient/SecurityIdentityBuilder.java +++ b/src/main/java/com/coveo/pushapiclient/SecurityIdentityBuilder.java @@ -1,14 +1,11 @@ package com.coveo.pushapiclient; -/** - * Build a security identity. See {@link SecurityIdentity}. - */ +/** Build a security identity. See {@link SecurityIdentity}. */ public interface SecurityIdentityBuilder { - /** - * Build and return a list of {@link SecurityIdentity} - * - * @return - */ - SecurityIdentity[] build(); + /** + * Build and return a list of {@link SecurityIdentity} + * + * @return + */ + SecurityIdentity[] build(); } - diff --git a/src/main/java/com/coveo/pushapiclient/SecurityIdentityDelete.java b/src/main/java/com/coveo/pushapiclient/SecurityIdentityDelete.java index ce5884bb..7df5c128 100644 --- a/src/main/java/com/coveo/pushapiclient/SecurityIdentityDelete.java +++ b/src/main/java/com/coveo/pushapiclient/SecurityIdentityDelete.java @@ -2,38 +2,34 @@ import java.util.Objects; -/** - * See [Disabling a Single Security Identity](https://docs.coveo.com/en/84) - */ +/** See [Disabling a Single Security Identity](https://docs.coveo.com/en/84) */ public class SecurityIdentityDelete { - private final IdentityModel identity; - - public SecurityIdentityDelete(IdentityModel identity) { - this.identity = identity; - } - - public IdentityModel getIdentity() { - return identity; - } - - @Override - public String toString() { - return "SecurityIdentityDelete[" + - "identity=" + identity + - ']'; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null || getClass() != obj.getClass()) return false; - SecurityIdentityDelete that = (SecurityIdentityDelete) obj; - return Objects.equals(identity, that.identity); - } - - @Override - public int hashCode() { - return Objects.hash(identity); - } + private final IdentityModel identity; + + public SecurityIdentityDelete(IdentityModel identity) { + this.identity = identity; + } + + public IdentityModel getIdentity() { + return identity; + } + + @Override + public String toString() { + return "SecurityIdentityDelete[" + "identity=" + identity + ']'; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null || getClass() != obj.getClass()) return false; + SecurityIdentityDelete that = (SecurityIdentityDelete) obj; + return Objects.equals(identity, that.identity); + } + + @Override + public int hashCode() { + return Objects.hash(identity); + } } diff --git a/src/main/java/com/coveo/pushapiclient/SecurityIdentityDeleteOptions.java b/src/main/java/com/coveo/pushapiclient/SecurityIdentityDeleteOptions.java index 28861303..21147653 100644 --- a/src/main/java/com/coveo/pushapiclient/SecurityIdentityDeleteOptions.java +++ b/src/main/java/com/coveo/pushapiclient/SecurityIdentityDeleteOptions.java @@ -2,45 +2,47 @@ import java.util.Objects; -/** - * See [Disabling Old Security Identities](https://docs.coveo.com/en/33) - */ +/** See [Disabling Old Security Identities](https://docs.coveo.com/en/33) */ public class SecurityIdentityDeleteOptions { - private final Integer queueDelay; - private final Long orderingId; - - public SecurityIdentityDeleteOptions(Integer queueDelay, Long orderingId) { - this.queueDelay = queueDelay; - this.orderingId = orderingId; - } - - public Integer getQueueDelay() { - return queueDelay; - } - - public Long getOrderingId() { - return orderingId; - } - - @Override - public String toString() { - return "SecurityIdentityDeleteOptions" + "[" + - "queueDelay=" + queueDelay + - ", orderingId=" + orderingId + - ']'; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null || getClass() != obj.getClass()) return false; - SecurityIdentityDeleteOptions that = (SecurityIdentityDeleteOptions) obj; - return Objects.equals(queueDelay, that.queueDelay) && Objects.equals(orderingId, that.orderingId); - } - - @Override - public int hashCode() { - return Objects.hash(queueDelay, orderingId); - } + private final Integer queueDelay; + private final Long orderingId; + + public SecurityIdentityDeleteOptions(Integer queueDelay, Long orderingId) { + this.queueDelay = queueDelay; + this.orderingId = orderingId; + } + + public Integer getQueueDelay() { + return queueDelay; + } + + public Long getOrderingId() { + return orderingId; + } + + @Override + public String toString() { + return "SecurityIdentityDeleteOptions" + + "[" + + "queueDelay=" + + queueDelay + + ", orderingId=" + + orderingId + + ']'; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null || getClass() != obj.getClass()) return false; + SecurityIdentityDeleteOptions that = (SecurityIdentityDeleteOptions) obj; + return Objects.equals(queueDelay, that.queueDelay) + && Objects.equals(orderingId, that.orderingId); + } + + @Override + public int hashCode() { + return Objects.hash(queueDelay, orderingId); + } } diff --git a/src/main/java/com/coveo/pushapiclient/SecurityIdentityModel.java b/src/main/java/com/coveo/pushapiclient/SecurityIdentityModel.java index 1dbb1e81..8cdaf7eb 100644 --- a/src/main/java/com/coveo/pushapiclient/SecurityIdentityModel.java +++ b/src/main/java/com/coveo/pushapiclient/SecurityIdentityModel.java @@ -1,13 +1,12 @@ package com.coveo.pushapiclient; -/** - * See [Security Identity Models](https://docs.coveo.com/en/139) - */ +/** See [Security Identity Models](https://docs.coveo.com/en/139) */ public class SecurityIdentityModel extends SecurityIdentityModelBase { - public final IdentityModel[] members; + public final IdentityModel[] members; - public SecurityIdentityModel(IdentityModel[] members, IdentityModel identity, IdentityModel[] wellKnowns) { - super(identity, wellKnowns); - this.members = members; - } + public SecurityIdentityModel( + IdentityModel[] members, IdentityModel identity, IdentityModel[] wellKnowns) { + super(identity, wellKnowns); + this.members = members; + } } diff --git a/src/main/java/com/coveo/pushapiclient/SecurityIdentityModelBase.java b/src/main/java/com/coveo/pushapiclient/SecurityIdentityModelBase.java index ad1b63b8..14181bdd 100644 --- a/src/main/java/com/coveo/pushapiclient/SecurityIdentityModelBase.java +++ b/src/main/java/com/coveo/pushapiclient/SecurityIdentityModelBase.java @@ -1,11 +1,11 @@ package com.coveo.pushapiclient; public class SecurityIdentityModelBase { - public final IdentityModel identity; - public final IdentityModel[] wellKnowns; + public final IdentityModel identity; + public final IdentityModel[] wellKnowns; - public SecurityIdentityModelBase(IdentityModel identity, IdentityModel[] wellKnowns) { - this.identity = identity; - this.wellKnowns = wellKnowns; - } + public SecurityIdentityModelBase(IdentityModel identity, IdentityModel[] wellKnowns) { + this.identity = identity; + this.wellKnowns = wellKnowns; + } } diff --git a/src/main/java/com/coveo/pushapiclient/SecurityIdentityType.java b/src/main/java/com/coveo/pushapiclient/SecurityIdentityType.java index 56e3d23e..70897c44 100644 --- a/src/main/java/com/coveo/pushapiclient/SecurityIdentityType.java +++ b/src/main/java/com/coveo/pushapiclient/SecurityIdentityType.java @@ -1,24 +1,24 @@ package com.coveo.pushapiclient; public enum SecurityIdentityType { - UNKNOWN { - public String toString() { - return "UNKNOWN"; - } - }, - USER { - public String toString() { - return "USER"; - } - }, - GROUP { - public String toString() { - return "GROUP"; - } - }, - VIRTUAL_GROUP { - public String toString() { - return "VIRTUAL_GROUP"; - } + UNKNOWN { + public String toString() { + return "UNKNOWN"; } -} \ No newline at end of file + }, + USER { + public String toString() { + return "USER"; + } + }, + GROUP { + public String toString() { + return "GROUP"; + } + }, + VIRTUAL_GROUP { + public String toString() { + return "VIRTUAL_GROUP"; + } + } +} diff --git a/src/main/java/com/coveo/pushapiclient/Source.java b/src/main/java/com/coveo/pushapiclient/Source.java index 475d3e5c..36772c12 100644 --- a/src/main/java/com/coveo/pushapiclient/Source.java +++ b/src/main/java/com/coveo/pushapiclient/Source.java @@ -1,227 +1,269 @@ package com.coveo.pushapiclient; import com.google.gson.Gson; - import java.io.IOException; import java.net.http.HttpResponse; // TODO: LENS-844 - Deprecate class public class Source { - PlatformClient platformClient; - - /** - * @param apiKey An apiKey capable of pushing documents and managing - * sources in a Coveo organization. See [Manage API - * Keys](https://docs.coveo.com/en/1718). - * @param organizationId The Coveo Organization identifier. - */ - public Source(String apiKey, String organizationId) { - this.platformClient = new PlatformClient(apiKey, organizationId); - } + PlatformClient platformClient; - /** - * @param apiKey An apiKey capable of pushing documents and managing - * sources in a Coveo organization. See [Manage API - * Keys](https://docs.coveo.com/en/1718). - * @param organizationId The Coveo Organization identifier. - * @param platformUrl - */ - public Source(String apiKey, String organizationId, PlatformUrl platformUrl) { - this.platformClient = new PlatformClient(apiKey, organizationId, platformUrl); - } + /** + * @param apiKey An apiKey capable of pushing documents and managing sources in a Coveo + * organization. See [Manage API Keys](https://docs.coveo.com/en/1718). + * @param organizationId The Coveo Organization identifier. + */ + public Source(String apiKey, String organizationId) { + this.platformClient = new PlatformClient(apiKey, organizationId); + } - /** - * @deprecated Please now use PlatformUrl to define your Platform environment - * @see PlatformUrl Construct a PlatformUrl - * - * @param apiKey An apiKey capable of pushing documents and managing sources in a Coveo organization. See [Manage API Keys](https://docs.coveo.com/en/1718). - * @param organizationId The Coveo Organization identifier. - * @param environment The Environment to be used. - */ - @Deprecated - public Source(String apiKey, String organizationId, Environment environment) { - this.platformClient = new PlatformClient(apiKey, organizationId, environment); - } + /** + * @param apiKey An apiKey capable of pushing documents and managing sources in a Coveo + * organization. See [Manage API Keys](https://docs.coveo.com/en/1718). + * @param organizationId The Coveo Organization identifier. + * @param platformUrl + */ + public Source(String apiKey, String organizationId, PlatformUrl platformUrl) { + this.platformClient = new PlatformClient(apiKey, organizationId, platformUrl); + } - /** - * Create a new push source. - * - * @param name The name of the source to create - * @param sourceVisibility The security option that should be applied to the content of the source. See [Content Security](https://docs.coveo.com/en/1779). - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse create(String name, SourceVisibility sourceVisibility) throws IOException, InterruptedException { - return this.platformClient.createSource(name, SourceType.PUSH, sourceVisibility); - } + /** + * @deprecated Please now use PlatformUrl to define your Platform environment + * @see PlatformUrl Construct a PlatformUrl + * @param apiKey An apiKey capable of pushing documents and managing sources in a Coveo + * organization. See [Manage API Keys](https://docs.coveo.com/en/1718). + * @param organizationId The Coveo Organization identifier. + * @param environment The Environment to be used. + */ + @Deprecated + public Source(String apiKey, String organizationId, Environment environment) { + this.platformClient = new PlatformClient(apiKey, organizationId, environment); + } - /** - * Create or update a security identity. See [Adding a Single Security Identity](https://docs.coveo.com/en/167) and [Security Identity Models](https://docs.coveo.com/en/139). - * - * @param securityProviderId - * @param securityIdentityModel - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse createOrUpdateSecurityIdentity(String securityProviderId, SecurityIdentityModel securityIdentityModel) throws IOException, InterruptedException { - return this.platformClient.createOrUpdateSecurityIdentity(securityProviderId, securityIdentityModel); - } + /** + * Create a new push source. + * + * @param name The name of the source to create + * @param sourceVisibility The security option that should be applied to the content of the + * source. See [Content Security](https://docs.coveo.com/en/1779). + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse create(String name, SourceVisibility sourceVisibility) + throws IOException, InterruptedException { + return this.platformClient.createSource(name, SourceType.PUSH, sourceVisibility); + } - /** - * Create or update a security identity alias. See [Adding a Single Alias](https://docs.coveo.com/en/142) and [User Alias Definition Examples](https://docs.coveo.com/en/46). - * - * @param securityProviderId - * @param securityIdentityAliasModel - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse createOrUpdateSecurityIdentityAlias(String securityProviderId, SecurityIdentityAliasModel securityIdentityAliasModel) throws IOException, InterruptedException { - return this.platformClient.createOrUpdateSecurityIdentityAlias(securityProviderId, securityIdentityAliasModel); - } + /** + * Create or update a security identity. See [Adding a Single Security + * Identity](https://docs.coveo.com/en/167) and [Security Identity + * Models](https://docs.coveo.com/en/139). + * + * @param securityProviderId + * @param securityIdentityModel + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse createOrUpdateSecurityIdentity( + String securityProviderId, SecurityIdentityModel securityIdentityModel) + throws IOException, InterruptedException { + return this.platformClient.createOrUpdateSecurityIdentity( + securityProviderId, securityIdentityModel); + } - /** - * Delete a security identity. See [Disabling a Single Security Identity](https://docs.coveo.com/en/84). - * - * @param securityProviderId - * @param securityIdentityDelete - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse deleteSecurityIdentity(String securityProviderId, SecurityIdentityDelete securityIdentityDelete) throws IOException, InterruptedException { - return this.platformClient.deleteSecurityIdentity(securityProviderId, securityIdentityDelete); - } + /** + * Create or update a security identity alias. See [Adding a Single + * Alias](https://docs.coveo.com/en/142) and [User Alias Definition + * Examples](https://docs.coveo.com/en/46). + * + * @param securityProviderId + * @param securityIdentityAliasModel + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse createOrUpdateSecurityIdentityAlias( + String securityProviderId, SecurityIdentityAliasModel securityIdentityAliasModel) + throws IOException, InterruptedException { + return this.platformClient.createOrUpdateSecurityIdentityAlias( + securityProviderId, securityIdentityAliasModel); + } - /** - * Update the status of a Push source. See [Updating the Status of a Push Source](https://docs.coveo.com/en/35). - * - * @param sourceId - * @param status - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse updateSourceStatus(String sourceId, PushAPIStatus status) throws IOException, InterruptedException { - return this.platformClient.updateSourceStatus(sourceId, status); - } + /** + * Delete a security identity. See [Disabling a Single Security + * Identity](https://docs.coveo.com/en/84). + * + * @param securityProviderId + * @param securityIdentityDelete + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse deleteSecurityIdentity( + String securityProviderId, SecurityIdentityDelete securityIdentityDelete) + throws IOException, InterruptedException { + return this.platformClient.deleteSecurityIdentity(securityProviderId, securityIdentityDelete); + } - /** - * Delete old security identities. See [Disabling Old Security Identities](https://docs.coveo.com/en/33). - * - * @param securityProviderId - * @param batchDelete - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse deleteOldSecurityIdentities(String securityProviderId, SecurityIdentityDeleteOptions batchDelete) throws IOException, InterruptedException { - return this.platformClient.deleteOldSecurityIdentities(securityProviderId, batchDelete); - } + /** + * Update the status of a Push source. See [Updating the Status of a Push + * Source](https://docs.coveo.com/en/35). + * + * @param sourceId + * @param status + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse updateSourceStatus(String sourceId, PushAPIStatus status) + throws IOException, InterruptedException { + return this.platformClient.updateSourceStatus(sourceId, status); + } - /** - * Manage batches of security identities. See [Manage Batches of Security Identities](https://docs.coveo.com/en/55). - * - * @param securityProviderId - * @param batchConfig - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse manageSecurityIdentities(String securityProviderId, SecurityIdentityBatchConfig batchConfig) throws IOException, InterruptedException { - return this.platformClient.manageSecurityIdentities(securityProviderId, batchConfig); - } + /** + * Delete old security identities. See [Disabling Old Security + * Identities](https://docs.coveo.com/en/33). + * + * @param securityProviderId + * @param batchDelete + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse deleteOldSecurityIdentities( + String securityProviderId, SecurityIdentityDeleteOptions batchDelete) + throws IOException, InterruptedException { + return this.platformClient.deleteOldSecurityIdentities(securityProviderId, batchDelete); + } - /** - * Adds or updates an individual item in a push source. See [Adding a Single Item in a Push Source](https://docs.coveo.com/en/133). - * - * @param sourceId - * @param docBuilder - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse addOrUpdateDocument(String sourceId, DocumentBuilder docBuilder) throws IOException, InterruptedException { - CompressionType compressionType = docBuilder.getDocument().compressedBinaryData != null ? docBuilder.getDocument().compressedBinaryData.getCompressionType() : CompressionType.UNCOMPRESSED; - return this.platformClient.pushDocument(sourceId, docBuilder.marshal(), docBuilder.getDocument().uri, compressionType); - } + /** + * Manage batches of security identities. See [Manage Batches of Security + * Identities](https://docs.coveo.com/en/55). + * + * @param securityProviderId + * @param batchConfig + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse manageSecurityIdentities( + String securityProviderId, SecurityIdentityBatchConfig batchConfig) + throws IOException, InterruptedException { + return this.platformClient.manageSecurityIdentities(securityProviderId, batchConfig); + } - /** - * Deletes a specific item from a Push source. Optionally, the child items of that item can also be deleted. See [Deleting an Item in a Push Source](https://docs.coveo.com/en/171). - * - * @param sourceId - * @param documentId - * @param deleteChildren - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse deleteDocument(String sourceId, String documentId, Boolean deleteChildren) throws IOException, InterruptedException { - return this.platformClient.deleteDocument(sourceId, documentId, deleteChildren); - } + /** + * Adds or updates an individual item in a push source. See [Adding a Single Item in a Push + * Source](https://docs.coveo.com/en/133). + * + * @param sourceId + * @param docBuilder + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse addOrUpdateDocument(String sourceId, DocumentBuilder docBuilder) + throws IOException, InterruptedException { + CompressionType compressionType = + docBuilder.getDocument().compressedBinaryData != null + ? docBuilder.getDocument().compressedBinaryData.getCompressionType() + : CompressionType.UNCOMPRESSED; + return this.platformClient.pushDocument( + sourceId, docBuilder.marshal(), docBuilder.getDocument().uri, compressionType); + } - /** - * Manage batches of items in a push source. See [Manage Batches of Items in a Push Source](https://docs.coveo.com/en/90) - * - * @param sourceId - * @param batchUpdate - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse batchUpdateDocuments(String sourceId, BatchUpdate batchUpdate) throws IOException, InterruptedException { - HttpResponse resFileContainer = this.platformClient.createFileContainer(); - FileContainer fileContainer = new Gson().fromJson(resFileContainer.body(), FileContainer.class); - this.platformClient.uploadContentToFileContainer(fileContainer, new Gson().toJson(batchUpdate.marshal())); - return this.platformClient.pushFileContainerContent(sourceId, fileContainer); - } + /** + * Deletes a specific item from a Push source. Optionally, the child items of that item can also + * be deleted. See [Deleting an Item in a Push Source](https://docs.coveo.com/en/171). + * + * @param sourceId + * @param documentId + * @param deleteChildren + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse deleteDocument( + String sourceId, String documentId, Boolean deleteChildren) + throws IOException, InterruptedException { + return this.platformClient.deleteDocument(sourceId, documentId, deleteChildren); + } - /** - * Manages pushing batches of Security Identities to a File Container, then into Coveo. See [Manage Batches of Security Identities](https://docs.coveo.com/en/55) - * - * @param securityProviderId - * @param batchIdentity - * @return - * @throws IOException - * @throws InterruptedException - */ - public SecurityIdentityBatchResponse batchUpdateSecurityIdentities(String securityProviderId, BatchIdentity batchIdentity) throws IOException, InterruptedException { - SecurityIdentityBatchResponse securityIdentityBatchResponse = new SecurityIdentityBatchResponse(); - HttpResponse resFileContainer = this.platformClient.createFileContainer(); - FileContainer fileContainer = new Gson().fromJson(resFileContainer.body(), FileContainer.class); - String batchIdJson = new Gson().toJson(batchIdentity.marshal()); - securityIdentityBatchResponse.s3Response = this.platformClient.uploadContentToFileContainer(fileContainer, batchIdJson); - if (securityIdentityBatchResponse.s3Response.statusCode() >= 200 && securityIdentityBatchResponse.s3Response.statusCode() <= 299) { //maybe just 200 or 202 - SecurityIdentityBatchConfig batchConfig = new SecurityIdentityBatchConfig(fileContainer.fileId, 0l); - securityIdentityBatchResponse.batchResponse = this.manageSecurityIdentities(securityProviderId, batchConfig); - } - return securityIdentityBatchResponse; - } + /** + * Manage batches of items in a push source. See [Manage Batches of Items in a Push + * Source](https://docs.coveo.com/en/90) + * + * @param sourceId + * @param batchUpdate + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse batchUpdateDocuments(String sourceId, BatchUpdate batchUpdate) + throws IOException, InterruptedException { + HttpResponse resFileContainer = this.platformClient.createFileContainer(); + FileContainer fileContainer = new Gson().fromJson(resFileContainer.body(), FileContainer.class); + this.platformClient.uploadContentToFileContainer( + fileContainer, new Gson().toJson(batchUpdate.marshal())); + return this.platformClient.pushFileContainerContent(sourceId, fileContainer); + } - /** - * Creates a File Container. [Creating a File Container](https://docs.coveo.com/en/43) - * - * @return - * @throws IOException - * @throws InterruptedException - */ - public FileContainer createFileContainer() throws IOException, InterruptedException { - HttpResponse resFileContainer = this.platformClient.createFileContainer(); - return new Gson().fromJson(resFileContainer.body(), FileContainer.class); + /** + * Manages pushing batches of Security Identities to a File Container, then into Coveo. See + * [Manage Batches of Security Identities](https://docs.coveo.com/en/55) + * + * @param securityProviderId + * @param batchIdentity + * @return + * @throws IOException + * @throws InterruptedException + */ + public SecurityIdentityBatchResponse batchUpdateSecurityIdentities( + String securityProviderId, BatchIdentity batchIdentity) + throws IOException, InterruptedException { + SecurityIdentityBatchResponse securityIdentityBatchResponse = + new SecurityIdentityBatchResponse(); + HttpResponse resFileContainer = this.platformClient.createFileContainer(); + FileContainer fileContainer = new Gson().fromJson(resFileContainer.body(), FileContainer.class); + String batchIdJson = new Gson().toJson(batchIdentity.marshal()); + securityIdentityBatchResponse.s3Response = + this.platformClient.uploadContentToFileContainer(fileContainer, batchIdJson); + if (securityIdentityBatchResponse.s3Response.statusCode() >= 200 + && securityIdentityBatchResponse.s3Response.statusCode() <= 299) { // maybe just 200 or 202 + SecurityIdentityBatchConfig batchConfig = + new SecurityIdentityBatchConfig(fileContainer.fileId, 0l); + securityIdentityBatchResponse.batchResponse = + this.manageSecurityIdentities(securityProviderId, batchConfig); } + return securityIdentityBatchResponse; + } - /** - * Push file to a File Container. [Using the compressedBinaryDataFileId Property](https://docs.coveo.com/en/69) - * - * @param fileContainer - * @param fileAsBytes - * @return - * @throws IOException - * @throws InterruptedException - */ - public HttpResponse pushBinaryToFileContainer(FileContainer fileContainer, byte[] fileAsBytes) throws IOException, InterruptedException { - return this.platformClient.pushBinaryToFileContainer(fileContainer, fileAsBytes); - } + /** + * Creates a File Container. [Creating a File Container](https://docs.coveo.com/en/43) + * + * @return + * @throws IOException + * @throws InterruptedException + */ + public FileContainer createFileContainer() throws IOException, InterruptedException { + HttpResponse resFileContainer = this.platformClient.createFileContainer(); + return new Gson().fromJson(resFileContainer.body(), FileContainer.class); + } + + /** + * Push file to a File Container. [Using the compressedBinaryDataFileId + * Property](https://docs.coveo.com/en/69) + * + * @param fileContainer + * @param fileAsBytes + * @return + * @throws IOException + * @throws InterruptedException + */ + public HttpResponse pushBinaryToFileContainer( + FileContainer fileContainer, byte[] fileAsBytes) throws IOException, InterruptedException { + return this.platformClient.pushBinaryToFileContainer(fileContainer, fileAsBytes); + } } diff --git a/src/main/java/com/coveo/pushapiclient/SourceType.java b/src/main/java/com/coveo/pushapiclient/SourceType.java index 3251aa46..d587dcaf 100644 --- a/src/main/java/com/coveo/pushapiclient/SourceType.java +++ b/src/main/java/com/coveo/pushapiclient/SourceType.java @@ -1,39 +1,42 @@ package com.coveo.pushapiclient; -public enum SourceType implements SourceTypeInterface{ - PUSH{ - public String toString() { - return "PUSH"; - } - public boolean isPushEnabled(){ return true;} - - @Override - public boolean isStreamEnabled() { - return false; - } - - }, - CATALOG{ - public String toString() { - return "CATALOG"; - } - - @Override - public boolean isPushEnabled() { - return true; - } - - @Override - public boolean isStreamEnabled() { - return true; - } - }, +public enum SourceType implements SourceTypeInterface { + PUSH { + public String toString() { + return "PUSH"; + } + + public boolean isPushEnabled() { + return true; + } + + @Override + public boolean isStreamEnabled() { + return false; + } + }, + CATALOG { + public String toString() { + return "CATALOG"; + } + + @Override + public boolean isPushEnabled() { + return true; + } + + @Override + public boolean isStreamEnabled() { + return true; + } + }, } interface SourceTypeInterface { - String toString(); - boolean isPushEnabled(); - boolean isStreamEnabled(); + String toString(); + boolean isPushEnabled(); + + boolean isStreamEnabled(); } diff --git a/src/main/java/com/coveo/pushapiclient/SourceVisibility.java b/src/main/java/com/coveo/pushapiclient/SourceVisibility.java index 416a1233..bedaa299 100644 --- a/src/main/java/com/coveo/pushapiclient/SourceVisibility.java +++ b/src/main/java/com/coveo/pushapiclient/SourceVisibility.java @@ -1,31 +1,26 @@ package com.coveo.pushapiclient; /** - * SourceVisibility controls the content security option that should be applied to the items in a source. See https://docs.coveo.com/en/1779/index-content/content-security + * SourceVisibility controls the content security option that should be applied to the items in a + * source. See https://docs.coveo.com/en/1779/index-content/content-security */ public enum SourceVisibility { - /** - * Items can be accessed by the source owner only. - */ - PRIVATE { - public String toString() { - return "PRIVATE"; - } - }, - /** - * Items can be accessed by allowed users only. - */ - SECURED { - public String toString() { - return "SECURED"; - } - }, - /** - * Items can be accessed by any user. - */ - SHARED { - public String toString() { - return "SHARED"; - } + /** Items can be accessed by the source owner only. */ + PRIVATE { + public String toString() { + return "PRIVATE"; } + }, + /** Items can be accessed by allowed users only. */ + SECURED { + public String toString() { + return "SECURED"; + } + }, + /** Items can be accessed by any user. */ + SHARED { + public String toString() { + return "SHARED"; + } + } } diff --git a/src/main/java/com/coveo/pushapiclient/StreamEnabledSource.java b/src/main/java/com/coveo/pushapiclient/StreamEnabledSource.java index b04912bf..a35e1be9 100644 --- a/src/main/java/com/coveo/pushapiclient/StreamEnabledSource.java +++ b/src/main/java/com/coveo/pushapiclient/StreamEnabledSource.java @@ -1,6 +1,4 @@ package com.coveo.pushapiclient; // Marker Interface -public interface StreamEnabledSource extends BaseSource { - -} +public interface StreamEnabledSource extends BaseSource {} diff --git a/src/main/java/com/coveo/pushapiclient/StreamResponse.java b/src/main/java/com/coveo/pushapiclient/StreamResponse.java index 61f2ceb7..af0015c9 100644 --- a/src/main/java/com/coveo/pushapiclient/StreamResponse.java +++ b/src/main/java/com/coveo/pushapiclient/StreamResponse.java @@ -3,9 +3,8 @@ import java.util.Map; public class StreamResponse { - public String uploadUri; - public String fileId; - public String streamId; - public Map requiredHeaders; - + public String uploadUri; + public String fileId; + public String streamId; + public Map requiredHeaders; } diff --git a/src/main/java/com/coveo/pushapiclient/StreamService.java b/src/main/java/com/coveo/pushapiclient/StreamService.java index b9212e20..a536ded4 100644 --- a/src/main/java/com/coveo/pushapiclient/StreamService.java +++ b/src/main/java/com/coveo/pushapiclient/StreamService.java @@ -1,116 +1,112 @@ package com.coveo.pushapiclient; -import java.io.IOException; -import java.net.http.HttpResponse; - import com.coveo.pushapiclient.exceptions.NoOpenStreamException; import com.google.gson.Gson; +import java.io.IOException; +import java.net.http.HttpResponse; // TODO: LENS-851 - Make public class StreamService { - private final StreamEnabledSource source; - private final PlatformClient platformClient; - private StreamServiceInternal service; - private String streamId; - private DocumentUploadQueue queue; - - /** - * Creates a service to stream your documents to the provided source by - * interacting with the Stream API. - * - *

- * To perform full document - * updates, use the {@PushService}, since pushing documents with the - * {@StreamService} is equivalent to triggering a full source rebuild. The - * {@StreamService} can also be used for an initial catalog upload. - * - * @param source The source to which you want to send your documents. - */ - public StreamService(StreamEnabledSource source) { - String apiKey = source.getApiKey(); - String organizationId = source.getOrganizationId(); - PlatformUrl platformUrl = source.getPlatformUrl(); - UploadStrategy uploader = this.getUploadStrategy(); - - this.source = source; - this.queue = new DocumentUploadQueue(uploader); - this.platformClient = new PlatformClient(apiKey, organizationId, platformUrl); - this.service = new StreamServiceInternal(this.source, this.queue, this.platformClient); - } + private final StreamEnabledSource source; + private final PlatformClient platformClient; + private StreamServiceInternal service; + private String streamId; + private DocumentUploadQueue queue; - /** - * Adds documents to the previously specified source. - * This function will open a stream before uploading documents into it. - * - *

- * If called several times, the service will automatically batch documents and - * create new stream chunks whenever the data payload exceeds the - * batch size limit - * set for the Stream API. - * - *

- * Once there are no more documents to add, it is important to call the {@link StreamService#close} function - * in order to send any buffered documents and close the open stream. - * Otherwise, changes will not be reflected in the index. - * - *

- *

-     * {@code
-     * //...
-     * StreamService service = new StreamService(source));
-     * for (DocumentBuilder document : fictionalDocumentList) {
-     *     service.add(document);
-     * }
-     * service.close(document);
-     * 
- * - *

- * For more code samples, visit Stream data to your catalog source - * - * @param document The documentBuilder to add to your source - * @throws InterruptedException - * @throws IOException - */ - public void add(DocumentBuilder document) throws IOException, InterruptedException { - this.service.add(document); - } + /** + * Creates a service to stream your documents to the provided source by interacting with the + * Stream API. + * + *

To perform full document updates, use the + * {@PushService}, since pushing documents with the {@StreamService} is equivalent to triggering a + * full source rebuild. The {@StreamService} can also be used for an initial catalog upload. + * + * @param source The source to which you want to send your documents. + */ + public StreamService(StreamEnabledSource source) { + String apiKey = source.getApiKey(); + String organizationId = source.getOrganizationId(); + PlatformUrl platformUrl = source.getPlatformUrl(); + UploadStrategy uploader = this.getUploadStrategy(); - /** - * Sends any buffered documents and closes the stream. - * - *

- * Upon invoking this method, any indexed items not added through this {@link StreamService} instance will be removed. - * All documents added from the initialization of the service until the invocation of the {@link StreamService#close} function - * will completely replace the previous content of the source. - * - *

- * When you upload a catalog into a source, it will replace the previous content - * of the source completely. Expect a 15-minute delay for the removal of the old - * items from the index. - * - * @return - * @throws IOException - * @throws InterruptedException - * @throws NoOpenStreamException - */ - public HttpResponse close() throws IOException, InterruptedException, NoOpenStreamException { - return this.service.close(); - } + this.source = source; + this.queue = new DocumentUploadQueue(uploader); + this.platformClient = new PlatformClient(apiKey, organizationId, platformUrl); + this.service = new StreamServiceInternal(this.source, this.queue, this.platformClient); + } - private UploadStrategy getUploadStrategy() { - return (batchUpdate) -> { - String sourceId = this.getSourceId(); - HttpResponse resFileContainer = this.platformClient.requireStreamChunk(sourceId, this.streamId); - FileContainer fileContainer = new Gson().fromJson(resFileContainer.body(), FileContainer.class); - String batchUpdateJson = new Gson().toJson(batchUpdate.marshal()); - return this.platformClient.uploadContentToFileContainer(fileContainer, - batchUpdateJson); + /** + * Adds documents to the previously specified source. + * This function will open a stream before uploading documents into it. + * + *

+ * If called several times, the service will automatically batch documents and + * create new stream chunks whenever the data payload exceeds the + * batch size limit + * set for the Stream API. + * + *

+ * Once there are no more documents to add, it is important to call the {@link StreamService#close} function + * in order to send any buffered documents and close the open stream. + * Otherwise, changes will not be reflected in the index. + * + *

+ *

+   * {@code
+   * //...
+   * StreamService service = new StreamService(source));
+   * for (DocumentBuilder document : fictionalDocumentList) {
+   *     service.add(document);
+   * }
+   * service.close(document);
+   * 
+ * + *

+ * For more code samples, visit Stream data to your catalog source + * + * @param document The documentBuilder to add to your source + * @throws InterruptedException + * @throws IOException + */ + public void add(DocumentBuilder document) throws IOException, InterruptedException { + this.service.add(document); + } - }; - } + /** + * Sends any buffered documents and closes the stream. + * + *

Upon invoking this method, any indexed items not added through this {@link StreamService} + * instance will be removed. All documents added from the initialization of the service until the + * invocation of the {@link StreamService#close} function will completely replace the previous + * content of the source. + * + *

When you upload a catalog into a source, it will replace the previous content of the source + * completely. Expect a 15-minute delay for the removal of the old items from the index. + * + * @return + * @throws IOException + * @throws InterruptedException + * @throws NoOpenStreamException + */ + public HttpResponse close() + throws IOException, InterruptedException, NoOpenStreamException { + return this.service.close(); + } - private String getSourceId() { - return this.source.getId(); - } + private UploadStrategy getUploadStrategy() { + return (batchUpdate) -> { + String sourceId = this.getSourceId(); + HttpResponse resFileContainer = + this.platformClient.requireStreamChunk(sourceId, this.streamId); + FileContainer fileContainer = + new Gson().fromJson(resFileContainer.body(), FileContainer.class); + String batchUpdateJson = new Gson().toJson(batchUpdate.marshal()); + return this.platformClient.uploadContentToFileContainer(fileContainer, batchUpdateJson); + }; + } + private String getSourceId() { + return this.source.getId(); + } } diff --git a/src/main/java/com/coveo/pushapiclient/StreamServiceInternal.java b/src/main/java/com/coveo/pushapiclient/StreamServiceInternal.java index 81f47c85..b0145504 100644 --- a/src/main/java/com/coveo/pushapiclient/StreamServiceInternal.java +++ b/src/main/java/com/coveo/pushapiclient/StreamServiceInternal.java @@ -1,52 +1,50 @@ package com.coveo.pushapiclient; -import java.io.IOException; -import java.net.http.HttpResponse; - import com.coveo.pushapiclient.exceptions.NoOpenStreamException; import com.google.gson.Gson; +import java.io.IOException; +import java.net.http.HttpResponse; -/** - * For internal use only. Made to easily test the service without having to use PowerMock - */ +/** For internal use only. Made to easily test the service without having to use PowerMock */ class StreamServiceInternal { - private final StreamEnabledSource source; - private final PlatformClient platformClient; - private String streamId; - private DocumentUploadQueue queue; - - public StreamServiceInternal(StreamEnabledSource source, DocumentUploadQueue queue, PlatformClient platformClient) { - this.source = source; - this.queue = queue; - this.platformClient = platformClient; - } - - public void add(DocumentBuilder document) throws IOException, InterruptedException { - if (this.streamId == null) { - this.streamId = this.getStreamId(); - } - queue.add(document); - } - - public HttpResponse close() throws IOException, InterruptedException, NoOpenStreamException { - if (this.streamId == null) { - throw new NoOpenStreamException( - "No open stream detected. A stream will automatically be opened once you start adding documents."); - } - queue.flush(); - String sourceId = this.getSourceId(); - return this.platformClient.closeStream(sourceId, this.streamId); + private final StreamEnabledSource source; + private final PlatformClient platformClient; + private String streamId; + private DocumentUploadQueue queue; + + public StreamServiceInternal( + StreamEnabledSource source, DocumentUploadQueue queue, PlatformClient platformClient) { + this.source = source; + this.queue = queue; + this.platformClient = platformClient; + } + + public void add(DocumentBuilder document) throws IOException, InterruptedException { + if (this.streamId == null) { + this.streamId = this.getStreamId(); } - - private String getStreamId() throws IOException, InterruptedException { - String sourceId = this.getSourceId(); - HttpResponse response = this.platformClient.openStream(sourceId); - StreamResponse streamResponse = new Gson().fromJson(response.body(), StreamResponse.class); - return streamResponse.streamId; + queue.add(document); + } + + public HttpResponse close() + throws IOException, InterruptedException, NoOpenStreamException { + if (this.streamId == null) { + throw new NoOpenStreamException( + "No open stream detected. A stream will automatically be opened once you start adding documents."); } - - private String getSourceId() { - return this.source.getId(); - } - + queue.flush(); + String sourceId = this.getSourceId(); + return this.platformClient.closeStream(sourceId, this.streamId); + } + + private String getStreamId() throws IOException, InterruptedException { + String sourceId = this.getSourceId(); + HttpResponse response = this.platformClient.openStream(sourceId); + StreamResponse streamResponse = new Gson().fromJson(response.body(), StreamResponse.class); + return streamResponse.streamId; + } + + private String getSourceId() { + return this.source.getId(); + } } diff --git a/src/main/java/com/coveo/pushapiclient/UploadStrategy.java b/src/main/java/com/coveo/pushapiclient/UploadStrategy.java index e77dd01c..053f7ba6 100644 --- a/src/main/java/com/coveo/pushapiclient/UploadStrategy.java +++ b/src/main/java/com/coveo/pushapiclient/UploadStrategy.java @@ -5,5 +5,5 @@ @FunctionalInterface public interface UploadStrategy { - HttpResponse apply(BatchUpdate batchUpdate) throws IOException, InterruptedException; + HttpResponse apply(BatchUpdate batchUpdate) throws IOException, InterruptedException; } diff --git a/src/main/java/com/coveo/pushapiclient/UserSecurityIdentityBuilder.java b/src/main/java/com/coveo/pushapiclient/UserSecurityIdentityBuilder.java index 5caa6486..d713df49 100644 --- a/src/main/java/com/coveo/pushapiclient/UserSecurityIdentityBuilder.java +++ b/src/main/java/com/coveo/pushapiclient/UserSecurityIdentityBuilder.java @@ -5,82 +5,90 @@ /** * Build a security identity of type `USER`. - *

- * Typically used in conjunction with {@link DocumentBuilder#withAllowedPermissions} or {@link DocumentBuilder#withDeniedPermissions}. - *

- * See {@link SecurityIdentity}. + * + *

Typically used in conjunction with {@link DocumentBuilder#withAllowedPermissions} or {@link + * DocumentBuilder#withDeniedPermissions}. + * + *

See {@link SecurityIdentity}. */ public class UserSecurityIdentityBuilder implements SecurityIdentityBuilder { - private final String[] identities; - private final String securityProvider; + private final String[] identities; + private final String securityProvider; - public UserSecurityIdentityBuilder(String[] identities, String securityProvider) { - this.identities = identities; - this.securityProvider = securityProvider; - } + public UserSecurityIdentityBuilder(String[] identities, String securityProvider) { + this.identities = identities; + this.securityProvider = securityProvider; + } - /** - * Construct a UserSecurityIdentityBuilder for a single identity with the given security provider. - * - * @param identity - * @param securityProvider - */ - public UserSecurityIdentityBuilder(String identity, String securityProvider) { - this(new String[]{identity}, securityProvider); - } + /** + * Construct a UserSecurityIdentityBuilder for a single identity with the given security provider. + * + * @param identity + * @param securityProvider + */ + public UserSecurityIdentityBuilder(String identity, String securityProvider) { + this(new String[] {identity}, securityProvider); + } - /** - * Construct a UserSecurityIdentityBuilder for a single identity with an `Email Security Provider`. - * - * @param identity - */ - public UserSecurityIdentityBuilder(String identity) { - this(new String[]{identity}, "Email Security Provider"); - } + /** + * Construct a UserSecurityIdentityBuilder for a single identity with an `Email Security + * Provider`. + * + * @param identity + */ + public UserSecurityIdentityBuilder(String identity) { + this(new String[] {identity}, "Email Security Provider"); + } - /** - * Construct a UserSecurityIdentityBuilder for multiple identities with an `Email Security Provider`. - * - * @param identities - */ - public UserSecurityIdentityBuilder(String[] identities) { - this(identities, "Email Security Provider"); - } + /** + * Construct a UserSecurityIdentityBuilder for multiple identities with an `Email Security + * Provider`. + * + * @param identities + */ + public UserSecurityIdentityBuilder(String[] identities) { + this(identities, "Email Security Provider"); + } + public SecurityIdentity[] build() { + return new AnySecurityIdentityBuilder( + this.identities, SecurityIdentityType.USER, this.securityProvider) + .build(); + } - public SecurityIdentity[] build() { - return new AnySecurityIdentityBuilder(this.identities, SecurityIdentityType.USER, this.securityProvider).build(); - } + public String[] getIdentities() { + return identities; + } - public String[] getIdentities() { - return identities; - } + public String getSecurityProvider() { + return securityProvider; + } - public String getSecurityProvider() { - return securityProvider; - } + @Override + public String toString() { + return "UserSecurityIdentityBuilder[" + + "identities=" + + Arrays.toString(identities) + + ", securityProvider='" + + securityProvider + + '\'' + + ']'; + } - @Override - public String toString() { - return "UserSecurityIdentityBuilder[" + - "identities=" + Arrays.toString(identities) + - ", securityProvider='" + securityProvider + '\'' + - ']'; - } + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null || getClass() != obj.getClass()) return false; + UserSecurityIdentityBuilder that = (UserSecurityIdentityBuilder) obj; + return Arrays.equals(identities, that.identities) + && Objects.equals(securityProvider, that.securityProvider); + } - @Override - public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null || getClass() != obj.getClass()) return false; - UserSecurityIdentityBuilder that = (UserSecurityIdentityBuilder) obj; - return Arrays.equals(identities, that.identities) && Objects.equals(securityProvider, that.securityProvider); - } - - @Override - public int hashCode() { - int result = Objects.hash(securityProvider); - result = 31 * result + Arrays.hashCode(identities); - return result; - } + @Override + public int hashCode() { + int result = Objects.hash(securityProvider); + result = 31 * result + Arrays.hashCode(identities); + return result; + } } diff --git a/src/main/java/com/coveo/pushapiclient/VirtualGroupSecurityIdentityBuilder.java b/src/main/java/com/coveo/pushapiclient/VirtualGroupSecurityIdentityBuilder.java index a61636ae..c6cc427e 100644 --- a/src/main/java/com/coveo/pushapiclient/VirtualGroupSecurityIdentityBuilder.java +++ b/src/main/java/com/coveo/pushapiclient/VirtualGroupSecurityIdentityBuilder.java @@ -5,64 +5,70 @@ /** * Build a security identity of type `VIRTUAL_GROUP`. - *

- * Typically used in conjunction with {@link DocumentBuilder#withAllowedPermissions} or {@link DocumentBuilder#withDeniedPermissions}. - *

- * See {@link SecurityIdentity}. + * + *

Typically used in conjunction with {@link DocumentBuilder#withAllowedPermissions} or {@link + * DocumentBuilder#withDeniedPermissions}. + * + *

See {@link SecurityIdentity}. */ public class VirtualGroupSecurityIdentityBuilder implements SecurityIdentityBuilder { - private final String[] identities; - private final String securityProvider; + private final String[] identities; + private final String securityProvider; - public VirtualGroupSecurityIdentityBuilder(String[] identities, String securityProvider) { - this.identities = identities; - this.securityProvider = securityProvider; - } + public VirtualGroupSecurityIdentityBuilder(String[] identities, String securityProvider) { + this.identities = identities; + this.securityProvider = securityProvider; + } - /** - * Construct a VirtualGroupSecurityIdentityBuilder with a single identity. - * - * @param identity - * @param securityProvider - */ - public VirtualGroupSecurityIdentityBuilder(String identity, String securityProvider) { - this(new String[]{identity}, securityProvider); - } + /** + * Construct a VirtualGroupSecurityIdentityBuilder with a single identity. + * + * @param identity + * @param securityProvider + */ + public VirtualGroupSecurityIdentityBuilder(String identity, String securityProvider) { + this(new String[] {identity}, securityProvider); + } - public SecurityIdentity[] build() { - return new AnySecurityIdentityBuilder(this.identities, SecurityIdentityType.VIRTUAL_GROUP, this.securityProvider).build(); - } + public SecurityIdentity[] build() { + return new AnySecurityIdentityBuilder( + this.identities, SecurityIdentityType.VIRTUAL_GROUP, this.securityProvider) + .build(); + } - public String[] getIdentities() { - return identities; - } + public String[] getIdentities() { + return identities; + } - public String getSecurityProvider() { - return securityProvider; - } + public String getSecurityProvider() { + return securityProvider; + } - @Override - public String toString() { - return "VirtualGroupSecurityIdentityBuilder[" + - "identities=" + Arrays.toString(identities) + - ", securityProvider='" + securityProvider + '\'' + - ']'; - } + @Override + public String toString() { + return "VirtualGroupSecurityIdentityBuilder[" + + "identities=" + + Arrays.toString(identities) + + ", securityProvider='" + + securityProvider + + '\'' + + ']'; + } - @Override - public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null || getClass() != obj.getClass()) return false; - VirtualGroupSecurityIdentityBuilder that = (VirtualGroupSecurityIdentityBuilder) obj; - return Arrays.equals(identities, that.identities) && Objects.equals(securityProvider, that.securityProvider); - } + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null || getClass() != obj.getClass()) return false; + VirtualGroupSecurityIdentityBuilder that = (VirtualGroupSecurityIdentityBuilder) obj; + return Arrays.equals(identities, that.identities) + && Objects.equals(securityProvider, that.securityProvider); + } - @Override - public int hashCode() { - int result = Objects.hash(securityProvider); - result = 31 * result + Arrays.hashCode(identities); - return result; - } + @Override + public int hashCode() { + int result = Objects.hash(securityProvider); + result = 31 * result + Arrays.hashCode(identities); + return result; + } } - diff --git a/src/main/java/com/coveo/pushapiclient/exceptions/NoOpenStreamException.java b/src/main/java/com/coveo/pushapiclient/exceptions/NoOpenStreamException.java index 91b2cf3a..18489ec4 100644 --- a/src/main/java/com/coveo/pushapiclient/exceptions/NoOpenStreamException.java +++ b/src/main/java/com/coveo/pushapiclient/exceptions/NoOpenStreamException.java @@ -1,7 +1,7 @@ package com.coveo.pushapiclient.exceptions; public class NoOpenStreamException extends Exception { - public NoOpenStreamException(String errorMessage) { - super(errorMessage); - } + public NoOpenStreamException(String errorMessage) { + super(errorMessage); + } } diff --git a/src/test/java/com/coveo/pushapiclient/ApiUrlTest.java b/src/test/java/com/coveo/pushapiclient/ApiUrlTest.java index 964dcb55..c1440b5d 100644 --- a/src/test/java/com/coveo/pushapiclient/ApiUrlTest.java +++ b/src/test/java/com/coveo/pushapiclient/ApiUrlTest.java @@ -4,84 +4,98 @@ import java.net.MalformedURLException; import java.net.URL; - import org.junit.Test; public class ApiUrlTest { - @Test - public void testSourceId() throws MalformedURLException { - ApiUrl url = new ApiUrl( - new URL("https://api.cloud.coveo.com/push/v1/organizations/my-org-id/sources/my-source-id/documents")); - assertEquals(url.getSourceId(), "my-source-id"); - } - - @Test - public void testOrganizationId() throws MalformedURLException { - ApiUrl url = new ApiUrl( - new URL("https://api.cloud.coveo.com/push/v1/organizations/my-org-id/sources/my-source-id/documents")); - assertEquals(url.getOrganizationId(), "my-org-id"); - } - - @Test - public void testPlatformUrl() throws MalformedURLException { - ApiUrl defaultUrl = new ApiUrl( - new URL("https://api.cloud.coveo.com/push/v1/organizations/my-org-id/sources/my-source-id/documents")); - ApiUrl regionOnlyUrl = new ApiUrl( - new URL("https://api-au.cloud.coveo.com/push/v1/organizations/my-org-id/sources/my-source-id/documents")); - ApiUrl environmentOnlyUrl = new ApiUrl( - new URL("https://apidev.cloud.coveo.com/push/v1/organizations/my-org-id/sources/my-source-id/documents")); - ApiUrl environmentAndRegionUrl = new ApiUrl( - new URL("https://apidev-au.cloud.coveo.com/push/v1/organizations/my-org-id/sources/my-source-id/documents")); - - assertEquals(defaultUrl.getPlatformUrl().getApiUrl(), "https://api.cloud.coveo.com"); - assertEquals(regionOnlyUrl.getPlatformUrl().getApiUrl(), "https://api-au.cloud.coveo.com"); - assertEquals(environmentOnlyUrl.getPlatformUrl().getApiUrl(), "https://apidev.cloud.coveo.com"); - assertEquals(environmentAndRegionUrl.getPlatformUrl().getApiUrl(), "https://apidev-au.cloud.coveo.com"); - } - - @Test - public void testStreamApiUrl() throws MalformedURLException { - ApiUrl url = new ApiUrl( - new URL("https://apidev-au.cloud.coveo.com/push/v1/organizations/my-org-id/sources/my-source-id/stream/open")); - - assertEquals(url.getPlatformUrl().getApiUrl(), "https://apidev-au.cloud.coveo.com"); - assertEquals(url.getOrganizationId(), "my-org-id"); - assertEquals(url.getSourceId(), "my-source-id"); - } - - @Test(expected = MalformedURLException.class) - public void testInvalidEnvironmentUrl() throws MalformedURLException { + @Test + public void testSourceId() throws MalformedURLException { + ApiUrl url = new ApiUrl( - new URL("https://apifoo.cloud.coveo.com/push/v1/organizations/my-org-id/sources/my-source-id/documents")); - - } - @Test(expected = MalformedURLException.class) - public void testInvalidUrl() throws MalformedURLException { + new URL( + "https://api.cloud.coveo.com/push/v1/organizations/my-org-id/sources/my-source-id/documents")); + assertEquals(url.getSourceId(), "my-source-id"); + } + + @Test + public void testOrganizationId() throws MalformedURLException { + ApiUrl url = new ApiUrl( - new URL("https://apifoo.cloud.coveo.com/push/v1/organizations/my-org-id/sources/my-source-id/documents")); - - } - - @Test(expected = MalformedURLException.class) - public void testInvalidRegionUrl() throws MalformedURLException { + new URL( + "https://api.cloud.coveo.com/push/v1/organizations/my-org-id/sources/my-source-id/documents")); + assertEquals(url.getOrganizationId(), "my-org-id"); + } + + @Test + public void testPlatformUrl() throws MalformedURLException { + ApiUrl defaultUrl = new ApiUrl( - new URL( - "https://api-bar.cloud.coveo.com/push/v1/organizations/my-org-id/sources/my-source-id/documents")); - - } - - @Test(expected = MalformedURLException.class) - public void testInvalidPathUrl() throws MalformedURLException { + new URL( + "https://api.cloud.coveo.com/push/v1/organizations/my-org-id/sources/my-source-id/documents")); + ApiUrl regionOnlyUrl = new ApiUrl( - new URL("https://api.cloud.coveo.com/push/v1/organizations/my-org-id/providers/provider-id/mappings")); - - } - - @Test(expected = MalformedURLException.class) - public void testInvalidHostUrl() throws MalformedURLException { + new URL( + "https://api-au.cloud.coveo.com/push/v1/organizations/my-org-id/sources/my-source-id/documents")); + ApiUrl environmentOnlyUrl = new ApiUrl( - new URL("https://platform.cloud.coveo.com/push/v1/organizations/my-org-id/sources/my-source-id/documents")); - - } + new URL( + "https://apidev.cloud.coveo.com/push/v1/organizations/my-org-id/sources/my-source-id/documents")); + ApiUrl environmentAndRegionUrl = + new ApiUrl( + new URL( + "https://apidev-au.cloud.coveo.com/push/v1/organizations/my-org-id/sources/my-source-id/documents")); + + assertEquals(defaultUrl.getPlatformUrl().getApiUrl(), "https://api.cloud.coveo.com"); + assertEquals(regionOnlyUrl.getPlatformUrl().getApiUrl(), "https://api-au.cloud.coveo.com"); + assertEquals(environmentOnlyUrl.getPlatformUrl().getApiUrl(), "https://apidev.cloud.coveo.com"); + assertEquals( + environmentAndRegionUrl.getPlatformUrl().getApiUrl(), "https://apidev-au.cloud.coveo.com"); + } + + @Test + public void testStreamApiUrl() throws MalformedURLException { + ApiUrl url = + new ApiUrl( + new URL( + "https://apidev-au.cloud.coveo.com/push/v1/organizations/my-org-id/sources/my-source-id/stream/open")); + + assertEquals(url.getPlatformUrl().getApiUrl(), "https://apidev-au.cloud.coveo.com"); + assertEquals(url.getOrganizationId(), "my-org-id"); + assertEquals(url.getSourceId(), "my-source-id"); + } + + @Test(expected = MalformedURLException.class) + public void testInvalidEnvironmentUrl() throws MalformedURLException { + new ApiUrl( + new URL( + "https://apifoo.cloud.coveo.com/push/v1/organizations/my-org-id/sources/my-source-id/documents")); + } + + @Test(expected = MalformedURLException.class) + public void testInvalidUrl() throws MalformedURLException { + new ApiUrl( + new URL( + "https://apifoo.cloud.coveo.com/push/v1/organizations/my-org-id/sources/my-source-id/documents")); + } + + @Test(expected = MalformedURLException.class) + public void testInvalidRegionUrl() throws MalformedURLException { + new ApiUrl( + new URL( + "https://api-bar.cloud.coveo.com/push/v1/organizations/my-org-id/sources/my-source-id/documents")); + } + + @Test(expected = MalformedURLException.class) + public void testInvalidPathUrl() throws MalformedURLException { + new ApiUrl( + new URL( + "https://api.cloud.coveo.com/push/v1/organizations/my-org-id/providers/provider-id/mappings")); + } + + @Test(expected = MalformedURLException.class) + public void testInvalidHostUrl() throws MalformedURLException { + new ApiUrl( + new URL( + "https://platform.cloud.coveo.com/push/v1/organizations/my-org-id/sources/my-source-id/documents")); + } } diff --git a/src/test/java/com/coveo/pushapiclient/BatchUpdateRecordTest.java b/src/test/java/com/coveo/pushapiclient/BatchUpdateRecordTest.java index fefb87d3..cae85d2e 100644 --- a/src/test/java/com/coveo/pushapiclient/BatchUpdateRecordTest.java +++ b/src/test/java/com/coveo/pushapiclient/BatchUpdateRecordTest.java @@ -1,62 +1,62 @@ package com.coveo.pushapiclient; +import static org.junit.Assert.*; + import com.google.gson.Gson; import com.google.gson.JsonObject; import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.*; - public class BatchUpdateRecordTest { - private BatchUpdateRecord bur1; - private BatchUpdateRecord bur2; - private BatchUpdateRecord bur3; - private BatchUpdateRecord bur4; - - @Before - public void setUp() throws Exception { - Gson gson = new Gson(); - JsonObject json1 = gson.fromJson("{ \"key\": \"value1\" }", JsonObject.class); - JsonObject json2 = gson.fromJson("{ \"key\": \"value1\" }", JsonObject.class); - JsonObject json3 = gson.fromJson("{ \"key3\": \"value3\" }", JsonObject.class); - JsonObject json4 = gson.fromJson("{ \"key4\": \"value4\" }", JsonObject.class); - - JsonObject[] jsonArray1 = new JsonObject[] {json1, json3}; - JsonObject[] jsonArray2 = new JsonObject[] {json2, json3}; - JsonObject[] jsonArray3 = new JsonObject[] {json1, json3}; - JsonObject[] jsonArray4 = new JsonObject[] {json4, json3}; - - bur1 = new BatchUpdateRecord(jsonArray1, jsonArray2); - bur2 = new BatchUpdateRecord(jsonArray1, jsonArray2); - bur3 = new BatchUpdateRecord(jsonArray3, jsonArray4); - bur4 = bur1; - } - - @Test - public void testToString() { - assertEquals(bur1.toString(), bur1.toString()); - assertEquals(bur1.toString(), bur2.toString()); - assertEquals(bur1.toString(), bur4.toString()); - assertNotEquals(bur1.toString(), bur3.toString()); - } - - @Test - public void testEquals() { - assertTrue(bur1.equals(bur1)); - assertTrue(bur1.equals(bur2)); - assertFalse(bur1.equals(bur3)); - assertTrue(bur1.equals(bur4)); - assertFalse(bur1.equals(null)); - } - - @Test - public void testHashCode() { - assertEquals(bur1.hashCode(), bur1.hashCode()); - assertEquals(bur1.hashCode(), bur2.hashCode()); - assertEquals(bur1.hashCode(), bur4.hashCode()); - assertEquals(bur3.hashCode(), bur3.hashCode()); - assertNotEquals(bur1.hashCode(), bur3.hashCode()); - assertNotEquals(bur2.hashCode(), bur3.hashCode()); - } -} \ No newline at end of file + private BatchUpdateRecord bur1; + private BatchUpdateRecord bur2; + private BatchUpdateRecord bur3; + private BatchUpdateRecord bur4; + + @Before + public void setUp() throws Exception { + Gson gson = new Gson(); + JsonObject json1 = gson.fromJson("{ \"key\": \"value1\" }", JsonObject.class); + JsonObject json2 = gson.fromJson("{ \"key\": \"value1\" }", JsonObject.class); + JsonObject json3 = gson.fromJson("{ \"key3\": \"value3\" }", JsonObject.class); + JsonObject json4 = gson.fromJson("{ \"key4\": \"value4\" }", JsonObject.class); + + JsonObject[] jsonArray1 = new JsonObject[] {json1, json3}; + JsonObject[] jsonArray2 = new JsonObject[] {json2, json3}; + JsonObject[] jsonArray3 = new JsonObject[] {json1, json3}; + JsonObject[] jsonArray4 = new JsonObject[] {json4, json3}; + + bur1 = new BatchUpdateRecord(jsonArray1, jsonArray2); + bur2 = new BatchUpdateRecord(jsonArray1, jsonArray2); + bur3 = new BatchUpdateRecord(jsonArray3, jsonArray4); + bur4 = bur1; + } + + @Test + public void testToString() { + assertEquals(bur1.toString(), bur1.toString()); + assertEquals(bur1.toString(), bur2.toString()); + assertEquals(bur1.toString(), bur4.toString()); + assertNotEquals(bur1.toString(), bur3.toString()); + } + + @Test + public void testEquals() { + assertTrue(bur1.equals(bur1)); + assertTrue(bur1.equals(bur2)); + assertFalse(bur1.equals(bur3)); + assertTrue(bur1.equals(bur4)); + assertFalse(bur1.equals(null)); + } + + @Test + public void testHashCode() { + assertEquals(bur1.hashCode(), bur1.hashCode()); + assertEquals(bur1.hashCode(), bur2.hashCode()); + assertEquals(bur1.hashCode(), bur4.hashCode()); + assertEquals(bur3.hashCode(), bur3.hashCode()); + assertNotEquals(bur1.hashCode(), bur3.hashCode()); + assertNotEquals(bur2.hashCode(), bur3.hashCode()); + } +} diff --git a/src/test/java/com/coveo/pushapiclient/BatchUpdateTest.java b/src/test/java/com/coveo/pushapiclient/BatchUpdateTest.java index e7383bf9..26f25e40 100644 --- a/src/test/java/com/coveo/pushapiclient/BatchUpdateTest.java +++ b/src/test/java/com/coveo/pushapiclient/BatchUpdateTest.java @@ -1,83 +1,82 @@ package com.coveo.pushapiclient; -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; -public class BatchUpdateTest { - - private BatchUpdate batch1; - private BatchUpdate batch2; - private BatchUpdate batch3; - private BatchUpdate batch4; - - @Before - public void setUp() { - DocumentBuilder db1 = new DocumentBuilder("some_uri", "some_title"); - DocumentBuilder db2 = new DocumentBuilder("some_uri", "some_title"); - DocumentBuilder db3 = new DocumentBuilder("some_other_uri", "some_title"); - DocumentBuilder db4 = new DocumentBuilder("some_uri", "some_other_title"); - - List list1 = new ArrayList<>(); - list1.add(db1); - list1.add(db3); - - List list2 = new ArrayList<>(); - list2.add(db1); - list2.add(db4); - - List list3 = new ArrayList<>(); - list3.add(db2); - list3.add(db3); - list3.add(db4); - - DeleteDocument del1 = new DeleteDocument("123"); - DeleteDocument del2 = new DeleteDocument("456"); - DeleteDocument del3 = new DeleteDocument("789"); - - List delList1 = new ArrayList<>(); - delList1.add(del1); - delList1.add(del2); - - List delList2 = new ArrayList<>(); - delList2.add(del2); - delList2.add(del3); - - batch1 = new BatchUpdate(list1, delList1); - batch2 = new BatchUpdate(list1, delList1); - batch3 = new BatchUpdate(list2, delList2); - batch4 = batch1; - } - - @Test - public void testToString() { - assertEquals(batch1.toString(), batch1.toString()); - assertEquals(batch1.toString(), batch2.toString()); - assertEquals(batch1.toString(), batch4.toString()); - assertNotEquals(batch1.toString(), batch3.toString()); - } +import java.util.ArrayList; +import java.util.List; +import org.junit.Before; +import org.junit.Test; - @Test - public void testEquals() { - assertFalse(batch1.equals(null)); - assertTrue(batch1.equals(batch1)); - assertTrue(batch1.equals(batch2)); - assertTrue(batch1.equals(batch4)); - assertFalse(batch1.equals(batch3)); - } +public class BatchUpdateTest { - @Test - public void testHashCode() { - assertEquals(batch1.hashCode(), batch1.hashCode()); - assertEquals(batch1.hashCode(), batch2.hashCode()); - assertEquals(batch1.hashCode(), batch4.hashCode()); - assertNotEquals(batch1.hashCode(), batch3.hashCode()); - } -} \ No newline at end of file + private BatchUpdate batch1; + private BatchUpdate batch2; + private BatchUpdate batch3; + private BatchUpdate batch4; + + @Before + public void setUp() { + DocumentBuilder db1 = new DocumentBuilder("some_uri", "some_title"); + DocumentBuilder db2 = new DocumentBuilder("some_uri", "some_title"); + DocumentBuilder db3 = new DocumentBuilder("some_other_uri", "some_title"); + DocumentBuilder db4 = new DocumentBuilder("some_uri", "some_other_title"); + + List list1 = new ArrayList<>(); + list1.add(db1); + list1.add(db3); + + List list2 = new ArrayList<>(); + list2.add(db1); + list2.add(db4); + + List list3 = new ArrayList<>(); + list3.add(db2); + list3.add(db3); + list3.add(db4); + + DeleteDocument del1 = new DeleteDocument("123"); + DeleteDocument del2 = new DeleteDocument("456"); + DeleteDocument del3 = new DeleteDocument("789"); + + List delList1 = new ArrayList<>(); + delList1.add(del1); + delList1.add(del2); + + List delList2 = new ArrayList<>(); + delList2.add(del2); + delList2.add(del3); + + batch1 = new BatchUpdate(list1, delList1); + batch2 = new BatchUpdate(list1, delList1); + batch3 = new BatchUpdate(list2, delList2); + batch4 = batch1; + } + + @Test + public void testToString() { + assertEquals(batch1.toString(), batch1.toString()); + assertEquals(batch1.toString(), batch2.toString()); + assertEquals(batch1.toString(), batch4.toString()); + assertNotEquals(batch1.toString(), batch3.toString()); + } + + @Test + public void testEquals() { + assertFalse(batch1.equals(null)); + assertTrue(batch1.equals(batch1)); + assertTrue(batch1.equals(batch2)); + assertTrue(batch1.equals(batch4)); + assertFalse(batch1.equals(batch3)); + } + + @Test + public void testHashCode() { + assertEquals(batch1.hashCode(), batch1.hashCode()); + assertEquals(batch1.hashCode(), batch2.hashCode()); + assertEquals(batch1.hashCode(), batch4.hashCode()); + assertNotEquals(batch1.hashCode(), batch3.hashCode()); + } +} diff --git a/src/test/java/com/coveo/pushapiclient/CompressedBinaryDataTest.java b/src/test/java/com/coveo/pushapiclient/CompressedBinaryDataTest.java index 231307d9..df555f3b 100644 --- a/src/test/java/com/coveo/pushapiclient/CompressedBinaryDataTest.java +++ b/src/test/java/com/coveo/pushapiclient/CompressedBinaryDataTest.java @@ -1,55 +1,55 @@ package com.coveo.pushapiclient; +import static org.junit.Assert.*; + import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.*; - public class CompressedBinaryDataTest { - private CompressedBinaryData data1; - private CompressedBinaryData data2; - - private CompressedBinaryData data3; - private CompressedBinaryData data4; - private CompressedBinaryData data5; - - @Before - public void setUp() { - data1 = new CompressedBinaryData("some_data", CompressionType.UNCOMPRESSED); - data2 = new CompressedBinaryData("some_data", CompressionType.UNCOMPRESSED); - - data3 = new CompressedBinaryData("some_other_data", CompressionType.UNCOMPRESSED); - data4 = new CompressedBinaryData("some_data", CompressionType.GZIP); - data5 = data1; - } - - @Test - public void testToString() { - assertEquals(data1.toString(), data1.toString()); - assertEquals(data1.toString(), data2.toString()); - assertEquals(data1.toString(), data5.toString()); - } - - @Test - public void testEquals() { - assertTrue(data1.equals(data1)); - assertTrue(data1.equals(data2)); - assertFalse(data1.equals(data3)); - assertFalse(data1.equals(data4)); - assertTrue(data1.equals(data5)); - assertFalse(data1.equals(null)); - } - - @Test - public void testHashCode() { - assertEquals(data1.hashCode(), data1.hashCode()); - assertEquals(data3.hashCode(), data3.hashCode()); - assertEquals(data4.hashCode(), data4.hashCode()); - assertEquals(data1.hashCode(), data2.hashCode()); - assertEquals(data1.hashCode(), data5.hashCode()); - assertNotEquals(data1.hashCode(), data3.hashCode()); - assertNotEquals(data1.hashCode(), data4.hashCode()); - assertNotEquals(data3.hashCode(), data4.hashCode()); - } -} \ No newline at end of file + private CompressedBinaryData data1; + private CompressedBinaryData data2; + + private CompressedBinaryData data3; + private CompressedBinaryData data4; + private CompressedBinaryData data5; + + @Before + public void setUp() { + data1 = new CompressedBinaryData("some_data", CompressionType.UNCOMPRESSED); + data2 = new CompressedBinaryData("some_data", CompressionType.UNCOMPRESSED); + + data3 = new CompressedBinaryData("some_other_data", CompressionType.UNCOMPRESSED); + data4 = new CompressedBinaryData("some_data", CompressionType.GZIP); + data5 = data1; + } + + @Test + public void testToString() { + assertEquals(data1.toString(), data1.toString()); + assertEquals(data1.toString(), data2.toString()); + assertEquals(data1.toString(), data5.toString()); + } + + @Test + public void testEquals() { + assertTrue(data1.equals(data1)); + assertTrue(data1.equals(data2)); + assertFalse(data1.equals(data3)); + assertFalse(data1.equals(data4)); + assertTrue(data1.equals(data5)); + assertFalse(data1.equals(null)); + } + + @Test + public void testHashCode() { + assertEquals(data1.hashCode(), data1.hashCode()); + assertEquals(data3.hashCode(), data3.hashCode()); + assertEquals(data4.hashCode(), data4.hashCode()); + assertEquals(data1.hashCode(), data2.hashCode()); + assertEquals(data1.hashCode(), data5.hashCode()); + assertNotEquals(data1.hashCode(), data3.hashCode()); + assertNotEquals(data1.hashCode(), data4.hashCode()); + assertNotEquals(data3.hashCode(), data4.hashCode()); + } +} diff --git a/src/test/java/com/coveo/pushapiclient/DocumentBuilderTest.java b/src/test/java/com/coveo/pushapiclient/DocumentBuilderTest.java index 43f3cf61..33f42ab5 100644 --- a/src/test/java/com/coveo/pushapiclient/DocumentBuilderTest.java +++ b/src/test/java/com/coveo/pushapiclient/DocumentBuilderTest.java @@ -1,378 +1,369 @@ package com.coveo.pushapiclient; -import org.joda.time.DateTime; -import org.joda.time.format.ISODateTimeFormat; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.*; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.Date; import java.util.HashMap; - -import static org.junit.Assert.*; +import org.joda.time.DateTime; +import org.joda.time.format.ISODateTimeFormat; +import org.junit.Before; +import org.junit.Test; public class DocumentBuilderTest { - private DocumentBuilder docBuilder; - - @Before - public void setUp() { - docBuilder = new DocumentBuilder("the_uri", "the_title"); - } - - @Test - public void testWithData() { - docBuilder.withData("this is searchable"); - assertEquals( - "withData should marshal correctly", - "this is searchable", - docBuilder.marshalJsonObject().get("data").getAsString() - ); - } - - @Test - public void testWithDatePlainDateObject() { - Date d = new Date(); - DateTime dt = new DateTime(d); - docBuilder.withDate(d); - assertEquals( - "withDate with a plain java date object should marshal correctly", - dt.toString(ISODateTimeFormat.dateTime()), - docBuilder.marshalJsonObject().get("date").getAsString() - ); - } - - @Test - public void testWithDateLong() { - docBuilder.withDate(12345l); - DateTime dt = new DateTime(12345l); - assertEquals( - "withDate with a long should marshal correctly", - dt.toString(ISODateTimeFormat.dateTime()), - docBuilder.marshalJsonObject().get("date").getAsString() - ); - } - - @Test - public void testWithDateJodatime() { - DateTime dt = new DateTime(); - docBuilder.withDate(dt); - assertEquals( - "withDate with jodatime should marshal correctly", - dt.toString(ISODateTimeFormat.dateTime()), - docBuilder.marshalJsonObject().get("date").getAsString() - ); - } - - @Test - public void testWithDateString() { - DateTime dt = new DateTime("2015-01-01"); - docBuilder.withDate("2015-01-01"); - assertEquals( - "withDate with string date should marshal correctly", - dt.toString(ISODateTimeFormat.dateTime()), - docBuilder.marshalJsonObject().get("date").getAsString() - ); - } - - @Test - public void withModifiedDatePlainDateObject() { - Date d = new Date(); - DateTime dt = new DateTime(d); - docBuilder.withModifiedDate(d); - assertEquals( - "withModifiedDate with a plain java date object should marshal correctly", - dt.toString(ISODateTimeFormat.dateTime()), - docBuilder.marshalJsonObject().get("modifiedDate").getAsString() - ); - } - - @Test - public void testWithModifiedDateLong() { - docBuilder.withModifiedDate(12345l); - DateTime dt = new DateTime(12345l); - assertEquals( - "withDate with a long should marshal correctly", - dt.toString(ISODateTimeFormat.dateTime()), - docBuilder.marshalJsonObject().get("modifiedDate").getAsString() - ); - } - - @Test - public void testWithModifiedDateJodatime() { - DateTime dt = new DateTime(); - docBuilder.withModifiedDate(dt); - assertEquals( - "withDate with jodatime should marshal correctly", - dt.toString(ISODateTimeFormat.dateTime()), - docBuilder.marshalJsonObject().get("modifiedDate").getAsString() - ); - } - - public void testWithModifiedDateString() { - DateTime dt = new DateTime("2015-01-01"); - docBuilder.withModifiedDate("2015-01-01"); - assertEquals( - "withDate with string date should marshal correctly", - dt.toString(ISODateTimeFormat.dateTime()), - docBuilder.marshalJsonObject().get("modifiedDate").getAsString() - ); - } - - @Test - public void testWithPermanentId() { - docBuilder.withPermanentId("the_permanent_id"); - assertEquals( - "with permanentId should marshal correctly", - "the_permanent_id", - docBuilder.marshalJsonObject().get("permanentId").getAsString() - ); - } - - @Test - public void testWithPermanentIdGeneration() { - docBuilder = new DocumentBuilder("https://foo.com", "bar"); - assertEquals( - "permanentId should be generated automatically if not set", - "aa2e0510b66edff7f05e2b30d4f1b3a4b5481c06b69f41751c54675c5afb", - docBuilder.marshalJsonObject().get("permanentId").getAsString() - ); - } - - @Test - public void testWithCompressedBinaryData() { - String encoded = Base64.getEncoder().encodeToString("binary data encoded".getBytes(StandardCharsets.UTF_8)); - docBuilder.withCompressedBinaryData(new CompressedBinaryData(encoded, CompressionType.UNCOMPRESSED)); - String decoded = new String(Base64.getDecoder().decode(docBuilder.marshalJsonObject().get("compressedBinaryData").getAsString().getBytes(StandardCharsets.UTF_8))); - - assertEquals("withCompressedBinaryData should marshal correctly", "binary data encoded", decoded); - } - - @Test - public void testWithFileExtension() { - docBuilder.withFileExtension(".txt"); - - assertEquals( - "withFileExtension should marshal correctly", - ".txt", - docBuilder.marshalJsonObject().get("fileExtension").getAsString() - ); - } - - @Test(expected = RuntimeException.class) - public void testWithInvalidFileExtension() { - docBuilder.withFileExtension("this should blow up"); - } - - @Test - public void testWithParentID() { - docBuilder.withParentID("the_parent_id"); - - assertEquals( - "withParentId should marshal correctly", - "the_parent_id", - docBuilder.marshalJsonObject().get("parentId").getAsString() - ); - } - - @Test - public void testWithClickableUri() { - docBuilder.withClickableUri("the click uri"); - - assertEquals("withClickableUri should marshal correctly", - "the click uri", - docBuilder.marshalJsonObject().get("clickableUri").getAsString() - ); - } - - @Test - public void testWithAuthor() { - docBuilder.withAuthor("the author"); - - assertEquals("withAuthor should marshal correctly", - "the author", - docBuilder.marshalJsonObject().get("author").getAsString() - ); - } - - @Test - public void testWithMetadataValue() { - docBuilder.withMetadataValue("the_key", "the_value"); - assertEquals( - "withMetadataValue should marshal correctly", - "the_value", - docBuilder.marshalJsonObject().get("the_key").getAsString() - ); - assertNull( - "withMetadataValue should remove metadata key when marshaling", - docBuilder.marshalJsonObject().get("metadata") - ); - } - - @Test(expected = RuntimeException.class) - public void testWithInvalidMetadataValue() { - docBuilder.withMetadataValue("data", "this should blow up"); - } - - @Test - public void testWithMetadata() { - docBuilder.withMetadata(new HashMap<>() {{ + private DocumentBuilder docBuilder; + + @Before + public void setUp() { + docBuilder = new DocumentBuilder("the_uri", "the_title"); + } + + @Test + public void testWithData() { + docBuilder.withData("this is searchable"); + assertEquals( + "withData should marshal correctly", + "this is searchable", + docBuilder.marshalJsonObject().get("data").getAsString()); + } + + @Test + public void testWithDatePlainDateObject() { + Date d = new Date(); + DateTime dt = new DateTime(d); + docBuilder.withDate(d); + assertEquals( + "withDate with a plain java date object should marshal correctly", + dt.toString(ISODateTimeFormat.dateTime()), + docBuilder.marshalJsonObject().get("date").getAsString()); + } + + @Test + public void testWithDateLong() { + docBuilder.withDate(12345l); + DateTime dt = new DateTime(12345l); + assertEquals( + "withDate with a long should marshal correctly", + dt.toString(ISODateTimeFormat.dateTime()), + docBuilder.marshalJsonObject().get("date").getAsString()); + } + + @Test + public void testWithDateJodatime() { + DateTime dt = new DateTime(); + docBuilder.withDate(dt); + assertEquals( + "withDate with jodatime should marshal correctly", + dt.toString(ISODateTimeFormat.dateTime()), + docBuilder.marshalJsonObject().get("date").getAsString()); + } + + @Test + public void testWithDateString() { + DateTime dt = new DateTime("2015-01-01"); + docBuilder.withDate("2015-01-01"); + assertEquals( + "withDate with string date should marshal correctly", + dt.toString(ISODateTimeFormat.dateTime()), + docBuilder.marshalJsonObject().get("date").getAsString()); + } + + @Test + public void withModifiedDatePlainDateObject() { + Date d = new Date(); + DateTime dt = new DateTime(d); + docBuilder.withModifiedDate(d); + assertEquals( + "withModifiedDate with a plain java date object should marshal correctly", + dt.toString(ISODateTimeFormat.dateTime()), + docBuilder.marshalJsonObject().get("modifiedDate").getAsString()); + } + + @Test + public void testWithModifiedDateLong() { + docBuilder.withModifiedDate(12345l); + DateTime dt = new DateTime(12345l); + assertEquals( + "withDate with a long should marshal correctly", + dt.toString(ISODateTimeFormat.dateTime()), + docBuilder.marshalJsonObject().get("modifiedDate").getAsString()); + } + + @Test + public void testWithModifiedDateJodatime() { + DateTime dt = new DateTime(); + docBuilder.withModifiedDate(dt); + assertEquals( + "withDate with jodatime should marshal correctly", + dt.toString(ISODateTimeFormat.dateTime()), + docBuilder.marshalJsonObject().get("modifiedDate").getAsString()); + } + + public void testWithModifiedDateString() { + DateTime dt = new DateTime("2015-01-01"); + docBuilder.withModifiedDate("2015-01-01"); + assertEquals( + "withDate with string date should marshal correctly", + dt.toString(ISODateTimeFormat.dateTime()), + docBuilder.marshalJsonObject().get("modifiedDate").getAsString()); + } + + @Test + public void testWithPermanentId() { + docBuilder.withPermanentId("the_permanent_id"); + assertEquals( + "with permanentId should marshal correctly", + "the_permanent_id", + docBuilder.marshalJsonObject().get("permanentId").getAsString()); + } + + @Test + public void testWithPermanentIdGeneration() { + docBuilder = new DocumentBuilder("https://foo.com", "bar"); + assertEquals( + "permanentId should be generated automatically if not set", + "aa2e0510b66edff7f05e2b30d4f1b3a4b5481c06b69f41751c54675c5afb", + docBuilder.marshalJsonObject().get("permanentId").getAsString()); + } + + @Test + public void testWithCompressedBinaryData() { + String encoded = + Base64.getEncoder().encodeToString("binary data encoded".getBytes(StandardCharsets.UTF_8)); + docBuilder.withCompressedBinaryData( + new CompressedBinaryData(encoded, CompressionType.UNCOMPRESSED)); + String decoded = + new String( + Base64.getDecoder() + .decode( + docBuilder + .marshalJsonObject() + .get("compressedBinaryData") + .getAsString() + .getBytes(StandardCharsets.UTF_8))); + + assertEquals( + "withCompressedBinaryData should marshal correctly", "binary data encoded", decoded); + } + + @Test + public void testWithFileExtension() { + docBuilder.withFileExtension(".txt"); + + assertEquals( + "withFileExtension should marshal correctly", + ".txt", + docBuilder.marshalJsonObject().get("fileExtension").getAsString()); + } + + @Test(expected = RuntimeException.class) + public void testWithInvalidFileExtension() { + docBuilder.withFileExtension("this should blow up"); + } + + @Test + public void testWithParentID() { + docBuilder.withParentID("the_parent_id"); + + assertEquals( + "withParentId should marshal correctly", + "the_parent_id", + docBuilder.marshalJsonObject().get("parentId").getAsString()); + } + + @Test + public void testWithClickableUri() { + docBuilder.withClickableUri("the click uri"); + + assertEquals( + "withClickableUri should marshal correctly", + "the click uri", + docBuilder.marshalJsonObject().get("clickableUri").getAsString()); + } + + @Test + public void testWithAuthor() { + docBuilder.withAuthor("the author"); + + assertEquals( + "withAuthor should marshal correctly", + "the author", + docBuilder.marshalJsonObject().get("author").getAsString()); + } + + @Test + public void testWithMetadataValue() { + docBuilder.withMetadataValue("the_key", "the_value"); + assertEquals( + "withMetadataValue should marshal correctly", + "the_value", + docBuilder.marshalJsonObject().get("the_key").getAsString()); + assertNull( + "withMetadataValue should remove metadata key when marshaling", + docBuilder.marshalJsonObject().get("metadata")); + } + + @Test(expected = RuntimeException.class) + public void testWithInvalidMetadataValue() { + docBuilder.withMetadataValue("data", "this should blow up"); + } + + @Test + public void testWithMetadata() { + docBuilder.withMetadata( + new HashMap<>() { + { put("my_field_1", "1"); put("my_field_2", false); put("my_field_3", 1234); - put("my_field_4", new String[]{"a", "b", "c"}); - }}); - assertEquals( - "1", - docBuilder.marshalJsonObject().get("my_field_1").getAsString() - ); - assertEquals( - false, - docBuilder.marshalJsonObject().get("my_field_2").getAsBoolean() - ); - assertEquals( - 1234, - docBuilder.marshalJsonObject().get("my_field_3").getAsInt() - ); - assertEquals( - "a", - docBuilder.marshalJsonObject().get("my_field_4").getAsJsonArray().get(0).getAsString() - ); - assertEquals( - "b", - docBuilder.marshalJsonObject().get("my_field_4").getAsJsonArray().get(1).getAsString() - ); - assertEquals( - "c", - docBuilder.marshalJsonObject().get("my_field_4").getAsJsonArray().get(2).getAsString() - ); - - } - - @Test - public void testWithSingleAllowedPermissions() { - docBuilder.withAllowedPermissions(new UserSecurityIdentityBuilder("bob@anonymous.com")); - - assertEquals( - "bob@anonymous.com", - docBuilder.marshalJsonObject() - .get("permissions") - .getAsJsonArray() - .get(0) - .getAsJsonObject() - .get("allowedPermissions") - .getAsJsonArray() - .get(0) - .getAsJsonObject() - .get("identity").getAsString() - ); - } - - @Test - public void testWithMultipleAllowedPermissions() { - docBuilder.withAllowedPermissions(new UserSecurityIdentityBuilder(new String[]{"bob@anonymous.com", "john@anonymous.com"})); - - assertEquals( - "bob@anonymous.com", - docBuilder.marshalJsonObject() - .get("permissions") - .getAsJsonArray() - .get(0) - .getAsJsonObject() - .get("allowedPermissions") - .getAsJsonArray() - .get(0) - .getAsJsonObject() - .get("identity").getAsString() - ); - assertEquals( - "john@anonymous.com", - docBuilder.marshalJsonObject() - .get("permissions") - .getAsJsonArray() - .get(0) - .getAsJsonObject() - .get("allowedPermissions") - .getAsJsonArray() - .get(1) - .getAsJsonObject() - .get("identity").getAsString() - ); - } - - @Test - public void testWithSingleDeniedPermissions() { - docBuilder.withDeniedPermissions(new UserSecurityIdentityBuilder("bob@anonymous.com")); - - assertEquals( - "bob@anonymous.com", - docBuilder.marshalJsonObject() - .get("permissions") - .getAsJsonArray() - .get(0) - .getAsJsonObject() - .get("deniedPermissions") - .getAsJsonArray() - .get(0) - .getAsJsonObject() - .get("identity").getAsString() - ); - } - - @Test - public void testWithMultipleDeniedPermissions() { - docBuilder.withDeniedPermissions(new UserSecurityIdentityBuilder(new String[]{"bob@anonymous.com", "john@anonymous.com"})); - - assertEquals( - "bob@anonymous.com", - docBuilder.marshalJsonObject() - .get("permissions") - .getAsJsonArray() - .get(0) - .getAsJsonObject() - .get("deniedPermissions") - .getAsJsonArray() - .get(0) - .getAsJsonObject() - .get("identity").getAsString() - ); - assertEquals( - "john@anonymous.com", - docBuilder.marshalJsonObject() - .get("permissions") - .getAsJsonArray() - .get(0) - .getAsJsonObject() - .get("deniedPermissions") - .getAsJsonArray() - .get(1) - .getAsJsonObject() - .get("identity").getAsString() - ); - } - - @Test - public void withAllowAnonymousUsers() { - docBuilder.withAllowAnonymousUsers(false); - assertFalse( - "withAllowAnonymousUser should marshal correctly", - docBuilder.marshalJsonObject() - .get("permissions") - .getAsJsonArray() - .get(0) - .getAsJsonObject() - .get("allowAnonymous") - .getAsBoolean()); - } - - @Test - public void marshal() { - String marshaled = docBuilder.marshal(); - assertTrue( - "marshal should return a valid JSON string", - docBuilder.marshal().contains("the_title") - ); - } - + put("my_field_4", new String[] {"a", "b", "c"}); + } + }); + assertEquals("1", docBuilder.marshalJsonObject().get("my_field_1").getAsString()); + assertEquals(false, docBuilder.marshalJsonObject().get("my_field_2").getAsBoolean()); + assertEquals(1234, docBuilder.marshalJsonObject().get("my_field_3").getAsInt()); + assertEquals( + "a", + docBuilder.marshalJsonObject().get("my_field_4").getAsJsonArray().get(0).getAsString()); + assertEquals( + "b", + docBuilder.marshalJsonObject().get("my_field_4").getAsJsonArray().get(1).getAsString()); + assertEquals( + "c", + docBuilder.marshalJsonObject().get("my_field_4").getAsJsonArray().get(2).getAsString()); + } + + @Test + public void testWithSingleAllowedPermissions() { + docBuilder.withAllowedPermissions(new UserSecurityIdentityBuilder("bob@anonymous.com")); + + assertEquals( + "bob@anonymous.com", + docBuilder + .marshalJsonObject() + .get("permissions") + .getAsJsonArray() + .get(0) + .getAsJsonObject() + .get("allowedPermissions") + .getAsJsonArray() + .get(0) + .getAsJsonObject() + .get("identity") + .getAsString()); + } + + @Test + public void testWithMultipleAllowedPermissions() { + docBuilder.withAllowedPermissions( + new UserSecurityIdentityBuilder(new String[] {"bob@anonymous.com", "john@anonymous.com"})); + + assertEquals( + "bob@anonymous.com", + docBuilder + .marshalJsonObject() + .get("permissions") + .getAsJsonArray() + .get(0) + .getAsJsonObject() + .get("allowedPermissions") + .getAsJsonArray() + .get(0) + .getAsJsonObject() + .get("identity") + .getAsString()); + assertEquals( + "john@anonymous.com", + docBuilder + .marshalJsonObject() + .get("permissions") + .getAsJsonArray() + .get(0) + .getAsJsonObject() + .get("allowedPermissions") + .getAsJsonArray() + .get(1) + .getAsJsonObject() + .get("identity") + .getAsString()); + } + + @Test + public void testWithSingleDeniedPermissions() { + docBuilder.withDeniedPermissions(new UserSecurityIdentityBuilder("bob@anonymous.com")); + + assertEquals( + "bob@anonymous.com", + docBuilder + .marshalJsonObject() + .get("permissions") + .getAsJsonArray() + .get(0) + .getAsJsonObject() + .get("deniedPermissions") + .getAsJsonArray() + .get(0) + .getAsJsonObject() + .get("identity") + .getAsString()); + } + + @Test + public void testWithMultipleDeniedPermissions() { + docBuilder.withDeniedPermissions( + new UserSecurityIdentityBuilder(new String[] {"bob@anonymous.com", "john@anonymous.com"})); + + assertEquals( + "bob@anonymous.com", + docBuilder + .marshalJsonObject() + .get("permissions") + .getAsJsonArray() + .get(0) + .getAsJsonObject() + .get("deniedPermissions") + .getAsJsonArray() + .get(0) + .getAsJsonObject() + .get("identity") + .getAsString()); + assertEquals( + "john@anonymous.com", + docBuilder + .marshalJsonObject() + .get("permissions") + .getAsJsonArray() + .get(0) + .getAsJsonObject() + .get("deniedPermissions") + .getAsJsonArray() + .get(1) + .getAsJsonObject() + .get("identity") + .getAsString()); + } + + @Test + public void withAllowAnonymousUsers() { + docBuilder.withAllowAnonymousUsers(false); + assertFalse( + "withAllowAnonymousUser should marshal correctly", + docBuilder + .marshalJsonObject() + .get("permissions") + .getAsJsonArray() + .get(0) + .getAsJsonObject() + .get("allowAnonymous") + .getAsBoolean()); + } + + @Test + public void marshal() { + String marshaled = docBuilder.marshal(); + assertTrue( + "marshal should return a valid JSON string", docBuilder.marshal().contains("the_title")); + } } diff --git a/src/test/java/com/coveo/pushapiclient/DocumentUploadQueueTest.java b/src/test/java/com/coveo/pushapiclient/DocumentUploadQueueTest.java index 5e346a41..4f0f20a6 100644 --- a/src/test/java/com/coveo/pushapiclient/DocumentUploadQueueTest.java +++ b/src/test/java/com/coveo/pushapiclient/DocumentUploadQueueTest.java @@ -9,7 +9,6 @@ import java.io.IOException; import java.util.ArrayList; - import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -19,174 +18,181 @@ public class DocumentUploadQueueTest { - @Mock - private UploadStrategy uploadStrategy; - - @InjectMocks - private DocumentUploadQueue queue; - - private AutoCloseable closeable; - private DocumentBuilder documentToAdd; - private DeleteDocument documentToDelete; - - private int oneMegaByte = 1 * 1024 * 1024; - - private String generateStringFromBytes(int numBytes) { - // Check if the number of bytes is valid - if (numBytes <= 0) { - return ""; - } - - // Create a byte array with the specified length - byte[] bytes = new byte[numBytes]; - - // Fill the byte array with a pattern of ASCII characters - byte pattern = 65; // ASCII value for 'A' - for (int i = 0; i < numBytes; i++) { - bytes[i] = pattern; - } - - return new String(bytes); - } - - private DocumentBuilder generateDocumentFromSize(int numBytes) { - return new DocumentBuilder("https://my.document.uri?ref=1", - "My bulky document") - .withData(generateStringFromBytes(numBytes)); - } - - @Before - public void setup() { - String twoMegaByteData = generateStringFromBytes(2 * oneMegaByte); - - documentToAdd = new DocumentBuilder( - "https://my.document.uri?ref=1", - "My new document") - .withData(twoMegaByteData); + @Mock private UploadStrategy uploadStrategy; - documentToDelete = new DeleteDocument("https://my.document.uri?ref=3"); + @InjectMocks private DocumentUploadQueue queue; - closeable = MockitoAnnotations.openMocks(this); - } + private AutoCloseable closeable; + private DocumentBuilder documentToAdd; + private DeleteDocument documentToDelete; - @After - public void closeService() throws Exception { - closeable.close(); - } + private int oneMegaByte = 1 * 1024 * 1024; - @Test - public void testIsEmpty() throws IOException, InterruptedException { - assertTrue(queue.isEmpty()); + private String generateStringFromBytes(int numBytes) { + // Check if the number of bytes is valid + if (numBytes <= 0) { + return ""; } - @Test - public void testIsNotEmpty() throws IOException, InterruptedException { - queue.add(documentToAdd); - assertFalse(queue.isEmpty()); - } + // Create a byte array with the specified length + byte[] bytes = new byte[numBytes]; - @Test - public void testShouldReturnBatch() throws IOException, InterruptedException { - BatchUpdate batchUpdate = new BatchUpdate( - new ArrayList<>() { - { - add(documentToAdd); - } - }, new ArrayList<>() { - { - add(documentToDelete); - } - }); - queue.add(documentToAdd); - queue.add(documentToDelete); - - assertEquals(batchUpdate, queue.getBatch()); + // Fill the byte array with a pattern of ASCII characters + byte pattern = 65; // ASCII value for 'A' + for (int i = 0; i < numBytes; i++) { + bytes[i] = pattern; } - @Test - public void testFlushShouldNotUploadDocumentaWhenRequiredSizeIsNotMet() throws IOException, InterruptedException { - queue.add(documentToAdd); - queue.add(documentToDelete); - - verify(uploadStrategy, times(0)).apply(any(BatchUpdate.class)); - } - - @Test - public void testShouldAutomaticallyFlushAccumulatedDocuments() throws IOException, InterruptedException { - DocumentBuilder firstBulkyDocument = generateDocumentFromSize(2 * oneMegaByte); - DocumentBuilder secondBulkyDocument = generateDocumentFromSize(2 * oneMegaByte); - DocumentBuilder thirdBulkyDocument = generateDocumentFromSize(2 * oneMegaByte); - ArrayList emptyList = new ArrayList<>(); - BatchUpdate firstBatch = new BatchUpdate( - new ArrayList<>() { - { - add(firstBulkyDocument); - add(secondBulkyDocument); - } - }, emptyList); - - // Adding 3 documents of 2MB to the queue. After adding the first 2 documents, - // the queue size will reach 6MB, which exceeds the maximum queue size - // limit. Therefore, the 2 first added documents will automatically be uploaded - // to the source. - queue.add(firstBulkyDocument); - queue.add(secondBulkyDocument); - - // The 3rd document added to the queue will be included in a separate batch, - // which will not be uploaded unless the `flush()` method is called or until the - // queue size limit has been reached - queue.add(thirdBulkyDocument); - - verify(uploadStrategy, times(1)).apply(any(BatchUpdate.class)); - verify(uploadStrategy, times(1)).apply(firstBatch); - } - - @Test - public void testShouldManuallyFlushAccumulatedDocuments() throws IOException, InterruptedException { - DocumentBuilder firstBulkyDocument = generateDocumentFromSize(2 * oneMegaByte); - DocumentBuilder secondBulkyDocument = generateDocumentFromSize(2 * oneMegaByte); - DocumentBuilder thirdBulkyDocument = generateDocumentFromSize(2 * oneMegaByte); - ArrayList emptyList = new ArrayList<>(); - BatchUpdate firstBatch = new BatchUpdate( - new ArrayList<>() { - { - add(firstBulkyDocument); - add(secondBulkyDocument); - } - }, emptyList); - - BatchUpdate secondBatch = new BatchUpdate( - new ArrayList<>() { - { - add(thirdBulkyDocument); - } - }, emptyList); - - // Adding 3 documents of 2MB to the queue. After adding the first 2 documents, - // the queue size will reach 6MB, which exceeds the maximum queue size - // limit. Therefore, the 2 first added documents will automatically be uploaded - // to the source. - queue.add(firstBulkyDocument); - queue.add(secondBulkyDocument); - queue.add(thirdBulkyDocument); - - queue.flush(); - - // Additional flush will have no effect if documents where already flushed - queue.flush(); - - verify(uploadStrategy, times(2)).apply(any(BatchUpdate.class)); - verify(uploadStrategy, times(1)).apply(firstBatch); - verify(uploadStrategy, times(1)).apply(secondBatch); - } - - @Test - public void testAddingEmptyDocument() throws IOException, InterruptedException { - DocumentBuilder nullDocument = null; - - queue.add(nullDocument); - queue.flush(); - - verify(uploadStrategy, times(0)).apply(any(BatchUpdate.class)); - } + return new String(bytes); + } + + private DocumentBuilder generateDocumentFromSize(int numBytes) { + return new DocumentBuilder("https://my.document.uri?ref=1", "My bulky document") + .withData(generateStringFromBytes(numBytes)); + } + + @Before + public void setup() { + String twoMegaByteData = generateStringFromBytes(2 * oneMegaByte); + + documentToAdd = + new DocumentBuilder("https://my.document.uri?ref=1", "My new document") + .withData(twoMegaByteData); + + documentToDelete = new DeleteDocument("https://my.document.uri?ref=3"); + + closeable = MockitoAnnotations.openMocks(this); + } + + @After + public void closeService() throws Exception { + closeable.close(); + } + + @Test + public void testIsEmpty() throws IOException, InterruptedException { + assertTrue(queue.isEmpty()); + } + + @Test + public void testIsNotEmpty() throws IOException, InterruptedException { + queue.add(documentToAdd); + assertFalse(queue.isEmpty()); + } + + @Test + public void testShouldReturnBatch() throws IOException, InterruptedException { + BatchUpdate batchUpdate = + new BatchUpdate( + new ArrayList<>() { + { + add(documentToAdd); + } + }, + new ArrayList<>() { + { + add(documentToDelete); + } + }); + queue.add(documentToAdd); + queue.add(documentToDelete); + + assertEquals(batchUpdate, queue.getBatch()); + } + + @Test + public void testFlushShouldNotUploadDocumentaWhenRequiredSizeIsNotMet() + throws IOException, InterruptedException { + queue.add(documentToAdd); + queue.add(documentToDelete); + + verify(uploadStrategy, times(0)).apply(any(BatchUpdate.class)); + } + + @Test + public void testShouldAutomaticallyFlushAccumulatedDocuments() + throws IOException, InterruptedException { + DocumentBuilder firstBulkyDocument = generateDocumentFromSize(2 * oneMegaByte); + DocumentBuilder secondBulkyDocument = generateDocumentFromSize(2 * oneMegaByte); + DocumentBuilder thirdBulkyDocument = generateDocumentFromSize(2 * oneMegaByte); + ArrayList emptyList = new ArrayList<>(); + BatchUpdate firstBatch = + new BatchUpdate( + new ArrayList<>() { + { + add(firstBulkyDocument); + add(secondBulkyDocument); + } + }, + emptyList); + + // Adding 3 documents of 2MB to the queue. After adding the first 2 documents, + // the queue size will reach 6MB, which exceeds the maximum queue size + // limit. Therefore, the 2 first added documents will automatically be uploaded + // to the source. + queue.add(firstBulkyDocument); + queue.add(secondBulkyDocument); + + // The 3rd document added to the queue will be included in a separate batch, + // which will not be uploaded unless the `flush()` method is called or until the + // queue size limit has been reached + queue.add(thirdBulkyDocument); + + verify(uploadStrategy, times(1)).apply(any(BatchUpdate.class)); + verify(uploadStrategy, times(1)).apply(firstBatch); + } + + @Test + public void testShouldManuallyFlushAccumulatedDocuments() + throws IOException, InterruptedException { + DocumentBuilder firstBulkyDocument = generateDocumentFromSize(2 * oneMegaByte); + DocumentBuilder secondBulkyDocument = generateDocumentFromSize(2 * oneMegaByte); + DocumentBuilder thirdBulkyDocument = generateDocumentFromSize(2 * oneMegaByte); + ArrayList emptyList = new ArrayList<>(); + BatchUpdate firstBatch = + new BatchUpdate( + new ArrayList<>() { + { + add(firstBulkyDocument); + add(secondBulkyDocument); + } + }, + emptyList); + + BatchUpdate secondBatch = + new BatchUpdate( + new ArrayList<>() { + { + add(thirdBulkyDocument); + } + }, + emptyList); + + // Adding 3 documents of 2MB to the queue. After adding the first 2 documents, + // the queue size will reach 6MB, which exceeds the maximum queue size + // limit. Therefore, the 2 first added documents will automatically be uploaded + // to the source. + queue.add(firstBulkyDocument); + queue.add(secondBulkyDocument); + queue.add(thirdBulkyDocument); + + queue.flush(); + + // Additional flush will have no effect if documents where already flushed + queue.flush(); + + verify(uploadStrategy, times(2)).apply(any(BatchUpdate.class)); + verify(uploadStrategy, times(1)).apply(firstBatch); + verify(uploadStrategy, times(1)).apply(secondBatch); + } + + @Test + public void testAddingEmptyDocument() throws IOException, InterruptedException { + DocumentBuilder nullDocument = null; + + queue.add(nullDocument); + queue.flush(); + + verify(uploadStrategy, times(0)).apply(any(BatchUpdate.class)); + } } diff --git a/src/test/java/com/coveo/pushapiclient/GroupSecurityIdentityBuilderTest.java b/src/test/java/com/coveo/pushapiclient/GroupSecurityIdentityBuilderTest.java index bb14e718..733cc506 100644 --- a/src/test/java/com/coveo/pushapiclient/GroupSecurityIdentityBuilderTest.java +++ b/src/test/java/com/coveo/pushapiclient/GroupSecurityIdentityBuilderTest.java @@ -1,76 +1,79 @@ package com.coveo.pushapiclient; -import org.junit.Before; -import org.junit.Test; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; -public class GroupSecurityIdentityBuilderTest { +import org.junit.Before; +import org.junit.Test; - private GroupSecurityIdentityBuilder gsib1; - private GroupSecurityIdentityBuilder gsib2; - private GroupSecurityIdentityBuilder gsib3; - private GroupSecurityIdentityBuilder gsib4; - private GroupSecurityIdentityBuilder gsib5; +public class GroupSecurityIdentityBuilderTest { - @Before - public void setUp() { - String[] id1 = new String[]{"identity1", "identity2"}; - String[] id2 = new String[]{"identity2", "identity3"}; + private GroupSecurityIdentityBuilder gsib1; + private GroupSecurityIdentityBuilder gsib2; + private GroupSecurityIdentityBuilder gsib3; + private GroupSecurityIdentityBuilder gsib4; + private GroupSecurityIdentityBuilder gsib5; - gsib1 = new GroupSecurityIdentityBuilder(id1, "some_sec_provider"); - gsib2 = new GroupSecurityIdentityBuilder(id1, "some_sec_provider"); - gsib3 = new GroupSecurityIdentityBuilder(id2, "some_sec_provider"); - gsib4 = new GroupSecurityIdentityBuilder(id1, "some_other_sec_provider"); - gsib5 = gsib1; - } + @Before + public void setUp() { + String[] id1 = new String[] {"identity1", "identity2"}; + String[] id2 = new String[] {"identity2", "identity3"}; - @Test - public void testSingleIdentities() { - SecurityIdentity identityBuilt = new GroupSecurityIdentityBuilder("bob@foo.com", "my provider").build()[0]; - assertEquals("bob@foo.com", identityBuilt.identity); - assertEquals(SecurityIdentityType.GROUP, identityBuilt.identityType); - assertEquals("my provider", identityBuilt.securityProvider); - } + gsib1 = new GroupSecurityIdentityBuilder(id1, "some_sec_provider"); + gsib2 = new GroupSecurityIdentityBuilder(id1, "some_sec_provider"); + gsib3 = new GroupSecurityIdentityBuilder(id2, "some_sec_provider"); + gsib4 = new GroupSecurityIdentityBuilder(id1, "some_other_sec_provider"); + gsib5 = gsib1; + } - @Test - public void testMultipleIdentities() { - SecurityIdentity[] identitiesBuilt = new GroupSecurityIdentityBuilder(new String[]{"bob@foo.com", "john@foo.com"}, "my provider").build(); + @Test + public void testSingleIdentities() { + SecurityIdentity identityBuilt = + new GroupSecurityIdentityBuilder("bob@foo.com", "my provider").build()[0]; + assertEquals("bob@foo.com", identityBuilt.identity); + assertEquals(SecurityIdentityType.GROUP, identityBuilt.identityType); + assertEquals("my provider", identityBuilt.securityProvider); + } - assertEquals("bob@foo.com", identitiesBuilt[0].identity); - assertEquals("john@foo.com", identitiesBuilt[1].identity); + @Test + public void testMultipleIdentities() { + SecurityIdentity[] identitiesBuilt = + new GroupSecurityIdentityBuilder( + new String[] {"bob@foo.com", "john@foo.com"}, "my provider") + .build(); - } + assertEquals("bob@foo.com", identitiesBuilt[0].identity); + assertEquals("john@foo.com", identitiesBuilt[1].identity); + } - @Test - public void testToString() { - assertEquals(gsib1.toString(), gsib1.toString()); - assertEquals(gsib1.toString(), gsib2.toString()); - assertEquals(gsib1.toString(), gsib5.toString()); - assertNotEquals(gsib1.toString(), gsib3.toString()); - assertNotEquals(gsib3.toString(), gsib4.toString()); - } + @Test + public void testToString() { + assertEquals(gsib1.toString(), gsib1.toString()); + assertEquals(gsib1.toString(), gsib2.toString()); + assertEquals(gsib1.toString(), gsib5.toString()); + assertNotEquals(gsib1.toString(), gsib3.toString()); + assertNotEquals(gsib3.toString(), gsib4.toString()); + } - @Test - public void testEquals() { - assertTrue(gsib1.equals(gsib1)); - assertTrue(gsib1.equals(gsib2)); - assertTrue(gsib1.equals(gsib5)); - assertFalse(gsib3.equals(gsib1)); - assertFalse(gsib3.equals(gsib4)); - assertFalse(gsib1.equals(null)); - } + @Test + public void testEquals() { + assertTrue(gsib1.equals(gsib1)); + assertTrue(gsib1.equals(gsib2)); + assertTrue(gsib1.equals(gsib5)); + assertFalse(gsib3.equals(gsib1)); + assertFalse(gsib3.equals(gsib4)); + assertFalse(gsib1.equals(null)); + } - @Test - public void testHashCode() { - assertEquals(gsib1.hashCode(), gsib1.hashCode()); - assertEquals(gsib1.hashCode(), gsib2.hashCode()); - assertEquals(gsib1.hashCode(), gsib5.hashCode()); - assertEquals(gsib3.hashCode(), gsib3.hashCode()); - assertNotEquals(gsib1.hashCode(), gsib3.hashCode()); - assertNotEquals(gsib3.hashCode(), gsib4.hashCode()); - } -} \ No newline at end of file + @Test + public void testHashCode() { + assertEquals(gsib1.hashCode(), gsib1.hashCode()); + assertEquals(gsib1.hashCode(), gsib2.hashCode()); + assertEquals(gsib1.hashCode(), gsib5.hashCode()); + assertEquals(gsib3.hashCode(), gsib3.hashCode()); + assertNotEquals(gsib1.hashCode(), gsib3.hashCode()); + assertNotEquals(gsib3.hashCode(), gsib4.hashCode()); + } +} diff --git a/src/test/java/com/coveo/pushapiclient/PlatformClientTest.java b/src/test/java/com/coveo/pushapiclient/PlatformClientTest.java index 20eda8af..b411d46f 100644 --- a/src/test/java/com/coveo/pushapiclient/PlatformClientTest.java +++ b/src/test/java/com/coveo/pushapiclient/PlatformClientTest.java @@ -1,10 +1,12 @@ package com.coveo.pushapiclient; -import com.google.gson.Gson; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import com.google.gson.Gson; import java.io.IOException; import java.net.http.HttpClient; import java.net.http.HttpRequest; @@ -12,321 +14,443 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; public class PlatformClientTest { - private PlatformClient client; - private HttpClient httpClient; - private ArgumentCaptor argument; - - public void assertAuthorizationHeader() { - assertTrue(this.argument.getValue().headers().map().get("Authorization").contains("Bearer the_api_key")); - } - - public void assertApplicationJsonHeader() { - assertTrue(this.argument.getValue().headers().map().get("Content-Type").contains("application/json")); - assertTrue(this.argument.getValue().headers().map().get("Accept").contains("application/json")); - } - - public SecurityIdentityModel securityIdentityModel() { - return new SecurityIdentityModel(identityModels(), identityModel(), identityModels()); - } - - public SecurityIdentityAliasModel securityIdentityAliasModel() { - return new SecurityIdentityAliasModel(aliasMappings(), identityModel(), identityModels()); - } - - public SecurityIdentityDelete securityIdentityDelete() { - return new SecurityIdentityDelete(identityModel()); - } - - public SecurityIdentityBatchConfig securityIdentityBatchConfig() { - return new SecurityIdentityBatchConfig("the_file_id", 1234L); - } - - public DocumentBuilder documentBuilder() { - return new DocumentBuilder("the_uri", "the_title"); - } - - public DeleteDocument deleteDocument() { - return new DeleteDocument("12345"); - } - - public Document document() { - return documentBuilder().getDocument(); - } - - public String documentString() { - return documentBuilder().marshal(); - } - - public FileContainer fileContainer() { - FileContainer fileContainer = new FileContainer(); - fileContainer.fileId = "the_file_id"; - fileContainer.requiredHeaders = new HashMap<>() {{ - put("foo", "bar"); - }}; - fileContainer.uploadUri = "https://upload.uri"; - return fileContainer; - } - - public BatchUpdateRecord batchUpdateRecord() { - BatchUpdate batchUpdate = new BatchUpdate(new ArrayList<>() {{ - add(documentBuilder()); - }}, new ArrayList<>() {{ - add(deleteDocument()); - }}); - return batchUpdate.marshal(); - } - - public IdentityModel identityModel() { - return new IdentityModel("the_name_identity_model", SecurityIdentityType.USER, new HashMap<>() {{ + private PlatformClient client; + private HttpClient httpClient; + private ArgumentCaptor argument; + + public void assertAuthorizationHeader() { + assertTrue( + this.argument + .getValue() + .headers() + .map() + .get("Authorization") + .contains("Bearer the_api_key")); + } + + public void assertApplicationJsonHeader() { + assertTrue( + this.argument.getValue().headers().map().get("Content-Type").contains("application/json")); + assertTrue(this.argument.getValue().headers().map().get("Accept").contains("application/json")); + } + + public SecurityIdentityModel securityIdentityModel() { + return new SecurityIdentityModel(identityModels(), identityModel(), identityModels()); + } + + public SecurityIdentityAliasModel securityIdentityAliasModel() { + return new SecurityIdentityAliasModel(aliasMappings(), identityModel(), identityModels()); + } + + public SecurityIdentityDelete securityIdentityDelete() { + return new SecurityIdentityDelete(identityModel()); + } + + public SecurityIdentityBatchConfig securityIdentityBatchConfig() { + return new SecurityIdentityBatchConfig("the_file_id", 1234L); + } + + public DocumentBuilder documentBuilder() { + return new DocumentBuilder("the_uri", "the_title"); + } + + public DeleteDocument deleteDocument() { + return new DeleteDocument("12345"); + } + + public Document document() { + return documentBuilder().getDocument(); + } + + public String documentString() { + return documentBuilder().marshal(); + } + + public FileContainer fileContainer() { + FileContainer fileContainer = new FileContainer(); + fileContainer.fileId = "the_file_id"; + fileContainer.requiredHeaders = + new HashMap<>() { + { put("foo", "bar"); - }}); - } - - public IdentityModel[] identityModels() { - return new IdentityModel[]{identityModel()}; - } - - public AliasMapping[] aliasMappings() { - return new AliasMapping[]{new AliasMapping("the_provider_alias", "the_name_alias", SecurityIdentityType.USER, new HashMap<>() {{ + } + }; + fileContainer.uploadUri = "https://upload.uri"; + return fileContainer; + } + + public BatchUpdateRecord batchUpdateRecord() { + BatchUpdate batchUpdate = + new BatchUpdate( + new ArrayList<>() { + { + add(documentBuilder()); + } + }, + new ArrayList<>() { + { + add(deleteDocument()); + } + }); + return batchUpdate.marshal(); + } + + public IdentityModel identityModel() { + return new IdentityModel( + "the_name_identity_model", + SecurityIdentityType.USER, + new HashMap<>() { + { put("foo", "bar"); - }})}; - } - - @Before - public void setupClient() { - this.httpClient = mock(HttpClient.class); - this.client = new PlatformClient("the_api_key", "the_org_id", this.httpClient); - this.argument = ArgumentCaptor.forClass(HttpRequest.class); - } - - @Test - public void testCreatePushSource() throws IOException, InterruptedException { - client.createSource("the_name", SourceType.PUSH, SourceVisibility.SECURED); - verify(httpClient).send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); - - assertEquals("POST", argument.getValue().method()); - assertTrue(argument.getValue().uri().getPath().contains("the_org_id/sources")); - assertAuthorizationHeader(); - assertApplicationJsonHeader(); - - Map requestBody = StringSubscriber.toMap(argument.getValue().bodyPublisher()); - assertEquals("the_name", requestBody.get("name")); - assertEquals(SourceVisibility.SECURED.toString(), requestBody.get("sourceVisibility")); - assertEquals("PUSH", requestBody.get("sourceType")); - assertEquals(true, requestBody.get("pushEnabled")); - } - - @Test - public void testCreateCatalogSource() throws IOException, InterruptedException { - client.createSource("the_name", SourceType.CATALOG, SourceVisibility.SECURED); - verify(httpClient).send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); - - assertEquals("POST", argument.getValue().method()); - assertTrue(argument.getValue().uri().getPath().contains("the_org_id/sources")); - assertAuthorizationHeader(); - assertApplicationJsonHeader(); - - Map requestBody = StringSubscriber.toMap(argument.getValue().bodyPublisher()); - assertEquals("the_name", requestBody.get("name")); - assertEquals(SourceVisibility.SECURED.toString(), requestBody.get("sourceVisibility")); - assertEquals("CATALOG", requestBody.get("sourceType")); - assertEquals(true, requestBody.get("pushEnabled")); - assertEquals(true, requestBody.get("streamEnabled")); - } - - @Test - public void testCreateOrUpdateSecurityIdentity() throws IOException, InterruptedException { - client.createOrUpdateSecurityIdentity("my_provider", securityIdentityModel()); - verify(httpClient).send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); - - assertEquals("PUT", argument.getValue().method()); - assertTrue(argument.getValue().uri().getPath().contains("the_org_id/providers/my_provider/permissions")); - assertAuthorizationHeader(); - assertApplicationJsonHeader(); - - Map requestBody = StringSubscriber.toMap(argument.getValue().bodyPublisher()); - - ArrayList members = (ArrayList) requestBody.get("members"); - ArrayList wellKnowns = (ArrayList) requestBody.get("wellKnowns"); - Map identity = (Map) requestBody.get("identity"); - - assertEquals(identityModel().name, members.get(0).get("name")); - assertEquals(identityModel().additionalInfo.get("foo"), ((Map) members.get(0).get("additionalInfo")).get("foo")); - assertEquals(identityModel().name, wellKnowns.get(0).get("name")); - assertEquals(identityModel().additionalInfo.get("foo"), ((Map) wellKnowns.get(0).get("additionalInfo")).get("foo")); - assertEquals(identityModel().name, identity.get("name")); - assertEquals(identityModel().additionalInfo.get("foo"), ((Map) identity.get("additionalInfo")).get("foo")); - } - - @Test - public void testCreateOrUpdateSecurityIdentityAlias() throws IOException, InterruptedException { - client.createOrUpdateSecurityIdentityAlias("my_provider", securityIdentityAliasModel()); - verify(httpClient).send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); - - assertEquals("PUT", argument.getValue().method()); - assertTrue(argument.getValue().uri().getPath().contains("the_org_id/providers/my_provider/mappings")); - assertAuthorizationHeader(); - assertApplicationJsonHeader(); - - Map requestBody = StringSubscriber.toMap(argument.getValue().bodyPublisher()); - - ArrayList mappings = (ArrayList) requestBody.get("mappings"); - ArrayList wellKnowns = (ArrayList) requestBody.get("wellKnowns"); - Map identity = (Map) requestBody.get("identity"); - - assertEquals(aliasMappings()[0].name, mappings.get(0).get("name")); - assertEquals(aliasMappings()[0].additionalInfo.get("foo"), ((Map) mappings.get(0).get("additionalInfo")).get("foo")); - assertEquals(identityModel().name, wellKnowns.get(0).get("name")); - assertEquals(identityModel().additionalInfo.get("foo"), ((Map) wellKnowns.get(0).get("additionalInfo")).get("foo")); - assertEquals(identityModel().name, identity.get("name")); - assertEquals(identityModel().additionalInfo.get("foo"), ((Map) identity.get("additionalInfo")).get("foo")); - } - - @Test - public void testDeleteSecurityIdentity() throws IOException, InterruptedException { - client.deleteSecurityIdentity("my_provider", securityIdentityDelete()); - verify(httpClient).send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); - - assertEquals("DELETE", argument.getValue().method()); - assertTrue(argument.getValue().uri().getPath().contains("the_org_id/providers/my_provider/permissions")); - assertAuthorizationHeader(); - assertApplicationJsonHeader(); - - Map requestBody = StringSubscriber.toMap(argument.getValue().bodyPublisher()); - Map identity = (Map) requestBody.get("identity"); - - assertEquals(identityModel().name, identity.get("name")); - } - - @Test - public void testManageSecurityIdentities() throws IOException, InterruptedException { - client.manageSecurityIdentities("my_provider", securityIdentityBatchConfig()); - verify(httpClient).send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); - - assertEquals("PUT", argument.getValue().method()); - assertTrue(argument.getValue().uri().getPath().contains("the_org_id/providers/my_provider/permissions/batch")); - assertTrue(argument.getValue().uri().getQuery().contains(String.format("fileId=%s", securityIdentityBatchConfig().getFileId()))); - assertTrue(argument.getValue().uri().getQuery().contains(String.format("orderingId=%s", securityIdentityBatchConfig().getOrderingId()))); - assertAuthorizationHeader(); - assertApplicationJsonHeader(); - } - - @Test - public void testAppendOrderingId() throws IOException, InterruptedException { - String standardOrderingParam = client.appendOrderingId(1234L); - String noOrderingParam = client.appendOrderingId(0L); - - assertTrue(standardOrderingParam.contains(String.format("orderingId=%s", "1234"))); - assertEquals("", noOrderingParam); - } - - @Test - public void testPushDocument() throws IOException, InterruptedException { - client.pushDocument("my_source", documentString(), document().uri, CompressionType.UNCOMPRESSED); - verify(httpClient).send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); - - assertEquals("PUT", argument.getValue().method()); - assertTrue(argument.getValue().uri().getPath().contains("the_org_id/sources/my_source/documents")); - assertTrue(argument.getValue().uri().getQuery().contains(String.format("documentId=%s", document().uri))); - assertTrue(argument.getValue().uri().getQuery().contains(String.format("compressionType=%s", CompressionType.UNCOMPRESSED.toString()))); - assertAuthorizationHeader(); - assertApplicationJsonHeader(); - - Map requestBody = StringSubscriber.toMap(argument.getValue().bodyPublisher()); - assertEquals(document().title, requestBody.get("title")); - } - - @Test - public void testCreateFileContainer() throws IOException, InterruptedException { - client.createFileContainer(); - verify(httpClient).send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); - - assertEquals("POST", argument.getValue().method()); - assertTrue(argument.getValue().uri().getPath().contains("the_org_id/files")); - assertAuthorizationHeader(); - assertApplicationJsonHeader(); - } - - @Test - public void testUploadContentToFileContainer() throws IOException, InterruptedException { - client.uploadContentToFileContainer(fileContainer(), new Gson().toJson(batchUpdateRecord())); - verify(httpClient).send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); - - assertEquals("PUT", argument.getValue().method()); - assertTrue(argument.getValue().uri().toString().equals(fileContainer().uploadUri)); - assertEquals(argument.getValue().headers().map().get("foo").get(0), fileContainer().requiredHeaders.get("foo")); - - Map requestBody = StringSubscriber.toMap(argument.getValue().bodyPublisher()); - ArrayList addOrUpdate = (ArrayList) requestBody.get("addOrUpdate"); - ArrayList delete = (ArrayList) requestBody.get("delete"); - - assertEquals(document().uri, addOrUpdate.get(0).get("documentId")); - assertEquals(deleteDocument().documentId, delete.get(0).get("documentId")); - } - - @Test - public void testPushFileContainerContent() throws IOException, InterruptedException { - client.pushFileContainerContent("my_source", fileContainer()); - verify(httpClient).send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); - - assertEquals("PUT", argument.getValue().method()); - assertTrue(argument.getValue().uri().getPath().contains("the_org_id/sources/my_source/documents/batch")); - assertTrue(argument.getValue().uri().getQuery().contains(String.format("fileId=%s", fileContainer().fileId))); - assertApplicationJsonHeader(); - assertAuthorizationHeader(); - } - - @Test - public void testOpenStream() throws IOException, InterruptedException { - client.openStream("my_source"); - verify(httpClient).send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); - - assertEquals("POST", argument.getValue().method()); - assertTrue(argument.getValue().uri().getPath().contains("the_org_id/sources/my_source/stream/open")); - assertApplicationJsonHeader(); - assertAuthorizationHeader(); - } - - @Test - public void testRequireStreamChunk() throws IOException, InterruptedException { - client.requireStreamChunk("my_source", "stream_id"); - verify(httpClient).send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); - - assertEquals("POST", argument.getValue().method()); - assertTrue(argument.getValue().uri().getPath().contains("the_org_id/sources/my_source/stream/stream_id/chunk")); - assertApplicationJsonHeader(); - assertAuthorizationHeader(); - } - - @Test - public void testCloseStream() throws IOException, InterruptedException { - client.closeStream("my_source", "stream_id"); - verify(httpClient).send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); - - assertEquals("POST", argument.getValue().method()); - assertTrue(argument.getValue().uri().getPath().contains("the_org_id/sources/my_source/stream/stream_id/close")); - assertApplicationJsonHeader(); - assertAuthorizationHeader(); - } - - @Test - public void testDeleteDocument() throws IOException, InterruptedException { - client.deleteDocument("my_source", document().uri, true); - verify(httpClient).send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); - - assertEquals("DELETE", argument.getValue().method()); - assertTrue(argument.getValue().uri().getPath().contains("the_org_id/sources/my_source/documents")); - assertTrue(argument.getValue().uri().getQuery().contains("deleteChildren=true")); - assertTrue(argument.getValue().uri().getQuery().contains(String.format("documentId=%s", document().uri))); - assertApplicationJsonHeader(); - assertAuthorizationHeader(); - } -} \ No newline at end of file + } + }); + } + + public IdentityModel[] identityModels() { + return new IdentityModel[] {identityModel()}; + } + + public AliasMapping[] aliasMappings() { + return new AliasMapping[] { + new AliasMapping( + "the_provider_alias", + "the_name_alias", + SecurityIdentityType.USER, + new HashMap<>() { + { + put("foo", "bar"); + } + }) + }; + } + + @Before + public void setupClient() { + this.httpClient = mock(HttpClient.class); + this.client = new PlatformClient("the_api_key", "the_org_id", this.httpClient); + this.argument = ArgumentCaptor.forClass(HttpRequest.class); + } + + @Test + public void testCreatePushSource() throws IOException, InterruptedException { + client.createSource("the_name", SourceType.PUSH, SourceVisibility.SECURED); + verify(httpClient) + .send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); + + assertEquals("POST", argument.getValue().method()); + assertTrue(argument.getValue().uri().getPath().contains("the_org_id/sources")); + assertAuthorizationHeader(); + assertApplicationJsonHeader(); + + Map requestBody = StringSubscriber.toMap(argument.getValue().bodyPublisher()); + assertEquals("the_name", requestBody.get("name")); + assertEquals(SourceVisibility.SECURED.toString(), requestBody.get("sourceVisibility")); + assertEquals("PUSH", requestBody.get("sourceType")); + assertEquals(true, requestBody.get("pushEnabled")); + } + + @Test + public void testCreateCatalogSource() throws IOException, InterruptedException { + client.createSource("the_name", SourceType.CATALOG, SourceVisibility.SECURED); + verify(httpClient) + .send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); + + assertEquals("POST", argument.getValue().method()); + assertTrue(argument.getValue().uri().getPath().contains("the_org_id/sources")); + assertAuthorizationHeader(); + assertApplicationJsonHeader(); + + Map requestBody = StringSubscriber.toMap(argument.getValue().bodyPublisher()); + assertEquals("the_name", requestBody.get("name")); + assertEquals(SourceVisibility.SECURED.toString(), requestBody.get("sourceVisibility")); + assertEquals("CATALOG", requestBody.get("sourceType")); + assertEquals(true, requestBody.get("pushEnabled")); + assertEquals(true, requestBody.get("streamEnabled")); + } + + @Test + public void testCreateOrUpdateSecurityIdentity() throws IOException, InterruptedException { + client.createOrUpdateSecurityIdentity("my_provider", securityIdentityModel()); + verify(httpClient) + .send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); + + assertEquals("PUT", argument.getValue().method()); + assertTrue( + argument + .getValue() + .uri() + .getPath() + .contains("the_org_id/providers/my_provider/permissions")); + assertAuthorizationHeader(); + assertApplicationJsonHeader(); + + Map requestBody = StringSubscriber.toMap(argument.getValue().bodyPublisher()); + + ArrayList members = (ArrayList) requestBody.get("members"); + ArrayList wellKnowns = (ArrayList) requestBody.get("wellKnowns"); + Map identity = (Map) requestBody.get("identity"); + + assertEquals(identityModel().name, members.get(0).get("name")); + assertEquals( + identityModel().additionalInfo.get("foo"), + ((Map) members.get(0).get("additionalInfo")).get("foo")); + assertEquals(identityModel().name, wellKnowns.get(0).get("name")); + assertEquals( + identityModel().additionalInfo.get("foo"), + ((Map) wellKnowns.get(0).get("additionalInfo")).get("foo")); + assertEquals(identityModel().name, identity.get("name")); + assertEquals( + identityModel().additionalInfo.get("foo"), + ((Map) identity.get("additionalInfo")).get("foo")); + } + + @Test + public void testCreateOrUpdateSecurityIdentityAlias() throws IOException, InterruptedException { + client.createOrUpdateSecurityIdentityAlias("my_provider", securityIdentityAliasModel()); + verify(httpClient) + .send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); + + assertEquals("PUT", argument.getValue().method()); + assertTrue( + argument.getValue().uri().getPath().contains("the_org_id/providers/my_provider/mappings")); + assertAuthorizationHeader(); + assertApplicationJsonHeader(); + + Map requestBody = StringSubscriber.toMap(argument.getValue().bodyPublisher()); + + ArrayList mappings = (ArrayList) requestBody.get("mappings"); + ArrayList wellKnowns = (ArrayList) requestBody.get("wellKnowns"); + Map identity = (Map) requestBody.get("identity"); + + assertEquals(aliasMappings()[0].name, mappings.get(0).get("name")); + assertEquals( + aliasMappings()[0].additionalInfo.get("foo"), + ((Map) mappings.get(0).get("additionalInfo")).get("foo")); + assertEquals(identityModel().name, wellKnowns.get(0).get("name")); + assertEquals( + identityModel().additionalInfo.get("foo"), + ((Map) wellKnowns.get(0).get("additionalInfo")).get("foo")); + assertEquals(identityModel().name, identity.get("name")); + assertEquals( + identityModel().additionalInfo.get("foo"), + ((Map) identity.get("additionalInfo")).get("foo")); + } + + @Test + public void testDeleteSecurityIdentity() throws IOException, InterruptedException { + client.deleteSecurityIdentity("my_provider", securityIdentityDelete()); + verify(httpClient) + .send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); + + assertEquals("DELETE", argument.getValue().method()); + assertTrue( + argument + .getValue() + .uri() + .getPath() + .contains("the_org_id/providers/my_provider/permissions")); + assertAuthorizationHeader(); + assertApplicationJsonHeader(); + + Map requestBody = StringSubscriber.toMap(argument.getValue().bodyPublisher()); + Map identity = (Map) requestBody.get("identity"); + + assertEquals(identityModel().name, identity.get("name")); + } + + @Test + public void testManageSecurityIdentities() throws IOException, InterruptedException { + client.manageSecurityIdentities("my_provider", securityIdentityBatchConfig()); + verify(httpClient) + .send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); + + assertEquals("PUT", argument.getValue().method()); + assertTrue( + argument + .getValue() + .uri() + .getPath() + .contains("the_org_id/providers/my_provider/permissions/batch")); + assertTrue( + argument + .getValue() + .uri() + .getQuery() + .contains(String.format("fileId=%s", securityIdentityBatchConfig().getFileId()))); + assertTrue( + argument + .getValue() + .uri() + .getQuery() + .contains( + String.format("orderingId=%s", securityIdentityBatchConfig().getOrderingId()))); + assertAuthorizationHeader(); + assertApplicationJsonHeader(); + } + + @Test + public void testAppendOrderingId() throws IOException, InterruptedException { + String standardOrderingParam = client.appendOrderingId(1234L); + String noOrderingParam = client.appendOrderingId(0L); + + assertTrue(standardOrderingParam.contains(String.format("orderingId=%s", "1234"))); + assertEquals("", noOrderingParam); + } + + @Test + public void testPushDocument() throws IOException, InterruptedException { + client.pushDocument( + "my_source", documentString(), document().uri, CompressionType.UNCOMPRESSED); + verify(httpClient) + .send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); + + assertEquals("PUT", argument.getValue().method()); + assertTrue( + argument.getValue().uri().getPath().contains("the_org_id/sources/my_source/documents")); + assertTrue( + argument + .getValue() + .uri() + .getQuery() + .contains(String.format("documentId=%s", document().uri))); + assertTrue( + argument + .getValue() + .uri() + .getQuery() + .contains( + String.format("compressionType=%s", CompressionType.UNCOMPRESSED.toString()))); + assertAuthorizationHeader(); + assertApplicationJsonHeader(); + + Map requestBody = StringSubscriber.toMap(argument.getValue().bodyPublisher()); + assertEquals(document().title, requestBody.get("title")); + } + + @Test + public void testCreateFileContainer() throws IOException, InterruptedException { + client.createFileContainer(); + verify(httpClient) + .send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); + + assertEquals("POST", argument.getValue().method()); + assertTrue(argument.getValue().uri().getPath().contains("the_org_id/files")); + assertAuthorizationHeader(); + assertApplicationJsonHeader(); + } + + @Test + public void testUploadContentToFileContainer() throws IOException, InterruptedException { + client.uploadContentToFileContainer(fileContainer(), new Gson().toJson(batchUpdateRecord())); + verify(httpClient) + .send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); + + assertEquals("PUT", argument.getValue().method()); + assertTrue(argument.getValue().uri().toString().equals(fileContainer().uploadUri)); + assertEquals( + argument.getValue().headers().map().get("foo").get(0), + fileContainer().requiredHeaders.get("foo")); + + Map requestBody = StringSubscriber.toMap(argument.getValue().bodyPublisher()); + ArrayList addOrUpdate = (ArrayList) requestBody.get("addOrUpdate"); + ArrayList delete = (ArrayList) requestBody.get("delete"); + + assertEquals(document().uri, addOrUpdate.get(0).get("documentId")); + assertEquals(deleteDocument().documentId, delete.get(0).get("documentId")); + } + + @Test + public void testPushFileContainerContent() throws IOException, InterruptedException { + client.pushFileContainerContent("my_source", fileContainer()); + verify(httpClient) + .send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); + + assertEquals("PUT", argument.getValue().method()); + assertTrue( + argument + .getValue() + .uri() + .getPath() + .contains("the_org_id/sources/my_source/documents/batch")); + assertTrue( + argument + .getValue() + .uri() + .getQuery() + .contains(String.format("fileId=%s", fileContainer().fileId))); + assertApplicationJsonHeader(); + assertAuthorizationHeader(); + } + + @Test + public void testOpenStream() throws IOException, InterruptedException { + client.openStream("my_source"); + verify(httpClient) + .send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); + + assertEquals("POST", argument.getValue().method()); + assertTrue( + argument.getValue().uri().getPath().contains("the_org_id/sources/my_source/stream/open")); + assertApplicationJsonHeader(); + assertAuthorizationHeader(); + } + + @Test + public void testRequireStreamChunk() throws IOException, InterruptedException { + client.requireStreamChunk("my_source", "stream_id"); + verify(httpClient) + .send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); + + assertEquals("POST", argument.getValue().method()); + assertTrue( + argument + .getValue() + .uri() + .getPath() + .contains("the_org_id/sources/my_source/stream/stream_id/chunk")); + assertApplicationJsonHeader(); + assertAuthorizationHeader(); + } + + @Test + public void testCloseStream() throws IOException, InterruptedException { + client.closeStream("my_source", "stream_id"); + verify(httpClient) + .send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); + + assertEquals("POST", argument.getValue().method()); + assertTrue( + argument + .getValue() + .uri() + .getPath() + .contains("the_org_id/sources/my_source/stream/stream_id/close")); + assertApplicationJsonHeader(); + assertAuthorizationHeader(); + } + + @Test + public void testDeleteDocument() throws IOException, InterruptedException { + client.deleteDocument("my_source", document().uri, true); + verify(httpClient) + .send(argument.capture(), any(HttpResponse.BodyHandlers.ofString().getClass())); + + assertEquals("DELETE", argument.getValue().method()); + assertTrue( + argument.getValue().uri().getPath().contains("the_org_id/sources/my_source/documents")); + assertTrue(argument.getValue().uri().getQuery().contains("deleteChildren=true")); + assertTrue( + argument + .getValue() + .uri() + .getQuery() + .contains(String.format("documentId=%s", document().uri))); + assertApplicationJsonHeader(); + assertAuthorizationHeader(); + } +} diff --git a/src/test/java/com/coveo/pushapiclient/PlatformUrlBuilderTest.java b/src/test/java/com/coveo/pushapiclient/PlatformUrlBuilderTest.java index 718fb120..adb32378 100644 --- a/src/test/java/com/coveo/pushapiclient/PlatformUrlBuilderTest.java +++ b/src/test/java/com/coveo/pushapiclient/PlatformUrlBuilderTest.java @@ -1,73 +1,63 @@ package com.coveo.pushapiclient; +import static org.junit.Assert.*; + import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.*; - public class PlatformUrlBuilderTest { - private PlatformUrlBuilder platformUrlBuilder; - - @Before - public void setup() { - platformUrlBuilder = new PlatformUrlBuilder(); - } - - @Test - public void testWithDefaultValues() { - PlatformUrl platformUrl = platformUrlBuilder.build(); - assertEquals( - "Should return default platform URL", - "https://platform.cloud.coveo.com", - platformUrl.getPlatformUrl()); - - assertEquals( - "Should return default API URL", - "https://api.cloud.coveo.com", - platformUrl.getApiUrl()); - } - - @Test - public void testWithNonDefaultRegion() { - PlatformUrl platformUrl = platformUrlBuilder.withRegion(Region.EU).build(); - assertEquals( - "Should return Europe platform URL", - "https://platform-eu.cloud.coveo.com", - platformUrl.getPlatformUrl()); - - assertEquals( - "Should return Europe API URL", - "https://api-eu.cloud.coveo.com", - platformUrl.getApiUrl()); - } - - @Test - public void testWithNonDefaultEnvironment() { - PlatformUrl platformUrl = platformUrlBuilder.withEnvironment(Environment.STAGING).build(); - assertEquals( - "Should return the staging platform URL", - "https://platformstg.cloud.coveo.com", - platformUrl.getPlatformUrl()); - - assertEquals( - "Should return the staging API URL", - "https://apistg.cloud.coveo.com", - platformUrl.getApiUrl()); - } - - @Test - public void testWithNonDefaultEnvironmentAndRegion() { - PlatformUrl platformUrl = platformUrlBuilder - .withEnvironment(Environment.DEVELOPMENT) - .withRegion(Region.EU) - .build(); - assertEquals( - "https://platformdev-eu.cloud.coveo.com", - platformUrl.getPlatformUrl()); - - assertEquals( - "https://apidev-eu.cloud.coveo.com", - platformUrl.getApiUrl()); - } + private PlatformUrlBuilder platformUrlBuilder; + + @Before + public void setup() { + platformUrlBuilder = new PlatformUrlBuilder(); + } + + @Test + public void testWithDefaultValues() { + PlatformUrl platformUrl = platformUrlBuilder.build(); + assertEquals( + "Should return default platform URL", + "https://platform.cloud.coveo.com", + platformUrl.getPlatformUrl()); + + assertEquals( + "Should return default API URL", "https://api.cloud.coveo.com", platformUrl.getApiUrl()); + } + + @Test + public void testWithNonDefaultRegion() { + PlatformUrl platformUrl = platformUrlBuilder.withRegion(Region.EU).build(); + assertEquals( + "Should return Europe platform URL", + "https://platform-eu.cloud.coveo.com", + platformUrl.getPlatformUrl()); + + assertEquals( + "Should return Europe API URL", "https://api-eu.cloud.coveo.com", platformUrl.getApiUrl()); + } + + @Test + public void testWithNonDefaultEnvironment() { + PlatformUrl platformUrl = platformUrlBuilder.withEnvironment(Environment.STAGING).build(); + assertEquals( + "Should return the staging platform URL", + "https://platformstg.cloud.coveo.com", + platformUrl.getPlatformUrl()); + + assertEquals( + "Should return the staging API URL", + "https://apistg.cloud.coveo.com", + platformUrl.getApiUrl()); + } + + @Test + public void testWithNonDefaultEnvironmentAndRegion() { + PlatformUrl platformUrl = + platformUrlBuilder.withEnvironment(Environment.DEVELOPMENT).withRegion(Region.EU).build(); + assertEquals("https://platformdev-eu.cloud.coveo.com", platformUrl.getPlatformUrl()); + + assertEquals("https://apidev-eu.cloud.coveo.com", platformUrl.getApiUrl()); + } } diff --git a/src/test/java/com/coveo/pushapiclient/SecurityIdentityBatchConfigTest.java b/src/test/java/com/coveo/pushapiclient/SecurityIdentityBatchConfigTest.java index 3a54e9c5..c2391473 100644 --- a/src/test/java/com/coveo/pushapiclient/SecurityIdentityBatchConfigTest.java +++ b/src/test/java/com/coveo/pushapiclient/SecurityIdentityBatchConfigTest.java @@ -1,54 +1,54 @@ package com.coveo.pushapiclient; +import static org.junit.Assert.*; + import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.*; - public class SecurityIdentityBatchConfigTest { - private SecurityIdentityBatchConfig config1; - private SecurityIdentityBatchConfig config2; - private SecurityIdentityBatchConfig config3; - private SecurityIdentityBatchConfig config4; - private SecurityIdentityBatchConfig config5; - - @Before - public void setUp() { - config1 = new SecurityIdentityBatchConfig("some_file_id", 123L); - config2 = new SecurityIdentityBatchConfig("some_file_id", 123L); - config3 = new SecurityIdentityBatchConfig("some_other_file_id", 123L); - config4 = new SecurityIdentityBatchConfig("some_file_id", 456L); - config5 = config1; - } - - @Test - public void testToString() { - assertEquals(config1.toString(), config1.toString()); - assertEquals(config1.toString(), config2.toString()); - assertEquals(config1.toString(), config5.toString()); - assertEquals(config3.toString(), config3.toString()); - assertNotEquals(config1.toString(), config3.toString()); - assertNotEquals(config3.toString(), config4.toString()); - } - - @Test - public void testEquals() { - assertFalse(config1.equals(null)); - assertTrue(config1.equals(config1)); - assertTrue(config1.equals(config2)); - assertTrue(config1.equals(config5)); - assertFalse(config1.equals(config3)); - assertFalse(config3.equals(config4)); - } - - @Test - public void testHashCode() { - assertEquals(config1.hashCode(), config1.hashCode()); - assertEquals(config1.hashCode(), config2.hashCode()); - assertEquals(config1.hashCode(), config5.hashCode()); - assertEquals(config3.hashCode(), config3.hashCode()); - assertNotEquals(config1.hashCode(), config3.hashCode()); - assertNotEquals(config3.hashCode(), config4.hashCode()); - } -} \ No newline at end of file + private SecurityIdentityBatchConfig config1; + private SecurityIdentityBatchConfig config2; + private SecurityIdentityBatchConfig config3; + private SecurityIdentityBatchConfig config4; + private SecurityIdentityBatchConfig config5; + + @Before + public void setUp() { + config1 = new SecurityIdentityBatchConfig("some_file_id", 123L); + config2 = new SecurityIdentityBatchConfig("some_file_id", 123L); + config3 = new SecurityIdentityBatchConfig("some_other_file_id", 123L); + config4 = new SecurityIdentityBatchConfig("some_file_id", 456L); + config5 = config1; + } + + @Test + public void testToString() { + assertEquals(config1.toString(), config1.toString()); + assertEquals(config1.toString(), config2.toString()); + assertEquals(config1.toString(), config5.toString()); + assertEquals(config3.toString(), config3.toString()); + assertNotEquals(config1.toString(), config3.toString()); + assertNotEquals(config3.toString(), config4.toString()); + } + + @Test + public void testEquals() { + assertFalse(config1.equals(null)); + assertTrue(config1.equals(config1)); + assertTrue(config1.equals(config2)); + assertTrue(config1.equals(config5)); + assertFalse(config1.equals(config3)); + assertFalse(config3.equals(config4)); + } + + @Test + public void testHashCode() { + assertEquals(config1.hashCode(), config1.hashCode()); + assertEquals(config1.hashCode(), config2.hashCode()); + assertEquals(config1.hashCode(), config5.hashCode()); + assertEquals(config3.hashCode(), config3.hashCode()); + assertNotEquals(config1.hashCode(), config3.hashCode()); + assertNotEquals(config3.hashCode(), config4.hashCode()); + } +} diff --git a/src/test/java/com/coveo/pushapiclient/SecurityIdentityDeleteOptionsTest.java b/src/test/java/com/coveo/pushapiclient/SecurityIdentityDeleteOptionsTest.java index b4018d4b..f8834a39 100644 --- a/src/test/java/com/coveo/pushapiclient/SecurityIdentityDeleteOptionsTest.java +++ b/src/test/java/com/coveo/pushapiclient/SecurityIdentityDeleteOptionsTest.java @@ -1,57 +1,57 @@ package com.coveo.pushapiclient; +import static org.junit.Assert.*; + import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.*; - public class SecurityIdentityDeleteOptionsTest { - private SecurityIdentityDeleteOptions opt1; - private SecurityIdentityDeleteOptions opt2; - private SecurityIdentityDeleteOptions opt3; - private SecurityIdentityDeleteOptions opt4; - private SecurityIdentityDeleteOptions opt5; - - @Before - public void setUp() { - opt1 = new SecurityIdentityDeleteOptions(123, 123L); - opt2 = new SecurityIdentityDeleteOptions(123, 123L); - opt3 = new SecurityIdentityDeleteOptions(456, 123L); - opt4 = new SecurityIdentityDeleteOptions(123, 456L); - opt5 = opt1; - } - - @Test - public void testToString() { - assertEquals(opt1.toString(), opt1.toString()); - assertEquals(opt1.toString(), opt2.toString()); - assertEquals(opt1.toString(), opt5.toString()); - assertEquals(opt3.toString(), opt3.toString()); - assertNotEquals(opt1.toString(), opt3.toString()); - assertNotEquals(opt3.toString(), opt4.toString()); - } - - @Test - public void testEquals() { - assertTrue(opt1.equals(opt1)); - assertTrue(opt1.equals(opt2)); - assertTrue(opt1.equals(opt5)); - assertFalse(opt1.equals(opt3)); - assertFalse(opt1.equals(opt4)); - assertFalse(opt3.equals(opt4)); - assertFalse(opt1.equals(null)); - } - - @Test - public void testHashCode() { - assertEquals(opt1.hashCode(), opt1.hashCode()); - assertEquals(opt1.hashCode(), opt2.hashCode()); - assertEquals(opt1.hashCode(), opt5.hashCode()); - assertEquals(opt3.hashCode(), opt3.hashCode()); - assertEquals(opt4.hashCode(), opt4.hashCode()); - assertNotEquals(opt1.hashCode(), opt3.hashCode()); - assertNotEquals(opt1.hashCode(), opt4.hashCode()); - assertNotEquals(opt3.hashCode(), opt4.hashCode()); - } -} \ No newline at end of file + private SecurityIdentityDeleteOptions opt1; + private SecurityIdentityDeleteOptions opt2; + private SecurityIdentityDeleteOptions opt3; + private SecurityIdentityDeleteOptions opt4; + private SecurityIdentityDeleteOptions opt5; + + @Before + public void setUp() { + opt1 = new SecurityIdentityDeleteOptions(123, 123L); + opt2 = new SecurityIdentityDeleteOptions(123, 123L); + opt3 = new SecurityIdentityDeleteOptions(456, 123L); + opt4 = new SecurityIdentityDeleteOptions(123, 456L); + opt5 = opt1; + } + + @Test + public void testToString() { + assertEquals(opt1.toString(), opt1.toString()); + assertEquals(opt1.toString(), opt2.toString()); + assertEquals(opt1.toString(), opt5.toString()); + assertEquals(opt3.toString(), opt3.toString()); + assertNotEquals(opt1.toString(), opt3.toString()); + assertNotEquals(opt3.toString(), opt4.toString()); + } + + @Test + public void testEquals() { + assertTrue(opt1.equals(opt1)); + assertTrue(opt1.equals(opt2)); + assertTrue(opt1.equals(opt5)); + assertFalse(opt1.equals(opt3)); + assertFalse(opt1.equals(opt4)); + assertFalse(opt3.equals(opt4)); + assertFalse(opt1.equals(null)); + } + + @Test + public void testHashCode() { + assertEquals(opt1.hashCode(), opt1.hashCode()); + assertEquals(opt1.hashCode(), opt2.hashCode()); + assertEquals(opt1.hashCode(), opt5.hashCode()); + assertEquals(opt3.hashCode(), opt3.hashCode()); + assertEquals(opt4.hashCode(), opt4.hashCode()); + assertNotEquals(opt1.hashCode(), opt3.hashCode()); + assertNotEquals(opt1.hashCode(), opt4.hashCode()); + assertNotEquals(opt3.hashCode(), opt4.hashCode()); + } +} diff --git a/src/test/java/com/coveo/pushapiclient/SecurityIdentityDeleteTest.java b/src/test/java/com/coveo/pushapiclient/SecurityIdentityDeleteTest.java index 90b06ea6..0cb1fe3d 100644 --- a/src/test/java/com/coveo/pushapiclient/SecurityIdentityDeleteTest.java +++ b/src/test/java/com/coveo/pushapiclient/SecurityIdentityDeleteTest.java @@ -1,71 +1,68 @@ package com.coveo.pushapiclient; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.*; import java.util.HashMap; import java.util.Map; - -import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; public class SecurityIdentityDeleteTest { - private SecurityIdentityDelete sid1; - private SecurityIdentityDelete sid2; - private SecurityIdentityDelete sid3; - private SecurityIdentityDelete sid4; - private SecurityIdentityDelete sid5; - - @Before - public void setUp() { - Map info1 = new HashMap<>(); - Map info2 = new HashMap<>(); - info1.put("key1", "value1"); - info1.put("key2", "value2"); - info2.put("key2.1", "value2.1"); - - IdentityModel id1 = new IdentityModel("some_name", SecurityIdentityType.USER, info1); - IdentityModel id3 = new IdentityModel("some_name", SecurityIdentityType.GROUP, info2); - IdentityModel id4 = new IdentityModel("some_other_name", SecurityIdentityType.USER, null); + private SecurityIdentityDelete sid1; + private SecurityIdentityDelete sid2; + private SecurityIdentityDelete sid3; + private SecurityIdentityDelete sid4; + private SecurityIdentityDelete sid5; - sid1 = new SecurityIdentityDelete(id1); - sid2 = new SecurityIdentityDelete(id1); - sid3 = new SecurityIdentityDelete(id3); - sid4 = new SecurityIdentityDelete(id4); - sid5 = sid1; + @Before + public void setUp() { + Map info1 = new HashMap<>(); + Map info2 = new HashMap<>(); + info1.put("key1", "value1"); + info1.put("key2", "value2"); + info2.put("key2.1", "value2.1"); - } + IdentityModel id1 = new IdentityModel("some_name", SecurityIdentityType.USER, info1); + IdentityModel id3 = new IdentityModel("some_name", SecurityIdentityType.GROUP, info2); + IdentityModel id4 = new IdentityModel("some_other_name", SecurityIdentityType.USER, null); - @Test - public void testToString() { - assertEquals(sid1.toString(), sid1.toString()); - assertEquals(sid1.toString(), sid2.toString()); - assertEquals(sid1.toString(), sid5.toString()); - assertEquals(sid2.toString(), sid5.toString()); - assertEquals(sid3.toString(), sid3.toString()); - assertEquals(sid4.toString(), sid4.toString()); - assertNotEquals(sid1.toString(), sid3.toString()); - assertNotEquals(sid2.toString(), sid4.toString()); - } + sid1 = new SecurityIdentityDelete(id1); + sid2 = new SecurityIdentityDelete(id1); + sid3 = new SecurityIdentityDelete(id3); + sid4 = new SecurityIdentityDelete(id4); + sid5 = sid1; + } - @Test - public void testEquals() { - assertTrue(sid1.equals(sid1)); - assertTrue(sid1.equals(sid2)); - assertTrue(sid1.equals(sid5)); - assertTrue(sid3.equals(sid3)); - assertFalse(sid1.equals(sid3)); - assertFalse(sid3.equals(sid4)); - assertFalse(sid1.equals(null)); - } + @Test + public void testToString() { + assertEquals(sid1.toString(), sid1.toString()); + assertEquals(sid1.toString(), sid2.toString()); + assertEquals(sid1.toString(), sid5.toString()); + assertEquals(sid2.toString(), sid5.toString()); + assertEquals(sid3.toString(), sid3.toString()); + assertEquals(sid4.toString(), sid4.toString()); + assertNotEquals(sid1.toString(), sid3.toString()); + assertNotEquals(sid2.toString(), sid4.toString()); + } - @Test - public void testHashCode() { - assertEquals(sid1.hashCode(), sid1.hashCode()); - assertEquals(sid1.hashCode(), sid2.hashCode()); - assertEquals(sid1.hashCode(), sid5.hashCode()); - assertNotEquals(sid1.hashCode(), sid3.hashCode()); - assertNotEquals(sid3.hashCode(), sid4.hashCode()); + @Test + public void testEquals() { + assertTrue(sid1.equals(sid1)); + assertTrue(sid1.equals(sid2)); + assertTrue(sid1.equals(sid5)); + assertTrue(sid3.equals(sid3)); + assertFalse(sid1.equals(sid3)); + assertFalse(sid3.equals(sid4)); + assertFalse(sid1.equals(null)); + } - } -} \ No newline at end of file + @Test + public void testHashCode() { + assertEquals(sid1.hashCode(), sid1.hashCode()); + assertEquals(sid1.hashCode(), sid2.hashCode()); + assertEquals(sid1.hashCode(), sid5.hashCode()); + assertNotEquals(sid1.hashCode(), sid3.hashCode()); + assertNotEquals(sid3.hashCode(), sid4.hashCode()); + } +} diff --git a/src/test/java/com/coveo/pushapiclient/StreamServiceInternalTest.java b/src/test/java/com/coveo/pushapiclient/StreamServiceInternalTest.java index 5779b240..d850c5e3 100644 --- a/src/test/java/com/coveo/pushapiclient/StreamServiceInternalTest.java +++ b/src/test/java/com/coveo/pushapiclient/StreamServiceInternalTest.java @@ -1,5 +1,12 @@ package com.coveo.pushapiclient; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.coveo.pushapiclient.exceptions.NoOpenStreamException; +import java.io.IOException; +import java.net.http.HttpResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -7,90 +14,76 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import com.coveo.pushapiclient.exceptions.NoOpenStreamException; - -import java.io.IOException; -import java.net.http.HttpResponse; - -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - public class StreamServiceInternalTest { - @Mock - private StreamEnabledSource source; - - @Mock - private DocumentUploadQueue queue; + @Mock private StreamEnabledSource source; - @Mock - private PlatformClient platformClient; + @Mock private DocumentUploadQueue queue; - @InjectMocks - private StreamServiceInternal service; + @Mock private PlatformClient platformClient; - @Mock - private HttpResponse httpResponse; + @InjectMocks private StreamServiceInternal service; - private AutoCloseable closeable; - private DocumentBuilder documentA; - private DocumentBuilder documentB; + @Mock private HttpResponse httpResponse; - @Before - public void setUp() throws Exception { - documentA = new DocumentBuilder("https://my.document.uri?ref=1", "My first document title"); - documentB = new DocumentBuilder("https://my.document.uri?ref=2", "My second document title"); + private AutoCloseable closeable; + private DocumentBuilder documentA; + private DocumentBuilder documentB; - closeable = MockitoAnnotations.openMocks(this); + @Before + public void setUp() throws Exception { + documentA = new DocumentBuilder("https://my.document.uri?ref=1", "My first document title"); + documentB = new DocumentBuilder("https://my.document.uri?ref=2", "My second document title"); - when(httpResponse.body()).thenReturn("{\"streamId\": \"stream-id\"}"); - when(platformClient.openStream("my-source-id")).thenReturn(httpResponse); - when(source.getId()).thenReturn("my-source-id"); - } + closeable = MockitoAnnotations.openMocks(this); - @After - public void closeService() throws Exception { - closeable.close(); - } + when(httpResponse.body()).thenReturn("{\"streamId\": \"stream-id\"}"); + when(platformClient.openStream("my-source-id")).thenReturn(httpResponse); + when(source.getId()).thenReturn("my-source-id"); + } - @Test - public void testAddShouldOpenANewStream() throws IOException, InterruptedException { - service.add(documentA); - service.add(documentB); + @After + public void closeService() throws Exception { + closeable.close(); + } - verify(this.platformClient, times(1)).openStream("my-source-id"); - } + @Test + public void testAddShouldOpenANewStream() throws IOException, InterruptedException { + service.add(documentA); + service.add(documentB); - @Test - public void testAddShouldAddDocumentToQueue() throws IOException, InterruptedException { - service.add(documentA); - service.add(documentB); + verify(this.platformClient, times(1)).openStream("my-source-id"); + } - verify(queue, times(1)).add(documentA); - verify(queue, times(1)).add(documentB); - } + @Test + public void testAddShouldAddDocumentToQueue() throws IOException, InterruptedException { + service.add(documentA); + service.add(documentB); - @Test - public void testCloseShouldCloseOpenStream() throws IOException, InterruptedException, NoOpenStreamException { - service.add(documentA); - service.close(); + verify(queue, times(1)).add(documentA); + verify(queue, times(1)).add(documentB); + } - verify(platformClient, times(1)).closeStream("my-source-id", "stream-id"); - } + @Test + public void testCloseShouldCloseOpenStream() + throws IOException, InterruptedException, NoOpenStreamException { + service.add(documentA); + service.close(); - @Test - public void testCloseShouldFlushBufferedDocuments() - throws IOException, InterruptedException, NoOpenStreamException { - service.add(documentA); - service.close(); + verify(platformClient, times(1)).closeStream("my-source-id", "stream-id"); + } - verify(queue, times(1)).flush(); - } + @Test + public void testCloseShouldFlushBufferedDocuments() + throws IOException, InterruptedException, NoOpenStreamException { + service.add(documentA); + service.close(); - @Test(expected = NoOpenStreamException.class) - public void givenNoOpenStream_whenClose_thenShouldThrow() - throws IOException, InterruptedException, NoOpenStreamException { - service.close(); - } + verify(queue, times(1)).flush(); + } -} \ No newline at end of file + @Test(expected = NoOpenStreamException.class) + public void givenNoOpenStream_whenClose_thenShouldThrow() + throws IOException, InterruptedException, NoOpenStreamException { + service.close(); + } +} diff --git a/src/test/java/com/coveo/pushapiclient/StringSubscriber.java b/src/test/java/com/coveo/pushapiclient/StringSubscriber.java index e061154d..f542d1cc 100644 --- a/src/test/java/com/coveo/pushapiclient/StringSubscriber.java +++ b/src/test/java/com/coveo/pushapiclient/StringSubscriber.java @@ -1,8 +1,6 @@ package com.coveo.pushapiclient; - import com.google.gson.Gson; - import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.ByteBuffer; @@ -14,40 +12,42 @@ class StringSubscriber implements Flow.Subscriber { - HttpResponse.BodySubscriber wrapped; - - public StringSubscriber(HttpResponse.BodySubscriber wrapped) { - this.wrapped = wrapped; - } - - public static Map toMap(Optional bodyPublisher) { - return bodyPublisher.map(p -> { - var bodySubscriber = HttpResponse.BodySubscribers.ofString(StandardCharsets.UTF_8); - var flowSubscriber = new StringSubscriber(bodySubscriber); - p.subscribe(flowSubscriber); - String requestBodyAsString = bodySubscriber.getBody().toCompletableFuture().join(); - return new Gson().fromJson(requestBodyAsString, Map.class); - }).get(); - } - - @Override - public void onSubscribe(Flow.Subscription subscription) { - wrapped.onSubscribe(subscription); - } - - @Override - public void onNext(ByteBuffer item) { - wrapped.onNext(List.of(item)); - } - - @Override - public void onError(Throwable throwable) { - wrapped.onError(throwable); - } - - @Override - public void onComplete() { - wrapped.onComplete(); - } + HttpResponse.BodySubscriber wrapped; + + public StringSubscriber(HttpResponse.BodySubscriber wrapped) { + this.wrapped = wrapped; + } + + public static Map toMap(Optional bodyPublisher) { + return bodyPublisher + .map( + p -> { + var bodySubscriber = HttpResponse.BodySubscribers.ofString(StandardCharsets.UTF_8); + var flowSubscriber = new StringSubscriber(bodySubscriber); + p.subscribe(flowSubscriber); + String requestBodyAsString = bodySubscriber.getBody().toCompletableFuture().join(); + return new Gson().fromJson(requestBodyAsString, Map.class); + }) + .get(); + } + + @Override + public void onSubscribe(Flow.Subscription subscription) { + wrapped.onSubscribe(subscription); + } + + @Override + public void onNext(ByteBuffer item) { + wrapped.onNext(List.of(item)); + } + + @Override + public void onError(Throwable throwable) { + wrapped.onError(throwable); + } + + @Override + public void onComplete() { + wrapped.onComplete(); + } } - diff --git a/src/test/java/com/coveo/pushapiclient/UserSecurityIdentityBuilderTest.java b/src/test/java/com/coveo/pushapiclient/UserSecurityIdentityBuilderTest.java index 65ecd53d..bca5be0b 100644 --- a/src/test/java/com/coveo/pushapiclient/UserSecurityIdentityBuilderTest.java +++ b/src/test/java/com/coveo/pushapiclient/UserSecurityIdentityBuilderTest.java @@ -1,84 +1,85 @@ package com.coveo.pushapiclient; -import org.junit.Before; -import org.junit.Test; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; -public class UserSecurityIdentityBuilderTest { - - private UserSecurityIdentityBuilder usib1; - private UserSecurityIdentityBuilder usib2; - private UserSecurityIdentityBuilder usib3; - private UserSecurityIdentityBuilder usib4; - private UserSecurityIdentityBuilder usib5; - - @Before - public void setUp() { - String[] id1 = new String[]{"identity1", "identity2"}; - String[] id2 = new String[]{"identity2", "identity3"}; - - usib1 = new UserSecurityIdentityBuilder(id1, "some_sec_provider"); - usib2 = new UserSecurityIdentityBuilder(id1, "some_sec_provider"); - usib3 = new UserSecurityIdentityBuilder(id2, "some_sec_provider"); - usib4 = new UserSecurityIdentityBuilder(id1, "some_other_sec_provider"); - usib5 = usib1; - } - - @Test - public void testSingleIdentity() { - SecurityIdentity identityBuilt = new UserSecurityIdentityBuilder("bob@foo.com").build()[0]; - - assertEquals("bob@foo.com", identityBuilt.identity); - assertEquals(SecurityIdentityType.USER, identityBuilt.identityType); - assertEquals("Email Security Provider", identityBuilt.securityProvider); - - } - - @Test - public void testMultipleIdentities() { - SecurityIdentity[] identitiesBuilt = new UserSecurityIdentityBuilder(new String[]{"bob@foo.com", "john@foo.com"}).build(); - - assertEquals("bob@foo.com", identitiesBuilt[0].identity); - assertEquals("john@foo.com", identitiesBuilt[1].identity); - } - - @Test - public void testSecurityProvider() { - SecurityIdentity identityBuilt = new UserSecurityIdentityBuilder("bob@foo.com", "my provider").build()[0]; - - assertEquals("my provider", identityBuilt.securityProvider); - } - - @Test - public void testToString() { - assertEquals(usib1.toString(), usib1.toString()); - assertEquals(usib1.toString(), usib2.toString()); - assertEquals(usib1.toString(), usib5.toString()); - assertNotEquals(usib1.toString(), usib3.toString()); - assertNotEquals(usib3.toString(), usib4.toString()); - } +import org.junit.Before; +import org.junit.Test; - @Test - public void testEquals() { - assertTrue(usib1.equals(usib1)); - assertTrue(usib1.equals(usib2)); - assertTrue(usib1.equals(usib5)); - assertFalse(usib3.equals(usib1)); - assertFalse(usib3.equals(usib4)); - assertFalse(usib1.equals(null)); - } +public class UserSecurityIdentityBuilderTest { - @Test - public void testHashCode() { - assertEquals(usib1.hashCode(), usib1.hashCode()); - assertEquals(usib1.hashCode(), usib2.hashCode()); - assertEquals(usib1.hashCode(), usib5.hashCode()); - assertEquals(usib3.hashCode(), usib3.hashCode()); - assertNotEquals(usib1.hashCode(), usib3.hashCode()); - assertNotEquals(usib3.hashCode(), usib4.hashCode()); - } -} \ No newline at end of file + private UserSecurityIdentityBuilder usib1; + private UserSecurityIdentityBuilder usib2; + private UserSecurityIdentityBuilder usib3; + private UserSecurityIdentityBuilder usib4; + private UserSecurityIdentityBuilder usib5; + + @Before + public void setUp() { + String[] id1 = new String[] {"identity1", "identity2"}; + String[] id2 = new String[] {"identity2", "identity3"}; + + usib1 = new UserSecurityIdentityBuilder(id1, "some_sec_provider"); + usib2 = new UserSecurityIdentityBuilder(id1, "some_sec_provider"); + usib3 = new UserSecurityIdentityBuilder(id2, "some_sec_provider"); + usib4 = new UserSecurityIdentityBuilder(id1, "some_other_sec_provider"); + usib5 = usib1; + } + + @Test + public void testSingleIdentity() { + SecurityIdentity identityBuilt = new UserSecurityIdentityBuilder("bob@foo.com").build()[0]; + + assertEquals("bob@foo.com", identityBuilt.identity); + assertEquals(SecurityIdentityType.USER, identityBuilt.identityType); + assertEquals("Email Security Provider", identityBuilt.securityProvider); + } + + @Test + public void testMultipleIdentities() { + SecurityIdentity[] identitiesBuilt = + new UserSecurityIdentityBuilder(new String[] {"bob@foo.com", "john@foo.com"}).build(); + + assertEquals("bob@foo.com", identitiesBuilt[0].identity); + assertEquals("john@foo.com", identitiesBuilt[1].identity); + } + + @Test + public void testSecurityProvider() { + SecurityIdentity identityBuilt = + new UserSecurityIdentityBuilder("bob@foo.com", "my provider").build()[0]; + + assertEquals("my provider", identityBuilt.securityProvider); + } + + @Test + public void testToString() { + assertEquals(usib1.toString(), usib1.toString()); + assertEquals(usib1.toString(), usib2.toString()); + assertEquals(usib1.toString(), usib5.toString()); + assertNotEquals(usib1.toString(), usib3.toString()); + assertNotEquals(usib3.toString(), usib4.toString()); + } + + @Test + public void testEquals() { + assertTrue(usib1.equals(usib1)); + assertTrue(usib1.equals(usib2)); + assertTrue(usib1.equals(usib5)); + assertFalse(usib3.equals(usib1)); + assertFalse(usib3.equals(usib4)); + assertFalse(usib1.equals(null)); + } + + @Test + public void testHashCode() { + assertEquals(usib1.hashCode(), usib1.hashCode()); + assertEquals(usib1.hashCode(), usib2.hashCode()); + assertEquals(usib1.hashCode(), usib5.hashCode()); + assertEquals(usib3.hashCode(), usib3.hashCode()); + assertNotEquals(usib1.hashCode(), usib3.hashCode()); + assertNotEquals(usib3.hashCode(), usib4.hashCode()); + } +} diff --git a/src/test/java/com/coveo/pushapiclient/VirtualGroupSecurityIdentityBuilderTest.java b/src/test/java/com/coveo/pushapiclient/VirtualGroupSecurityIdentityBuilderTest.java index a3437c6d..2ed2aab9 100644 --- a/src/test/java/com/coveo/pushapiclient/VirtualGroupSecurityIdentityBuilderTest.java +++ b/src/test/java/com/coveo/pushapiclient/VirtualGroupSecurityIdentityBuilderTest.java @@ -1,77 +1,80 @@ package com.coveo.pushapiclient; -import org.junit.Before; -import org.junit.Test; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; +import org.junit.Before; +import org.junit.Test; + public class VirtualGroupSecurityIdentityBuilderTest { - private VirtualGroupSecurityIdentityBuilder vgsib1; - private VirtualGroupSecurityIdentityBuilder vgsib2; - private VirtualGroupSecurityIdentityBuilder vgsib3; - private VirtualGroupSecurityIdentityBuilder vgsib4; - private VirtualGroupSecurityIdentityBuilder vgsib5; + private VirtualGroupSecurityIdentityBuilder vgsib1; + private VirtualGroupSecurityIdentityBuilder vgsib2; + private VirtualGroupSecurityIdentityBuilder vgsib3; + private VirtualGroupSecurityIdentityBuilder vgsib4; + private VirtualGroupSecurityIdentityBuilder vgsib5; - @Before - public void setUp() { - String[] id1 = new String[]{"identity1", "identity2"}; - String[] id2 = new String[]{"identity2", "identity3"}; + @Before + public void setUp() { + String[] id1 = new String[] {"identity1", "identity2"}; + String[] id2 = new String[] {"identity2", "identity3"}; - vgsib1 = new VirtualGroupSecurityIdentityBuilder(id1, "some_sec_provider"); - vgsib2 = new VirtualGroupSecurityIdentityBuilder(id1, "some_sec_provider"); - vgsib3 = new VirtualGroupSecurityIdentityBuilder(id2, "some_sec_provider"); - vgsib4 = new VirtualGroupSecurityIdentityBuilder(id1, "some_other_sec_provider"); - vgsib5 = vgsib1; - } - - @Test - public void testSingleIdentity() { - SecurityIdentity identityBuilt = new VirtualGroupSecurityIdentityBuilder("bob@foo.com", "my provider").build()[0]; + vgsib1 = new VirtualGroupSecurityIdentityBuilder(id1, "some_sec_provider"); + vgsib2 = new VirtualGroupSecurityIdentityBuilder(id1, "some_sec_provider"); + vgsib3 = new VirtualGroupSecurityIdentityBuilder(id2, "some_sec_provider"); + vgsib4 = new VirtualGroupSecurityIdentityBuilder(id1, "some_other_sec_provider"); + vgsib5 = vgsib1; + } - assertEquals("bob@foo.com", identityBuilt.identity); - assertEquals(SecurityIdentityType.VIRTUAL_GROUP, identityBuilt.identityType); - assertEquals("my provider", identityBuilt.securityProvider); + @Test + public void testSingleIdentity() { + SecurityIdentity identityBuilt = + new VirtualGroupSecurityIdentityBuilder("bob@foo.com", "my provider").build()[0]; - } + assertEquals("bob@foo.com", identityBuilt.identity); + assertEquals(SecurityIdentityType.VIRTUAL_GROUP, identityBuilt.identityType); + assertEquals("my provider", identityBuilt.securityProvider); + } - @Test - public void testMultipleIdentities() { - SecurityIdentity[] identitiesBuilt = new VirtualGroupSecurityIdentityBuilder(new String[]{"bob@foo.com", "john@foo.com"}, "my provider").build(); + @Test + public void testMultipleIdentities() { + SecurityIdentity[] identitiesBuilt = + new VirtualGroupSecurityIdentityBuilder( + new String[] {"bob@foo.com", "john@foo.com"}, "my provider") + .build(); - assertEquals("bob@foo.com", identitiesBuilt[0].identity); - assertEquals("john@foo.com", identitiesBuilt[1].identity); - } + assertEquals("bob@foo.com", identitiesBuilt[0].identity); + assertEquals("john@foo.com", identitiesBuilt[1].identity); + } - @Test - public void testToString() { - assertEquals(vgsib1.toString(), vgsib1.toString()); - assertEquals(vgsib1.toString(), vgsib2.toString()); - assertEquals(vgsib1.toString(), vgsib5.toString()); - assertNotEquals(vgsib1.toString(), vgsib3.toString()); - assertNotEquals(vgsib3.toString(), vgsib4.toString()); - } + @Test + public void testToString() { + assertEquals(vgsib1.toString(), vgsib1.toString()); + assertEquals(vgsib1.toString(), vgsib2.toString()); + assertEquals(vgsib1.toString(), vgsib5.toString()); + assertNotEquals(vgsib1.toString(), vgsib3.toString()); + assertNotEquals(vgsib3.toString(), vgsib4.toString()); + } - @Test - public void testEquals() { - assertTrue(vgsib1.equals(vgsib1)); - assertTrue(vgsib1.equals(vgsib2)); - assertTrue(vgsib1.equals(vgsib5)); - assertFalse(vgsib3.equals(vgsib1)); - assertFalse(vgsib3.equals(vgsib4)); - assertFalse(vgsib1.equals(null)); - } + @Test + public void testEquals() { + assertTrue(vgsib1.equals(vgsib1)); + assertTrue(vgsib1.equals(vgsib2)); + assertTrue(vgsib1.equals(vgsib5)); + assertFalse(vgsib3.equals(vgsib1)); + assertFalse(vgsib3.equals(vgsib4)); + assertFalse(vgsib1.equals(null)); + } - @Test - public void testHashCode() { - assertEquals(vgsib1.hashCode(), vgsib1.hashCode()); - assertEquals(vgsib1.hashCode(), vgsib2.hashCode()); - assertEquals(vgsib1.hashCode(), vgsib5.hashCode()); - assertEquals(vgsib3.hashCode(), vgsib3.hashCode()); - assertNotEquals(vgsib1.hashCode(), vgsib3.hashCode()); - assertNotEquals(vgsib3.hashCode(), vgsib4.hashCode()); - } -} \ No newline at end of file + @Test + public void testHashCode() { + assertEquals(vgsib1.hashCode(), vgsib1.hashCode()); + assertEquals(vgsib1.hashCode(), vgsib2.hashCode()); + assertEquals(vgsib1.hashCode(), vgsib5.hashCode()); + assertEquals(vgsib3.hashCode(), vgsib3.hashCode()); + assertNotEquals(vgsib1.hashCode(), vgsib3.hashCode()); + assertNotEquals(vgsib3.hashCode(), vgsib4.hashCode()); + } +} From a86a248fc360117986c59276c1a60959de363c93 Mon Sep 17 00:00:00 2001 From: ylakhdar Date: Fri, 9 Jun 2023 11:47:26 -0400 Subject: [PATCH 6/8] chore: remove old files --- .gitignore | 2 +- .vscode/code-style.xml | 337 ----------------------------------------- 2 files changed, 1 insertion(+), 338 deletions(-) delete mode 100644 .vscode/code-style.xml diff --git a/.gitignore b/.gitignore index 61ca0e58..8744fae7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ /target/ .env /.idea/ -.vscode/* +.vscode diff --git a/.vscode/code-style.xml b/.vscode/code-style.xml deleted file mode 100644 index bb335f00..00000000 --- a/.vscode/code-style.xml +++ /dev/null @@ -1,337 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - From e9bbaaeccf27a76df6d933da463f9d9b22aa4bc0 Mon Sep 17 00:00:00 2001 From: ylakhdar Date: Fri, 9 Jun 2023 11:48:04 -0400 Subject: [PATCH 7/8] chore: revert commit diff --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 8744fae7..d5a7ca72 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ /target/ .env /.idea/ -.vscode +.vscode \ No newline at end of file From 3db7f8cad4a9dd1db4009c0804e207bee181be78 Mon Sep 17 00:00:00 2001 From: ylakhdar Date: Fri, 9 Jun 2023 12:07:18 -0400 Subject: [PATCH 8/8] format --- .../com/coveo/pushapiclient/PushService.java | 89 ++++++------- .../pushapiclient/PushServiceInternal.java | 27 ++-- .../PushServiceInternalTest.java | 123 +++++++++--------- 3 files changed, 116 insertions(+), 123 deletions(-) diff --git a/src/main/java/com/coveo/pushapiclient/PushService.java b/src/main/java/com/coveo/pushapiclient/PushService.java index 185203f0..8691fe83 100644 --- a/src/main/java/com/coveo/pushapiclient/PushService.java +++ b/src/main/java/com/coveo/pushapiclient/PushService.java @@ -1,51 +1,52 @@ package com.coveo.pushapiclient; +import com.google.gson.Gson; import java.io.IOException; import java.net.http.HttpResponse; -import com.google.gson.Gson; - public class PushService { - private final PushEnabledSource source; - private final PlatformClient platformClient; - private PushServiceInternal service; - - public PushService(PushEnabledSource source) { - String apiKey = source.getApiKey(); - String organizationId = source.getOrganizationId(); - PlatformUrl platformUrl = source.getPlatformUrl(); - UploadStrategy uploader = this.getUploadStrategy(); - DocumentUploadQueue queue = new DocumentUploadQueue(uploader); - - this.platformClient = new PlatformClient(apiKey, organizationId, platformUrl); - this.service = new PushServiceInternal(queue); - this.source = source; - } - - public void addOrUpdate(DocumentBuilder document) throws IOException, InterruptedException { - // TODO: LENS-843: include partial document updates - this.service.addOrUpdate(document); - } - - public void delete(DeleteDocument document) throws IOException, InterruptedException { - this.service.delete(document); - } - - public void close() throws IOException, InterruptedException { - this.service.close(); - } - - private UploadStrategy getUploadStrategy() { - return (batchUpdate) -> { - String sourceId = this.getSourceId(); - HttpResponse resFileContainer = this.platformClient.createFileContainer(); - FileContainer fileContainer = new Gson().fromJson(resFileContainer.body(), FileContainer.class); - this.platformClient.uploadContentToFileContainer(fileContainer, new Gson().toJson(batchUpdate.marshal())); - return this.platformClient.pushFileContainerContent(sourceId, fileContainer); - }; - } - - private String getSourceId() { - return this.source.getId(); - } + private final PushEnabledSource source; + private final PlatformClient platformClient; + private PushServiceInternal service; + + public PushService(PushEnabledSource source) { + String apiKey = source.getApiKey(); + String organizationId = source.getOrganizationId(); + PlatformUrl platformUrl = source.getPlatformUrl(); + UploadStrategy uploader = this.getUploadStrategy(); + DocumentUploadQueue queue = new DocumentUploadQueue(uploader); + + this.platformClient = new PlatformClient(apiKey, organizationId, platformUrl); + this.service = new PushServiceInternal(queue); + this.source = source; + } + + public void addOrUpdate(DocumentBuilder document) throws IOException, InterruptedException { + // TODO: LENS-843: include partial document updates + this.service.addOrUpdate(document); + } + + public void delete(DeleteDocument document) throws IOException, InterruptedException { + this.service.delete(document); + } + + public void close() throws IOException, InterruptedException { + this.service.close(); + } + + private UploadStrategy getUploadStrategy() { + return (batchUpdate) -> { + String sourceId = this.getSourceId(); + HttpResponse resFileContainer = this.platformClient.createFileContainer(); + FileContainer fileContainer = + new Gson().fromJson(resFileContainer.body(), FileContainer.class); + this.platformClient.uploadContentToFileContainer( + fileContainer, new Gson().toJson(batchUpdate.marshal())); + return this.platformClient.pushFileContainerContent(sourceId, fileContainer); + }; + } + + private String getSourceId() { + return this.source.getId(); + } } diff --git a/src/main/java/com/coveo/pushapiclient/PushServiceInternal.java b/src/main/java/com/coveo/pushapiclient/PushServiceInternal.java index 7f3f0c4c..a082c887 100644 --- a/src/main/java/com/coveo/pushapiclient/PushServiceInternal.java +++ b/src/main/java/com/coveo/pushapiclient/PushServiceInternal.java @@ -3,22 +3,21 @@ import java.io.IOException; public class PushServiceInternal { - private DocumentUploadQueue queue; + private DocumentUploadQueue queue; - public PushServiceInternal(DocumentUploadQueue queue) { - this.queue = queue; - } + public PushServiceInternal(DocumentUploadQueue queue) { + this.queue = queue; + } - public void addOrUpdate(DocumentBuilder document) throws IOException, InterruptedException { - this.queue.add(document); - } + public void addOrUpdate(DocumentBuilder document) throws IOException, InterruptedException { + this.queue.add(document); + } - public void delete(DeleteDocument document) throws IOException, InterruptedException { - this.queue.add(document); - } - - public void close() throws IOException, InterruptedException { - queue.flush(); - } + public void delete(DeleteDocument document) throws IOException, InterruptedException { + this.queue.add(document); + } + public void close() throws IOException, InterruptedException { + queue.flush(); + } } diff --git a/src/test/java/com/coveo/pushapiclient/PushServiceInternalTest.java b/src/test/java/com/coveo/pushapiclient/PushServiceInternalTest.java index 2a214f7e..99fd43cb 100644 --- a/src/test/java/com/coveo/pushapiclient/PushServiceInternalTest.java +++ b/src/test/java/com/coveo/pushapiclient/PushServiceInternalTest.java @@ -1,5 +1,11 @@ package com.coveo.pushapiclient; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import com.coveo.pushapiclient.exceptions.NoOpenStreamException; +import java.io.IOException; +import java.net.http.HttpResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -7,69 +13,56 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import com.coveo.pushapiclient.exceptions.NoOpenStreamException; - -import java.io.IOException; -import java.net.http.HttpResponse; - -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - public class PushServiceInternalTest { - @Mock - private DocumentUploadQueue queue; - - @InjectMocks - private PushServiceInternal service; - - @Mock - private HttpResponse httpResponse; - - private AutoCloseable closeable; - private DocumentBuilder documentA; - private DocumentBuilder documentB; - private DeleteDocument documentC; - - @Before - public void setUp() throws Exception { - documentA = new DocumentBuilder("https://my.document.uri?ref=1", "My first document title"); - documentB = new DocumentBuilder("https://my.document.uri?ref=2", "My second document title"); - documentC = new DeleteDocument("https://my.document.uri?ref=3"); - - closeable = MockitoAnnotations.openMocks(this); - - } - - @After - public void closeService() throws Exception { - closeable.close(); - } - - @Test - public void testShouldAddNewDocumentToQueue() throws IOException, InterruptedException { - service.addOrUpdate(documentA); - service.addOrUpdate(documentB); - - verify(this.queue, times(1)).add(documentA); - verify(this.queue, times(1)).add(documentB); - } - - @Test - public void testAddShouldAddDocumentToDeleteToQueue() throws IOException, InterruptedException { - service.delete(documentC); - - verify(queue, times(1)).add(documentC); - } - - @Test - public void testCloseShouldFlushBufferedDocuments() - throws IOException, InterruptedException, NoOpenStreamException { - service.addOrUpdate(documentA); - service.addOrUpdate(documentB); - service.delete(documentC); - service.close(); - - verify(queue, times(1)).flush(); - } - -} \ No newline at end of file + @Mock private DocumentUploadQueue queue; + + @InjectMocks private PushServiceInternal service; + + @Mock private HttpResponse httpResponse; + + private AutoCloseable closeable; + private DocumentBuilder documentA; + private DocumentBuilder documentB; + private DeleteDocument documentC; + + @Before + public void setUp() throws Exception { + documentA = new DocumentBuilder("https://my.document.uri?ref=1", "My first document title"); + documentB = new DocumentBuilder("https://my.document.uri?ref=2", "My second document title"); + documentC = new DeleteDocument("https://my.document.uri?ref=3"); + + closeable = MockitoAnnotations.openMocks(this); + } + + @After + public void closeService() throws Exception { + closeable.close(); + } + + @Test + public void testShouldAddNewDocumentToQueue() throws IOException, InterruptedException { + service.addOrUpdate(documentA); + service.addOrUpdate(documentB); + + verify(this.queue, times(1)).add(documentA); + verify(this.queue, times(1)).add(documentB); + } + + @Test + public void testAddShouldAddDocumentToDeleteToQueue() throws IOException, InterruptedException { + service.delete(documentC); + + verify(queue, times(1)).add(documentC); + } + + @Test + public void testCloseShouldFlushBufferedDocuments() + throws IOException, InterruptedException, NoOpenStreamException { + service.addOrUpdate(documentA); + service.addOrUpdate(documentB); + service.delete(documentC); + service.close(); + + verify(queue, times(1)).flush(); + } +}