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 66355664..bd83a2bc 100644
--- a/src/main/java/com/coveo/pushapiclient/DocumentUploadQueue.java
+++ b/src/main/java/com/coveo/pushapiclient/DocumentUploadQueue.java
@@ -3,99 +3,93 @@
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();
- }
- 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 the {@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 deleted 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();
- }
- documentToDeleteList.add(document);
- this.size += sizeOfDoc;
+ final int sizeOfDoc = document.marshal().getBytes().length;
+ if (this.size + sizeOfDoc >= this.maxQueueSize) {
+ this.flush();
}
+ documentToAddList.add(document);
+ this.size += sizeOfDoc;
+ }
- public BatchUpdate getBatch() {
- return new BatchUpdate(
- new ArrayList(this.documentToAddList),
- new ArrayList(this.documentToDeleteList));
+ /**
+ * Adds the {@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 deleted 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();
}
+ 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/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/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 97c11087..f488f3a5 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,182 +18,189 @@
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;
+ @Mock private UploadStrategy uploadStrategy;
- private String generateStringFromBytes(int numBytes) {
- // Check if the number of bytes is valid
- if (numBytes <= 0) {
- return "";
- }
+ @InjectMocks private DocumentUploadQueue queue;
- // Create a byte array with the specified length
- byte[] bytes = new byte[numBytes];
+ private AutoCloseable closeable;
+ private DocumentBuilder documentToAdd;
+ private DeleteDocument documentToDelete;
- // 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;
- }
+ private int oneMegaByte = 1 * 1024 * 1024;
- return new String(bytes);
+ private String generateStringFromBytes(int numBytes) {
+ // Check if the number of bytes is valid
+ if (numBytes <= 0) {
+ return "";
}
- 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);
+ // Create a byte array with the specified length
+ byte[] bytes = new byte[numBytes];
- documentToDelete = new DeleteDocument("https://my.document.uri?ref=3");
-
- closeable = MockitoAnnotations.openMocks(this);
- }
-
- @After
- public void closeService() throws Exception {
- closeable.close();
+ // 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 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 testFlushShouldNotUploadDocumentsWhenRequiredSizeIsNotMet() throws IOException, InterruptedException {
- // Adding 2MB document to the queue => queue has now 3MB of free space
- // (5MB - 2MB = 3MB)
- queue.add(documentToAdd);
- // Adding 2MB document to the queue => queue has now 1MB of free space
- // (3MB - 2MB = 1MB)
- queue.add(documentToDelete);
-
- // The maximum queue size has not been reached yet (1MB left of free space).
- // Therefore, the accumulated documents will not be automatically flushed.
- // Unless the user runs `.flush()` the queue will keep the 4MB of documents
- 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 by 1MB. Therefore, the 2 first added documents will automatically be
- // uploaded to the source.
- queue.add(firstBulkyDocument);
- queue.add(secondBulkyDocument);
- verify(uploadStrategy, times(0)).apply(any(BatchUpdate.class));
-
- // 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 testFlushShouldNotUploadDocumentsWhenRequiredSizeIsNotMet()
+ throws IOException, InterruptedException {
+ // Adding 2MB document to the queue => queue has now 3MB of free space
+ // (5MB - 2MB = 3MB)
+ queue.add(documentToAdd);
+ // Adding 2MB document to the queue => queue has now 1MB of free space
+ // (3MB - 2MB = 1MB)
+ queue.add(documentToDelete);
+
+ // The maximum queue size has not been reached yet (1MB left of free space).
+ // Therefore, the accumulated documents will not be automatically flushed.
+ // Unless the user runs `.flush()` the queue will keep the 4MB of documents
+ 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 by 1MB. Therefore, the 2 first added documents will automatically be
+ // uploaded to the source.
+ queue.add(firstBulkyDocument);
+ queue.add(secondBulkyDocument);
+ verify(uploadStrategy, times(0)).apply(any(BatchUpdate.class));
+
+ // 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