From b1b9e48dd8f332d19d909f54ea48307ced5b665a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ianar=C3=A9=20S=C3=A9vi?= Date: Fri, 19 Dec 2025 10:44:03 +0100 Subject: [PATCH 1/4] bit stricter checkstyle --- checkstyle.xml | 1 + pom.xml | 6 +++++- src/main/java/com/mindee/MindeeClient.java | 1 + .../mindee/cli/CommandLineInterfaceProducts.java | 1 + src/main/java/com/mindee/cli/ProductProcessor.java | 2 ++ .../java/com/mindee/extraction/ExtractedImage.java | 1 + .../java/com/mindee/extraction/ExtractedPDF.java | 2 ++ .../java/com/mindee/extraction/ImageExtractor.java | 2 ++ .../java/com/mindee/extraction/PDFExtractor.java | 4 +++- src/main/java/com/mindee/http/MindeeHttpApi.java | 4 ++-- src/main/java/com/mindee/input/PageOptions.java | 2 ++ src/main/java/com/mindee/input/URLInputSource.java | 14 ++++++++++++++ .../parsing/common/LocalDateTimeDeserializer.java | 6 +++++- .../mindee/parsing/custom/lineitems/LineItems.java | 1 + .../mindee/parsing/generated/GeneratedFeature.java | 1 + .../com/mindee/parsing/standard/BaseField.java | 10 +++++++++- src/main/java/com/mindee/pdf/PdfOperation.java | 2 +- src/main/java/com/mindee/pdf/PdfPageImage.java | 1 + .../FinancialDocumentV1Document.java | 2 +- .../FinancialDocumentV1LineItem.java | 2 +- .../mindee/product/fr/idcard/IdCardV1Document.java | 4 ++-- .../mindee/product/invoice/InvoiceV4LineItem.java | 2 +- .../product/passport/PassportV1Document.java | 4 ++-- .../product/us/bankcheck/BankCheckV1Page.java | 3 ++- 24 files changed, 63 insertions(+), 15 deletions(-) diff --git a/checkstyle.xml b/checkstyle.xml index 51b8e10d5..21556b93a 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -326,6 +326,7 @@ + diff --git a/pom.xml b/pom.xml index 8e59689fc..6ac3a2cae 100644 --- a/pom.xml +++ b/pom.xml @@ -97,7 +97,7 @@ org.apache.maven.plugins maven-checkstyle-plugin - 3.2.1 + 3.6.0 com.puppycrawl.tools @@ -132,6 +132,10 @@ 8 + + org.apache.maven.plugins + maven-checkstyle-plugin + org.sonatype.central central-publishing-maven-plugin diff --git a/src/main/java/com/mindee/MindeeClient.java b/src/main/java/com/mindee/MindeeClient.java index ec0a98c88..c5c9a7127 100644 --- a/src/main/java/com/mindee/MindeeClient.java +++ b/src/main/java/com/mindee/MindeeClient.java @@ -416,6 +416,7 @@ public AsyncPredictResponse enqueueAndParse( } /** + * Validate async polling options. * @param pollingOptions Options for async call parameters * @throws MindeeException Throws if settings aren't set properly. */ diff --git a/src/main/java/com/mindee/cli/CommandLineInterfaceProducts.java b/src/main/java/com/mindee/cli/CommandLineInterfaceProducts.java index 1e5908286..36fd18bd4 100644 --- a/src/main/java/com/mindee/cli/CommandLineInterfaceProducts.java +++ b/src/main/java/com/mindee/cli/CommandLineInterfaceProducts.java @@ -36,6 +36,7 @@ public class CommandLineInterfaceProducts { private final ProductProcessor processor; /** + * Default constructor. * @param processor Processor instance to render the products. */ public CommandLineInterfaceProducts(ProductProcessor processor) { diff --git a/src/main/java/com/mindee/cli/ProductProcessor.java b/src/main/java/com/mindee/cli/ProductProcessor.java index 3931d3485..d44167ac8 100644 --- a/src/main/java/com/mindee/cli/ProductProcessor.java +++ b/src/main/java/com/mindee/cli/ProductProcessor.java @@ -16,6 +16,7 @@ ) public interface ProductProcessor { /** + * Process a product synchronously. * @param productClass Product class to be processed for synchronous products. * @param file Input file. * @param Type of the product. @@ -25,6 +26,7 @@ public interface ProductProcessor { > String standardProductOutput(Class productClass, File file) throws IOException; /** + * Process a product asynchronously. * @param productClass Product class to be processed for asynchronous products. * @param file Input file. * @param Type of the product. diff --git a/src/main/java/com/mindee/extraction/ExtractedImage.java b/src/main/java/com/mindee/extraction/ExtractedImage.java index c5e84a4a5..f6adfcdd5 100644 --- a/src/main/java/com/mindee/extraction/ExtractedImage.java +++ b/src/main/java/com/mindee/extraction/ExtractedImage.java @@ -20,6 +20,7 @@ public class ExtractedImage { private final String saveFormat; /** + * Default constructor. * @param image Buffered image object. * @param filename Name of the extracted image. * @param saveFormat Format to save the image as, defaults to PNG. diff --git a/src/main/java/com/mindee/extraction/ExtractedPDF.java b/src/main/java/com/mindee/extraction/ExtractedPDF.java index bbe0ad912..eef26c013 100644 --- a/src/main/java/com/mindee/extraction/ExtractedPDF.java +++ b/src/main/java/com/mindee/extraction/ExtractedPDF.java @@ -19,6 +19,8 @@ public class ExtractedPDF { private final String filename; /** + * Default constructor. + * * @param pdf PDF wrapper object. * @param filename Name of the extracted file. */ diff --git a/src/main/java/com/mindee/extraction/ImageExtractor.java b/src/main/java/com/mindee/extraction/ImageExtractor.java index c48fda835..c89803611 100644 --- a/src/main/java/com/mindee/extraction/ImageExtractor.java +++ b/src/main/java/com/mindee/extraction/ImageExtractor.java @@ -57,6 +57,8 @@ public ImageExtractor(LocalInputSource source) throws IOException { } /** + * Get the number of pages in the file. + * * @return The number of pages in the file. */ public int getPageCount() { diff --git a/src/main/java/com/mindee/extraction/PDFExtractor.java b/src/main/java/com/mindee/extraction/PDFExtractor.java index 55b5f7b02..b9a0a7ecb 100644 --- a/src/main/java/com/mindee/extraction/PDFExtractor.java +++ b/src/main/java/com/mindee/extraction/PDFExtractor.java @@ -64,7 +64,9 @@ public PDFExtractor(LocalInputSource source) throws IOException { } /** - * @return The number of pages in the file. + * Get the number of pages in the PDF file. + * + * @return The number of pages in the PDF file. */ public int getPageCount() { return sourcePdf.getNumberOfPages(); diff --git a/src/main/java/com/mindee/http/MindeeHttpApi.java b/src/main/java/com/mindee/http/MindeeHttpApi.java index 0433d5b7a..2278e285d 100644 --- a/src/main/java/com/mindee/http/MindeeHttpApi.java +++ b/src/main/java/com/mindee/http/MindeeHttpApi.java @@ -50,7 +50,7 @@ public final class MindeeHttpApi extends MindeeApi { private final MindeeSettings mindeeSettings; /** * The HttpClientBuilder used to create HttpClient objects used to make api calls over http. - * Defaults to HttpClientBuilder.create().useSystemProperties() + * Defaults to HttpClientBuilder.create().useSystemProperties(). */ private final HttpClientBuilder httpClientBuilder; /** @@ -145,7 +145,7 @@ private MindeeHttpApi( } /** - * GET job status and document for an enqueued job + * GET job status and document for an enqueued job. */ public AsyncPredictResponse documentQueueGet( Class documentClass, diff --git a/src/main/java/com/mindee/input/PageOptions.java b/src/main/java/com/mindee/input/PageOptions.java index dad3e9220..2f3cfb564 100644 --- a/src/main/java/com/mindee/input/PageOptions.java +++ b/src/main/java/com/mindee/input/PageOptions.java @@ -28,6 +28,7 @@ public class PageOptions { Integer onMinPages; /** + * Default constructor. * @deprecated Use the Builder pattern instead. */ @Deprecated @@ -36,6 +37,7 @@ public PageOptions(List pages) { } /** + * Constructor with operation. * @deprecated Use the Builder pattern instead. */ @Deprecated diff --git a/src/main/java/com/mindee/input/URLInputSource.java b/src/main/java/com/mindee/input/URLInputSource.java index de9f67871..73c6f4798 100644 --- a/src/main/java/com/mindee/input/URLInputSource.java +++ b/src/main/java/com/mindee/input/URLInputSource.java @@ -26,6 +26,9 @@ public class URLInputSource { private String localFilename; private final String token; + /** + * Private constructor. + */ URLInputSource(Builder builder) { this.url = builder.url; this.username = builder.username; @@ -35,6 +38,7 @@ public class URLInputSource { } /** + * Creates a new builder for an URLInputSource. * @param url URL to fetch the file from. * @return An instance of {@link URLInputSource}. */ @@ -188,6 +192,8 @@ public static class Builder { private String token; /** + * Default constructor. + * * @param url Remote URL resource. */ public Builder(String url) { @@ -195,6 +201,8 @@ public Builder(String url) { } /** + * Builder method to set the token for remote access. + * * @param token Token for remote access requiring an authentication Token. * @return An instance of the builder. */ @@ -204,6 +212,8 @@ public Builder withToken(String token) { } /** + * Builder method to set the username and password for remote authentication. + * * @param username Username for remote authentication. * @param password Password for remote authentication. * @return An instance of the builder. @@ -215,6 +225,8 @@ public Builder withCredentials(String username, String password) { } /** + * Builder method to set the local filename for the downloaded file. + * * @param filename Filename to give to the file. * @return An instance of the builder. */ @@ -225,6 +237,8 @@ public Builder withLocalFilename(String filename) { /** + * Build the {@link URLInputSource} object. + * * @return A valid {@link URLInputSource} object. */ public URLInputSource build() { diff --git a/src/main/java/com/mindee/parsing/common/LocalDateTimeDeserializer.java b/src/main/java/com/mindee/parsing/common/LocalDateTimeDeserializer.java index 3aadcd05c..6cf4d7b62 100644 --- a/src/main/java/com/mindee/parsing/common/LocalDateTimeDeserializer.java +++ b/src/main/java/com/mindee/parsing/common/LocalDateTimeDeserializer.java @@ -12,9 +12,13 @@ import java.time.temporal.TemporalAccessor; /** - * Deserializer for LocalDateTime + * Deserializer for LocalDateTime. */ public class LocalDateTimeDeserializer extends JsonDeserializer { + + /** + * Deserialize a LocalDateTime from a JSON string. + */ @Override public LocalDateTime deserialize( JsonParser jsonParser, diff --git a/src/main/java/com/mindee/parsing/custom/lineitems/LineItems.java b/src/main/java/com/mindee/parsing/custom/lineitems/LineItems.java index 84426cf9d..692f5cd11 100644 --- a/src/main/java/com/mindee/parsing/custom/lineitems/LineItems.java +++ b/src/main/java/com/mindee/parsing/custom/lineitems/LineItems.java @@ -12,6 +12,7 @@ public class LineItems { private List rows; /** + * Default constructor. * @param rows */ public LineItems(List rows) { diff --git a/src/main/java/com/mindee/parsing/generated/GeneratedFeature.java b/src/main/java/com/mindee/parsing/generated/GeneratedFeature.java index 56a4da469..e6dd2e714 100644 --- a/src/main/java/com/mindee/parsing/generated/GeneratedFeature.java +++ b/src/main/java/com/mindee/parsing/generated/GeneratedFeature.java @@ -54,6 +54,7 @@ public StringField asStringField() { } /** + * Represent the feature as a standard {@link BooleanField}. * @return An instance of a {@link BooleanField}. */ public BooleanField asBooleanField() { diff --git a/src/main/java/com/mindee/parsing/standard/BaseField.java b/src/main/java/com/mindee/parsing/standard/BaseField.java index 939208841..371600e62 100644 --- a/src/main/java/com/mindee/parsing/standard/BaseField.java +++ b/src/main/java/com/mindee/parsing/standard/BaseField.java @@ -24,7 +24,7 @@ public abstract class BaseField implements PositionData { @JsonIgnore private final Polygon boundingBox; /** - * Define the coordinates of the zone in the page where the values has been found. + * Define the coordinates of the zone in the page where the value has been found. */ @JsonProperty("polygon") @JsonDeserialize(using = PolygonDeserializer.class) @@ -41,6 +41,9 @@ public abstract class BaseField implements PositionData { @JsonProperty("page_id") private Integer pageId; + /** + * JSON constructor. + */ protected BaseField( @JsonProperty("confidence") Double confidence, @@ -60,6 +63,9 @@ protected BaseField( } } + /** + * Default constructor. + */ protected BaseField() { if (polygon != null) { this.boundingBox = BoundingBoxUtils.createBoundingBoxFrom(this.polygon); @@ -69,6 +75,8 @@ protected BaseField() { } /** + * Whether the field is empty or not. + * * @return true if the field is empty, false otherwise. */ public abstract boolean isEmpty(); diff --git a/src/main/java/com/mindee/pdf/PdfOperation.java b/src/main/java/com/mindee/pdf/PdfOperation.java index 4b3c4fdc2..7d1466c28 100644 --- a/src/main/java/com/mindee/pdf/PdfOperation.java +++ b/src/main/java/com/mindee/pdf/PdfOperation.java @@ -11,7 +11,7 @@ public interface PdfOperation { * Split a PDF file. * * @param splitQuery Options to perform the query. - * @return The split pdf. + * @return The split PDF. */ SplitPdf split(SplitQuery splitQuery) throws IOException; } diff --git a/src/main/java/com/mindee/pdf/PdfPageImage.java b/src/main/java/com/mindee/pdf/PdfPageImage.java index 6732f5352..aba11cf10 100644 --- a/src/main/java/com/mindee/pdf/PdfPageImage.java +++ b/src/main/java/com/mindee/pdf/PdfPageImage.java @@ -51,6 +51,7 @@ public void writeToFile(String outputPath) throws IOException, MindeeException { } /** + * Generate a filename for the image. * @return An auto-generated filename String. */ public String getFilename() { diff --git a/src/main/java/com/mindee/product/financialdocument/FinancialDocumentV1Document.java b/src/main/java/com/mindee/product/financialdocument/FinancialDocumentV1Document.java index 925b8c6eb..83d527c66 100644 --- a/src/main/java/com/mindee/product/financialdocument/FinancialDocumentV1Document.java +++ b/src/main/java/com/mindee/product/financialdocument/FinancialDocumentV1Document.java @@ -175,7 +175,7 @@ public class FinancialDocumentV1Document extends Prediction { @JsonProperty("time") protected StringField time; /** - * The total amount of tip and gratuity + * The total amount of tip and gratuity. */ @JsonProperty("tip") protected AmountField tip; diff --git a/src/main/java/com/mindee/product/financialdocument/FinancialDocumentV1LineItem.java b/src/main/java/com/mindee/product/financialdocument/FinancialDocumentV1LineItem.java index 34f8fe7a0..3cc48cbdc 100644 --- a/src/main/java/com/mindee/product/financialdocument/FinancialDocumentV1LineItem.java +++ b/src/main/java/com/mindee/product/financialdocument/FinancialDocumentV1LineItem.java @@ -27,7 +27,7 @@ public class FinancialDocumentV1LineItem extends BaseField implements LineItemFi @JsonProperty("product_code") String productCode; /** - * The item quantity + * The item quantity. */ @JsonProperty("quantity") Double quantity; diff --git a/src/main/java/com/mindee/product/fr/idcard/IdCardV1Document.java b/src/main/java/com/mindee/product/fr/idcard/IdCardV1Document.java index b5ccbadbf..df19ddd79 100644 --- a/src/main/java/com/mindee/product/fr/idcard/IdCardV1Document.java +++ b/src/main/java/com/mindee/product/fr/idcard/IdCardV1Document.java @@ -55,12 +55,12 @@ public class IdCardV1Document extends Prediction { @JsonProperty("id_number") protected StringField idNumber; /** - * Machine Readable Zone, first line + * Machine Readable Zone, first line. */ @JsonProperty("mrz1") protected StringField mrz1; /** - * Machine Readable Zone, second line + * Machine Readable Zone, second line. */ @JsonProperty("mrz2") protected StringField mrz2; diff --git a/src/main/java/com/mindee/product/invoice/InvoiceV4LineItem.java b/src/main/java/com/mindee/product/invoice/InvoiceV4LineItem.java index d6c02d015..614a91b92 100644 --- a/src/main/java/com/mindee/product/invoice/InvoiceV4LineItem.java +++ b/src/main/java/com/mindee/product/invoice/InvoiceV4LineItem.java @@ -27,7 +27,7 @@ public class InvoiceV4LineItem extends BaseField implements LineItemField { @JsonProperty("product_code") String productCode; /** - * The item quantity + * The item quantity. */ @JsonProperty("quantity") Double quantity; diff --git a/src/main/java/com/mindee/product/passport/PassportV1Document.java b/src/main/java/com/mindee/product/passport/PassportV1Document.java index 3e7606e67..70ed3b7ae 100644 --- a/src/main/java/com/mindee/product/passport/PassportV1Document.java +++ b/src/main/java/com/mindee/product/passport/PassportV1Document.java @@ -60,12 +60,12 @@ public class PassportV1Document extends Prediction { @JsonProperty("issuance_date") protected DateField issuanceDate; /** - * Machine Readable Zone, first line + * Machine Readable Zone, first line. */ @JsonProperty("mrz1") protected StringField mrz1; /** - * Machine Readable Zone, second line + * Machine Readable Zone, second line. */ @JsonProperty("mrz2") protected StringField mrz2; diff --git a/src/main/java/com/mindee/product/us/bankcheck/BankCheckV1Page.java b/src/main/java/com/mindee/product/us/bankcheck/BankCheckV1Page.java index 3e9bc056f..e1496c099 100644 --- a/src/main/java/com/mindee/product/us/bankcheck/BankCheckV1Page.java +++ b/src/main/java/com/mindee/product/us/bankcheck/BankCheckV1Page.java @@ -22,8 +22,9 @@ public class BankCheckV1Page extends BankCheckV1Document { */ @JsonProperty("check_position") protected PositionField checkPosition; + /** - * List of signature positions + * List of signature positions. */ @JsonProperty("signatures_positions") protected List signaturesPositions = new ArrayList<>(); From 0bfd109c82e01b499954507017543a70428af1f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ianar=C3=A9=20S=C3=A9vi?= Date: Fri, 19 Dec 2025 11:20:21 +0100 Subject: [PATCH 2/4] add spotless --- .github/workflows/_static-analysis.yml | 2 +- pom.xml | 26 +++++++++++++++++-- .../java/com/mindee/MindeeClientTest.java | 18 ++++++------- .../java/com/mindee/MindeeClientV2Test.java | 10 +++---- .../java/com/mindee/TestingUtilities.java | 4 +-- .../mindee/extraction/ImageExtractorTest.java | 12 ++++----- .../mindee/extraction/PDFExtractorTest.java | 4 +-- .../com/mindee/input/FileCompressionTest.java | 19 +++++++------- .../mindee/input/LocalInputSourceTest.java | 7 +++-- .../com/mindee/input/LocalResponseV1Test.java | 8 +++--- .../com/mindee/input/LocalResponseV2Test.java | 9 +++---- .../com/mindee/input/URLInputSourceTest.java | 13 +++++----- .../common/AsyncPredictResponseTest.java | 8 +++--- .../mindee/parsing/common/CropperTest.java | 8 +++--- .../com/mindee/parsing/common/ErrorTest.java | 8 +++--- .../parsing/common/FullTextOcrTest.java | 6 ++--- .../com/mindee/parsing/common/OcrTest.java | 10 +++---- .../custom/lineitems/FakeListField.java | 6 ++--- .../com/mindee/parsing/v2/InferenceTest.java | 4 +-- .../java/com/mindee/parsing/v2/JobTest.java | 11 ++++---- .../java/com/mindee/pdf/PDFUtilsTest.java | 5 ++-- .../java/com/mindee/pdf/PdfOperationTest.java | 11 ++++---- .../barcodereader/BarcodeReaderV1Test.java | 10 +++---- .../billoflading/BillOfLadingV1Test.java | 10 +++---- .../businesscard/BusinessCardV1Test.java | 10 +++---- .../mindee/product/cropper/CropperV1Test.java | 10 +++---- .../mindee/product/custom/CustomV1Test.java | 10 +++---- .../custom/CustomV1WithLineItemsTest.java | 9 +++---- .../deliverynote/DeliveryNoteV1Test.java | 10 +++---- .../driverlicense/DriverLicenseV1Test.java | 10 +++---- .../FinancialDocumentV1Test.java | 10 +++---- .../BankAccountDetailsV1Test.java | 10 +++---- .../BankAccountDetailsV2Test.java | 10 +++---- .../fr/cartegrise/CarteGriseV1Test.java | 10 +++---- .../fr/energybill/EnergyBillV1Test.java | 10 +++---- .../fr/healthcard/HealthCardV1Test.java | 10 +++---- .../product/fr/idcard/IdCardV1Test.java | 10 +++---- .../product/fr/idcard/IdCardV2Test.java | 10 +++---- .../product/fr/payslip/PayslipV2Test.java | 10 +++---- .../product/fr/payslip/PayslipV3Test.java | 10 +++---- .../product/generated/GeneratedV1Test.java | 8 +++--- .../indianpassport/IndianPassportV1Test.java | 10 +++---- .../InternationalIdV2Test.java | 10 +++---- .../mindee/product/invoice/InvoiceV4Test.java | 10 +++---- .../InvoiceSplitterV1Test.java | 10 +++---- .../MultiReceiptsDetectorV1Test.java | 10 +++---- .../NutritionFactsLabelV1Test.java | 10 +++---- .../product/passport/PassportV1Test.java | 10 +++---- .../mindee/product/receipt/ReceiptV5Test.java | 10 +++---- .../mindee/product/resume/ResumeV1Test.java | 10 +++---- .../product/us/bankcheck/BankCheckV1Test.java | 10 +++---- .../healthcarecard/HealthcareCardV1Test.java | 10 +++---- .../product/us/usmail/UsMailV3Test.java | 10 +++---- .../java/com/mindee/workflow/WorkflowIT.java | 4 +-- 54 files changed, 267 insertions(+), 253 deletions(-) diff --git a/.github/workflows/_static-analysis.yml b/.github/workflows/_static-analysis.yml index b95c9c16d..5c89e2b90 100644 --- a/.github/workflows/_static-analysis.yml +++ b/.github/workflows/_static-analysis.yml @@ -20,4 +20,4 @@ jobs: cache: "maven" - name: Check Code Style - run: mvn --update-snapshots --no-transfer-progress checkstyle:check + run: mvn --update-snapshots --no-transfer-progress process-sources diff --git a/pom.xml b/pom.xml index 6ac3a2cae..5bdb5993f 100644 --- a/pom.xml +++ b/pom.xml @@ -102,7 +102,7 @@ com.puppycrawl.tools checkstyle - 10.9.3 + 10.12.7 @@ -113,7 +113,24 @@ - validate + process-sources + + check + + + + + + com.diffplug.spotless + spotless-maven-plugin + 2.30.0 + + + + + + + validate check @@ -123,6 +140,7 @@ + org.apache.maven.plugins @@ -132,6 +150,10 @@ 8 + + com.diffplug.spotless + spotless-maven-plugin + org.apache.maven.plugins maven-checkstyle-plugin diff --git a/src/test/java/com/mindee/MindeeClientTest.java b/src/test/java/com/mindee/MindeeClientTest.java index 3884959a6..68c182102 100644 --- a/src/test/java/com/mindee/MindeeClientTest.java +++ b/src/test/java/com/mindee/MindeeClientTest.java @@ -1,23 +1,26 @@ package com.mindee; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getResourcePath; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.mindee.http.Endpoint; -import com.mindee.input.LocalResponse; -import com.mindee.input.LocalInputSource; import com.mindee.http.MindeeApi; import com.mindee.http.RequestParameters; +import com.mindee.input.LocalInputSource; +import com.mindee.input.LocalResponse; import com.mindee.input.PageOptions; import com.mindee.input.PageOptionsOperation; import com.mindee.parsing.common.AsyncPredictResponse; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.Job; import com.mindee.parsing.common.PredictResponse; -import static com.mindee.TestingUtilities.assertStringEqualsFile; +import com.mindee.pdf.PdfOperation; +import com.mindee.pdf.SplitPdf; import com.mindee.product.custom.CustomV1; import com.mindee.product.generated.GeneratedV1; -import com.mindee.product.invoice.InvoiceV4; import com.mindee.product.internationalid.InternationalIdV2; -import com.mindee.pdf.PdfOperation; -import com.mindee.pdf.SplitPdf; +import com.mindee.product.invoice.InvoiceV4; import java.io.File; import java.io.IOException; import java.net.URL; @@ -33,9 +36,6 @@ import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; -import static com.mindee.TestingUtilities.getResourcePath; -import static com.mindee.TestingUtilities.getV1ResourcePathString; - @ExtendWith(MockitoExtension.class) class MindeeClientTest { diff --git a/src/test/java/com/mindee/MindeeClientV2Test.java b/src/test/java/com/mindee/MindeeClientV2Test.java index 5dc4031c8..e01c64e83 100644 --- a/src/test/java/com/mindee/MindeeClientV2Test.java +++ b/src/test/java/com/mindee/MindeeClientV2Test.java @@ -1,5 +1,10 @@ package com.mindee; +import static com.mindee.TestingUtilities.getResourcePath; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.http.MindeeApiV2; @@ -14,11 +19,6 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import static com.mindee.TestingUtilities.getResourcePath; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; - @DisplayName("MindeeV2 – Client and API Tests") class MindeeClientV2Test { /** diff --git a/src/test/java/com/mindee/TestingUtilities.java b/src/test/java/com/mindee/TestingUtilities.java index 5433aa9d5..cba05f158 100644 --- a/src/test/java/com/mindee/TestingUtilities.java +++ b/src/test/java/com/mindee/TestingUtilities.java @@ -1,13 +1,12 @@ package com.mindee; -import org.junit.jupiter.api.Assertions; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Objects; +import org.junit.jupiter.api.Assertions; public class TestingUtilities { public static Path getResourcePath(String filePath) { @@ -156,4 +155,3 @@ public static double levenshteinRatio(String referenceString, String targetStrin } } - diff --git a/src/test/java/com/mindee/extraction/ImageExtractorTest.java b/src/test/java/com/mindee/extraction/ImageExtractorTest.java index bb8df9ad0..fe170bd33 100644 --- a/src/test/java/com/mindee/extraction/ImageExtractorTest.java +++ b/src/test/java/com/mindee/extraction/ImageExtractorTest.java @@ -1,5 +1,9 @@ package com.mindee.extraction; +import static com.mindee.TestingUtilities.getResourcePath; +import static com.mindee.TestingUtilities.getV1ResourcePath; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.input.LocalInputSource; @@ -9,14 +13,10 @@ import com.mindee.product.barcodereader.BarcodeReaderV1Document; import com.mindee.product.multireceiptsdetector.MultiReceiptsDetectorV1; import com.mindee.product.multireceiptsdetector.MultiReceiptsDetectorV1Document; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.List; - -import static com.mindee.TestingUtilities.getResourcePath; -import static com.mindee.TestingUtilities.getV1ResourcePath; -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class ImageExtractorTest { diff --git a/src/test/java/com/mindee/extraction/PDFExtractorTest.java b/src/test/java/com/mindee/extraction/PDFExtractorTest.java index 846b55919..b8fb3c027 100644 --- a/src/test/java/com/mindee/extraction/PDFExtractorTest.java +++ b/src/test/java/com/mindee/extraction/PDFExtractorTest.java @@ -1,5 +1,7 @@ package com.mindee.extraction; +import static com.mindee.TestingUtilities.getV1ResourcePath; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.input.LocalInputSource; @@ -10,8 +12,6 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import static com.mindee.TestingUtilities.getV1ResourcePath; - public class PDFExtractorTest { protected PredictResponse getInvoiceSplitterPrediction() throws diff --git a/src/test/java/com/mindee/input/FileCompressionTest.java b/src/test/java/com/mindee/input/FileCompressionTest.java index cda43ad8d..5d32563ef 100644 --- a/src/test/java/com/mindee/input/FileCompressionTest.java +++ b/src/test/java/com/mindee/input/FileCompressionTest.java @@ -1,14 +1,10 @@ package com.mindee.input; +import static com.mindee.TestingUtilities.getResourcePath; +import static com.mindee.TestingUtilities.getV1ResourcePath; + import com.mindee.image.ImageCompressor; import com.mindee.pdf.PdfCompressor; -import org.apache.pdfbox.Loader; -import org.apache.pdfbox.pdmodel.PDDocument; -import org.apache.pdfbox.text.PDFTextStripper; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.IOException; import java.nio.file.Files; @@ -16,9 +12,12 @@ import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; - -import static com.mindee.TestingUtilities.getResourcePath; -import static com.mindee.TestingUtilities.getV1ResourcePath; +import javax.imageio.ImageIO; +import org.apache.pdfbox.Loader; +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.text.PDFTextStripper; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class FileCompressionTest { diff --git a/src/test/java/com/mindee/input/LocalInputSourceTest.java b/src/test/java/com/mindee/input/LocalInputSourceTest.java index 3daa237d1..4d1d4e15c 100644 --- a/src/test/java/com/mindee/input/LocalInputSourceTest.java +++ b/src/test/java/com/mindee/input/LocalInputSourceTest.java @@ -1,18 +1,17 @@ package com.mindee.input; +import static com.mindee.TestingUtilities.getResourcePath; +import static com.mindee.TestingUtilities.getV1ResourcePath; + import com.mindee.MindeeException; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; - import org.apache.commons.codec.binary.Base64; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import static com.mindee.TestingUtilities.getResourcePath; -import static com.mindee.TestingUtilities.getV1ResourcePath; - public class LocalInputSourceTest { void assertMultipagePDF(LocalInputSource inputSource, Path filePath) throws IOException { Assertions.assertNotNull(inputSource); diff --git a/src/test/java/com/mindee/input/LocalResponseV1Test.java b/src/test/java/com/mindee/input/LocalResponseV1Test.java index 32bdf3537..a17bfa944 100644 --- a/src/test/java/com/mindee/input/LocalResponseV1Test.java +++ b/src/test/java/com/mindee/input/LocalResponseV1Test.java @@ -1,13 +1,13 @@ package com.mindee.input; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; +import static com.mindee.TestingUtilities.getV1ResourcePath; + import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; - -import static com.mindee.TestingUtilities.getV1ResourcePath; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class LocalResponseV1Test { diff --git a/src/test/java/com/mindee/input/LocalResponseV2Test.java b/src/test/java/com/mindee/input/LocalResponseV2Test.java index fb5b71ea4..dbfbd7590 100644 --- a/src/test/java/com/mindee/input/LocalResponseV2Test.java +++ b/src/test/java/com/mindee/input/LocalResponseV2Test.java @@ -1,15 +1,14 @@ package com.mindee.input; -import com.mindee.parsing.v2.InferenceResponse; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; +import static com.mindee.TestingUtilities.getV2ResourcePath; +import com.mindee.parsing.v2.InferenceResponse; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; - -import static com.mindee.TestingUtilities.getV2ResourcePath; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class LocalResponseV2Test { diff --git a/src/test/java/com/mindee/input/URLInputSourceTest.java b/src/test/java/com/mindee/input/URLInputSourceTest.java index e61d4952a..9ae3a1e8f 100644 --- a/src/test/java/com/mindee/input/URLInputSourceTest.java +++ b/src/test/java/com/mindee/input/URLInputSourceTest.java @@ -1,17 +1,16 @@ package com.mindee.input; -import java.nio.file.Path; -import java.nio.file.Paths; -import lombok.Setter; -import org.junit.jupiter.api.*; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; import java.io.File; import java.io.IOException; import java.net.HttpURLConnection; import java.nio.file.Files; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; +import java.nio.file.Path; +import java.nio.file.Paths; +import lombok.Setter; +import org.junit.jupiter.api.*; public class URLInputSourceTest { diff --git a/src/test/java/com/mindee/parsing/common/AsyncPredictResponseTest.java b/src/test/java/com/mindee/parsing/common/AsyncPredictResponseTest.java index 4f2a828db..c583dc71b 100644 --- a/src/test/java/com/mindee/parsing/common/AsyncPredictResponseTest.java +++ b/src/test/java/com/mindee/parsing/common/AsyncPredictResponseTest.java @@ -1,16 +1,16 @@ package com.mindee.parsing.common; +import static com.mindee.TestingUtilities.getV1ResourcePath; + import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.product.invoicesplitter.InvoiceSplitterV1; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; import java.nio.file.Path; - -import static com.mindee.TestingUtilities.getV1ResourcePath; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class AsyncPredictResponseTest { diff --git a/src/test/java/com/mindee/parsing/common/CropperTest.java b/src/test/java/com/mindee/parsing/common/CropperTest.java index 9b99bc2f0..0eb8083d7 100644 --- a/src/test/java/com/mindee/parsing/common/CropperTest.java +++ b/src/test/java/com/mindee/parsing/common/CropperTest.java @@ -1,16 +1,16 @@ package com.mindee.parsing.common; +import static com.mindee.TestingUtilities.getV1ResourcePath; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.standard.PositionField; import com.mindee.product.receipt.ReceiptV5; import com.mindee.product.receipt.ReceiptV5Document; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.List; - -import static com.mindee.TestingUtilities.getV1ResourcePath; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class CropperTest { diff --git a/src/test/java/com/mindee/parsing/common/ErrorTest.java b/src/test/java/com/mindee/parsing/common/ErrorTest.java index 9462d1090..cdef158af 100644 --- a/src/test/java/com/mindee/parsing/common/ErrorTest.java +++ b/src/test/java/com/mindee/parsing/common/ErrorTest.java @@ -1,12 +1,12 @@ package com.mindee.parsing.common; +import static com.mindee.TestingUtilities.getV1ResourcePath; + import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePath; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class ErrorTest { diff --git a/src/test/java/com/mindee/parsing/common/FullTextOcrTest.java b/src/test/java/com/mindee/parsing/common/FullTextOcrTest.java index 94e5382fc..4ab295b49 100644 --- a/src/test/java/com/mindee/parsing/common/FullTextOcrTest.java +++ b/src/test/java/com/mindee/parsing/common/FullTextOcrTest.java @@ -1,5 +1,7 @@ package com.mindee.parsing.common; +import static com.mindee.TestingUtilities.getV1ResourcePath; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.product.internationalid.InternationalIdV2; @@ -7,10 +9,8 @@ import java.io.IOException; import java.nio.file.Files; import java.util.List; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Assertions; - -import static com.mindee.TestingUtilities.getV1ResourcePath; +import org.junit.jupiter.api.Test; public class FullTextOcrTest { private Inference loadInference() throws IOException { diff --git a/src/test/java/com/mindee/parsing/common/OcrTest.java b/src/test/java/com/mindee/parsing/common/OcrTest.java index e8b0df446..3fea8976d 100644 --- a/src/test/java/com/mindee/parsing/common/OcrTest.java +++ b/src/test/java/com/mindee/parsing/common/OcrTest.java @@ -1,19 +1,19 @@ package com.mindee.parsing.common; +import static com.mindee.TestingUtilities.getV1ResourcePath; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; -import com.mindee.parsing.common.ocr.Word; import com.mindee.parsing.common.ocr.Ocr; +import com.mindee.parsing.common.ocr.Word; import com.mindee.product.receipt.ReceiptV5; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; - -import static com.mindee.TestingUtilities.getV1ResourcePath; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class OcrTest { diff --git a/src/test/java/com/mindee/parsing/custom/lineitems/FakeListField.java b/src/test/java/com/mindee/parsing/custom/lineitems/FakeListField.java index 505089ab4..8b1357a83 100644 --- a/src/test/java/com/mindee/parsing/custom/lineitems/FakeListField.java +++ b/src/test/java/com/mindee/parsing/custom/lineitems/FakeListField.java @@ -1,12 +1,12 @@ package com.mindee.parsing.custom.lineitems; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; import com.mindee.geometry.Point; import com.mindee.geometry.Polygon; import com.mindee.parsing.custom.ListField; import com.mindee.parsing.custom.ListFieldValue; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; class FakeListField { private FakeListField() { diff --git a/src/test/java/com/mindee/parsing/v2/InferenceTest.java b/src/test/java/com/mindee/parsing/v2/InferenceTest.java index 790d1db14..24222238b 100644 --- a/src/test/java/com/mindee/parsing/v2/InferenceTest.java +++ b/src/test/java/com/mindee/parsing/v2/InferenceTest.java @@ -8,13 +8,13 @@ import com.mindee.geometry.Polygon; import com.mindee.input.LocalResponse; import com.mindee.parsing.v2.field.DynamicField; +import com.mindee.parsing.v2.field.DynamicField.FieldType; import com.mindee.parsing.v2.field.FieldConfidence; import com.mindee.parsing.v2.field.FieldLocation; import com.mindee.parsing.v2.field.InferenceFields; -import com.mindee.parsing.v2.field.SimpleField; import com.mindee.parsing.v2.field.ListField; import com.mindee.parsing.v2.field.ObjectField; -import com.mindee.parsing.v2.field.DynamicField.FieldType; +import com.mindee.parsing.v2.field.SimpleField; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; diff --git a/src/test/java/com/mindee/parsing/v2/JobTest.java b/src/test/java/com/mindee/parsing/v2/JobTest.java index bec940ac2..cbfb915ff 100644 --- a/src/test/java/com/mindee/parsing/v2/JobTest.java +++ b/src/test/java/com/mindee/parsing/v2/JobTest.java @@ -1,15 +1,16 @@ package com.mindee.parsing.v2; -import com.mindee.input.LocalResponse; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Nested; -import org.junit.jupiter.api.Test; -import java.io.IOException; import static com.mindee.TestingUtilities.getV2ResourcePath; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import com.mindee.input.LocalResponse; +import java.io.IOException; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + @DisplayName("MindeeV2 - Job Tests") public class JobTest { private JobResponse loadJob(String filePath) throws IOException { diff --git a/src/test/java/com/mindee/pdf/PDFUtilsTest.java b/src/test/java/com/mindee/pdf/PDFUtilsTest.java index 433d3d371..4c12aa837 100644 --- a/src/test/java/com/mindee/pdf/PDFUtilsTest.java +++ b/src/test/java/com/mindee/pdf/PDFUtilsTest.java @@ -1,5 +1,7 @@ package com.mindee.pdf; +import static com.mindee.TestingUtilities.getResourcePath; + import com.mindee.input.LocalInputSource; import java.io.File; import java.io.IOException; @@ -10,15 +12,12 @@ import java.util.Arrays; import java.util.List; import java.util.Random; - import org.apache.pdfbox.Loader; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import static com.mindee.TestingUtilities.getResourcePath; - public class PDFUtilsTest { diff --git a/src/test/java/com/mindee/pdf/PdfOperationTest.java b/src/test/java/com/mindee/pdf/PdfOperationTest.java index 0d4ad8e2b..9a5ba2fa7 100644 --- a/src/test/java/com/mindee/pdf/PdfOperationTest.java +++ b/src/test/java/com/mindee/pdf/PdfOperationTest.java @@ -1,17 +1,16 @@ package com.mindee.pdf; +import static com.mindee.TestingUtilities.getResourcePath; + +import com.mindee.MindeeException; import com.mindee.input.PageOptions; import com.mindee.input.PageOptionsOperation; -import com.mindee.MindeeException; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; - -import static com.mindee.TestingUtilities.getResourcePath; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class PdfOperationTest { diff --git a/src/test/java/com/mindee/product/barcodereader/BarcodeReaderV1Test.java b/src/test/java/com/mindee/product/barcodereader/BarcodeReaderV1Test.java index bb1a005df..a772a9432 100644 --- a/src/test/java/com/mindee/product/barcodereader/BarcodeReaderV1Test.java +++ b/src/test/java/com/mindee/product/barcodereader/BarcodeReaderV1Test.java @@ -1,16 +1,16 @@ package com.mindee.product.barcodereader; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; -import static com.mindee.TestingUtilities.assertStringEqualsFile; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit tests for BarcodeReaderV1. diff --git a/src/test/java/com/mindee/product/billoflading/BillOfLadingV1Test.java b/src/test/java/com/mindee/product/billoflading/BillOfLadingV1Test.java index e7da3ec0f..17aa9125b 100644 --- a/src/test/java/com/mindee/product/billoflading/BillOfLadingV1Test.java +++ b/src/test/java/com/mindee/product/billoflading/BillOfLadingV1Test.java @@ -1,16 +1,16 @@ package com.mindee.product.billoflading; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; -import static com.mindee.TestingUtilities.assertStringEqualsFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit tests for BillOfLadingV1. diff --git a/src/test/java/com/mindee/product/businesscard/BusinessCardV1Test.java b/src/test/java/com/mindee/product/businesscard/BusinessCardV1Test.java index c85a003e8..7b387eaff 100644 --- a/src/test/java/com/mindee/product/businesscard/BusinessCardV1Test.java +++ b/src/test/java/com/mindee/product/businesscard/BusinessCardV1Test.java @@ -1,17 +1,17 @@ package com.mindee.product.businesscard; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; import com.mindee.parsing.standard.ClassificationField; -import static com.mindee.TestingUtilities.assertStringEqualsFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit tests for BusinessCardV1. diff --git a/src/test/java/com/mindee/product/cropper/CropperV1Test.java b/src/test/java/com/mindee/product/cropper/CropperV1Test.java index 35b127aed..e4ab47f11 100644 --- a/src/test/java/com/mindee/product/cropper/CropperV1Test.java +++ b/src/test/java/com/mindee/product/cropper/CropperV1Test.java @@ -1,18 +1,18 @@ package com.mindee.product.cropper; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.Page; import com.mindee.parsing.common.PredictResponse; import com.mindee.parsing.standard.ClassificationField; -import static com.mindee.TestingUtilities.assertStringEqualsFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit tests for CropperV1. diff --git a/src/test/java/com/mindee/product/custom/CustomV1Test.java b/src/test/java/com/mindee/product/custom/CustomV1Test.java index 04c1e6d11..d648d1d5c 100644 --- a/src/test/java/com/mindee/product/custom/CustomV1Test.java +++ b/src/test/java/com/mindee/product/custom/CustomV1Test.java @@ -1,5 +1,8 @@ package com.mindee.product.custom; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; @@ -7,14 +10,11 @@ import com.mindee.parsing.common.PredictResponse; import com.mindee.parsing.custom.ListField; import com.mindee.parsing.custom.ListFieldValue; -import static com.mindee.TestingUtilities.assertStringEqualsFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; import java.util.Map; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; class CustomV1Test { diff --git a/src/test/java/com/mindee/product/custom/CustomV1WithLineItemsTest.java b/src/test/java/com/mindee/product/custom/CustomV1WithLineItemsTest.java index 685026da5..a38ebe922 100644 --- a/src/test/java/com/mindee/product/custom/CustomV1WithLineItemsTest.java +++ b/src/test/java/com/mindee/product/custom/CustomV1WithLineItemsTest.java @@ -1,5 +1,7 @@ package com.mindee.product.custom; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.PredictResponse; @@ -7,14 +9,11 @@ import com.mindee.parsing.custom.lineitems.Line; import com.mindee.parsing.custom.lineitems.LineItems; import com.mindee.parsing.custom.lineitems.LineItemsGenerator; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.io.File; import java.io.IOException; import java.util.Arrays; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; class CustomV1WithLineItemsTest { diff --git a/src/test/java/com/mindee/product/deliverynote/DeliveryNoteV1Test.java b/src/test/java/com/mindee/product/deliverynote/DeliveryNoteV1Test.java index 21ecd105a..028a463ac 100644 --- a/src/test/java/com/mindee/product/deliverynote/DeliveryNoteV1Test.java +++ b/src/test/java/com/mindee/product/deliverynote/DeliveryNoteV1Test.java @@ -1,17 +1,17 @@ package com.mindee.product.deliverynote; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; import com.mindee.parsing.standard.ClassificationField; -import static com.mindee.TestingUtilities.assertStringEqualsFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit tests for DeliveryNoteV1. diff --git a/src/test/java/com/mindee/product/driverlicense/DriverLicenseV1Test.java b/src/test/java/com/mindee/product/driverlicense/DriverLicenseV1Test.java index 2b06b50b5..2eea61d84 100644 --- a/src/test/java/com/mindee/product/driverlicense/DriverLicenseV1Test.java +++ b/src/test/java/com/mindee/product/driverlicense/DriverLicenseV1Test.java @@ -1,17 +1,17 @@ package com.mindee.product.driverlicense; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; import com.mindee.parsing.standard.ClassificationField; -import static com.mindee.TestingUtilities.assertStringEqualsFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit tests for DriverLicenseV1. diff --git a/src/test/java/com/mindee/product/financialdocument/FinancialDocumentV1Test.java b/src/test/java/com/mindee/product/financialdocument/FinancialDocumentV1Test.java index 7a377a51c..9d67960d4 100644 --- a/src/test/java/com/mindee/product/financialdocument/FinancialDocumentV1Test.java +++ b/src/test/java/com/mindee/product/financialdocument/FinancialDocumentV1Test.java @@ -1,19 +1,19 @@ package com.mindee.product.financialdocument; +import static com.mindee.TestingUtilities.getV1ResourcePath; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; - -import static com.mindee.TestingUtilities.getV1ResourcePath; -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; class FinancialDocumentV1Test { diff --git a/src/test/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV1Test.java b/src/test/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV1Test.java index 056121529..129600cf1 100644 --- a/src/test/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV1Test.java +++ b/src/test/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV1Test.java @@ -1,17 +1,17 @@ package com.mindee.product.fr.bankaccountdetails; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; import com.mindee.parsing.standard.ClassificationField; -import static com.mindee.TestingUtilities.assertStringEqualsFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit tests for BankAccountDetailsV1. diff --git a/src/test/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV2Test.java b/src/test/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV2Test.java index 792977c69..543762216 100644 --- a/src/test/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV2Test.java +++ b/src/test/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV2Test.java @@ -1,17 +1,17 @@ package com.mindee.product.fr.bankaccountdetails; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; import com.mindee.parsing.standard.ClassificationField; -import static com.mindee.TestingUtilities.assertStringEqualsFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit tests for BankAccountDetailsV2. diff --git a/src/test/java/com/mindee/product/fr/cartegrise/CarteGriseV1Test.java b/src/test/java/com/mindee/product/fr/cartegrise/CarteGriseV1Test.java index cadb3bf57..4426162c5 100644 --- a/src/test/java/com/mindee/product/fr/cartegrise/CarteGriseV1Test.java +++ b/src/test/java/com/mindee/product/fr/cartegrise/CarteGriseV1Test.java @@ -1,17 +1,17 @@ package com.mindee.product.fr.cartegrise; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; import com.mindee.parsing.standard.ClassificationField; -import static com.mindee.TestingUtilities.assertStringEqualsFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit tests for CarteGriseV1. diff --git a/src/test/java/com/mindee/product/fr/energybill/EnergyBillV1Test.java b/src/test/java/com/mindee/product/fr/energybill/EnergyBillV1Test.java index b7ee102db..aa8f30ba0 100644 --- a/src/test/java/com/mindee/product/fr/energybill/EnergyBillV1Test.java +++ b/src/test/java/com/mindee/product/fr/energybill/EnergyBillV1Test.java @@ -1,17 +1,17 @@ package com.mindee.product.fr.energybill; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; import com.mindee.parsing.standard.ClassificationField; -import static com.mindee.TestingUtilities.assertStringEqualsFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit tests for EnergyBillV1. diff --git a/src/test/java/com/mindee/product/fr/healthcard/HealthCardV1Test.java b/src/test/java/com/mindee/product/fr/healthcard/HealthCardV1Test.java index 1171d1c41..8fec17e1c 100644 --- a/src/test/java/com/mindee/product/fr/healthcard/HealthCardV1Test.java +++ b/src/test/java/com/mindee/product/fr/healthcard/HealthCardV1Test.java @@ -1,17 +1,17 @@ package com.mindee.product.fr.healthcard; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; import com.mindee.parsing.standard.ClassificationField; -import static com.mindee.TestingUtilities.assertStringEqualsFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit tests for HealthCardV1. diff --git a/src/test/java/com/mindee/product/fr/idcard/IdCardV1Test.java b/src/test/java/com/mindee/product/fr/idcard/IdCardV1Test.java index 66bdd7493..6d7bfd1ac 100644 --- a/src/test/java/com/mindee/product/fr/idcard/IdCardV1Test.java +++ b/src/test/java/com/mindee/product/fr/idcard/IdCardV1Test.java @@ -1,18 +1,18 @@ package com.mindee.product.fr.idcard; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.Page; import com.mindee.parsing.common.PredictResponse; import com.mindee.parsing.standard.ClassificationField; -import static com.mindee.TestingUtilities.assertStringEqualsFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit tests for IdCardV1. diff --git a/src/test/java/com/mindee/product/fr/idcard/IdCardV2Test.java b/src/test/java/com/mindee/product/fr/idcard/IdCardV2Test.java index 473ed7eb2..787645565 100644 --- a/src/test/java/com/mindee/product/fr/idcard/IdCardV2Test.java +++ b/src/test/java/com/mindee/product/fr/idcard/IdCardV2Test.java @@ -1,18 +1,18 @@ package com.mindee.product.fr.idcard; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.Page; import com.mindee.parsing.common.PredictResponse; import com.mindee.parsing.standard.ClassificationField; -import static com.mindee.TestingUtilities.assertStringEqualsFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit tests for IdCardV2. diff --git a/src/test/java/com/mindee/product/fr/payslip/PayslipV2Test.java b/src/test/java/com/mindee/product/fr/payslip/PayslipV2Test.java index fe88d2608..783dac7cd 100644 --- a/src/test/java/com/mindee/product/fr/payslip/PayslipV2Test.java +++ b/src/test/java/com/mindee/product/fr/payslip/PayslipV2Test.java @@ -1,17 +1,17 @@ package com.mindee.product.fr.payslip; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; import com.mindee.parsing.standard.ClassificationField; -import static com.mindee.TestingUtilities.assertStringEqualsFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit tests for PayslipV2. diff --git a/src/test/java/com/mindee/product/fr/payslip/PayslipV3Test.java b/src/test/java/com/mindee/product/fr/payslip/PayslipV3Test.java index 8a4c973d8..a33eed9dd 100644 --- a/src/test/java/com/mindee/product/fr/payslip/PayslipV3Test.java +++ b/src/test/java/com/mindee/product/fr/payslip/PayslipV3Test.java @@ -1,17 +1,17 @@ package com.mindee.product.fr.payslip; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; import com.mindee.parsing.standard.ClassificationField; -import static com.mindee.TestingUtilities.assertStringEqualsFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit tests for PayslipV3. diff --git a/src/test/java/com/mindee/product/generated/GeneratedV1Test.java b/src/test/java/com/mindee/product/generated/GeneratedV1Test.java index da28e1f46..812583ab8 100644 --- a/src/test/java/com/mindee/product/generated/GeneratedV1Test.java +++ b/src/test/java/com/mindee/product/generated/GeneratedV1Test.java @@ -1,5 +1,7 @@ package com.mindee.product.generated; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.AsyncPredictResponse; @@ -11,15 +13,13 @@ import com.mindee.parsing.standard.ClassificationField; import com.mindee.parsing.standard.DateField; import com.mindee.parsing.standard.StringField; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; import java.time.LocalDate; import java.util.Map; import java.util.Objects; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class GeneratedV1Test { protected AsyncPredictResponse getAsyncPrediction(String name) throws IOException { diff --git a/src/test/java/com/mindee/product/ind/indianpassport/IndianPassportV1Test.java b/src/test/java/com/mindee/product/ind/indianpassport/IndianPassportV1Test.java index 6c11bd93e..63d180b8f 100644 --- a/src/test/java/com/mindee/product/ind/indianpassport/IndianPassportV1Test.java +++ b/src/test/java/com/mindee/product/ind/indianpassport/IndianPassportV1Test.java @@ -1,17 +1,17 @@ package com.mindee.product.ind.indianpassport; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; import com.mindee.parsing.standard.ClassificationField; -import static com.mindee.TestingUtilities.assertStringEqualsFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit tests for IndianPassportV1. diff --git a/src/test/java/com/mindee/product/internationalid/InternationalIdV2Test.java b/src/test/java/com/mindee/product/internationalid/InternationalIdV2Test.java index b6998950b..751de16da 100644 --- a/src/test/java/com/mindee/product/internationalid/InternationalIdV2Test.java +++ b/src/test/java/com/mindee/product/internationalid/InternationalIdV2Test.java @@ -1,17 +1,17 @@ package com.mindee.product.internationalid; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; import com.mindee.parsing.standard.ClassificationField; -import static com.mindee.TestingUtilities.assertStringEqualsFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit tests for InternationalIdV2. diff --git a/src/test/java/com/mindee/product/invoice/InvoiceV4Test.java b/src/test/java/com/mindee/product/invoice/InvoiceV4Test.java index 27b0482ca..9cd811d06 100644 --- a/src/test/java/com/mindee/product/invoice/InvoiceV4Test.java +++ b/src/test/java/com/mindee/product/invoice/InvoiceV4Test.java @@ -1,17 +1,17 @@ package com.mindee.product.invoice; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; import com.mindee.parsing.standard.ClassificationField; -import static com.mindee.TestingUtilities.assertStringEqualsFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit tests for InvoiceV4. diff --git a/src/test/java/com/mindee/product/invoicesplitter/InvoiceSplitterV1Test.java b/src/test/java/com/mindee/product/invoicesplitter/InvoiceSplitterV1Test.java index ec601e93b..4f730e590 100644 --- a/src/test/java/com/mindee/product/invoicesplitter/InvoiceSplitterV1Test.java +++ b/src/test/java/com/mindee/product/invoicesplitter/InvoiceSplitterV1Test.java @@ -1,17 +1,17 @@ package com.mindee.product.invoicesplitter; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; import com.mindee.parsing.standard.ClassificationField; -import static com.mindee.TestingUtilities.assertStringEqualsFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit tests for InvoiceSplitterV1. diff --git a/src/test/java/com/mindee/product/multireceiptsdetector/MultiReceiptsDetectorV1Test.java b/src/test/java/com/mindee/product/multireceiptsdetector/MultiReceiptsDetectorV1Test.java index 8dd6174fa..d7e06a59b 100644 --- a/src/test/java/com/mindee/product/multireceiptsdetector/MultiReceiptsDetectorV1Test.java +++ b/src/test/java/com/mindee/product/multireceiptsdetector/MultiReceiptsDetectorV1Test.java @@ -1,17 +1,17 @@ package com.mindee.product.multireceiptsdetector; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; import com.mindee.parsing.standard.ClassificationField; -import static com.mindee.TestingUtilities.assertStringEqualsFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit tests for MultiReceiptsDetectorV1. diff --git a/src/test/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Test.java b/src/test/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Test.java index fca4db33c..0d8bd9b3d 100644 --- a/src/test/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Test.java +++ b/src/test/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Test.java @@ -1,17 +1,17 @@ package com.mindee.product.nutritionfactslabel; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; import com.mindee.parsing.standard.ClassificationField; -import static com.mindee.TestingUtilities.assertStringEqualsFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit tests for NutritionFactsLabelV1. diff --git a/src/test/java/com/mindee/product/passport/PassportV1Test.java b/src/test/java/com/mindee/product/passport/PassportV1Test.java index d2f0befc5..39f6e289d 100644 --- a/src/test/java/com/mindee/product/passport/PassportV1Test.java +++ b/src/test/java/com/mindee/product/passport/PassportV1Test.java @@ -1,17 +1,17 @@ package com.mindee.product.passport; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; import com.mindee.parsing.standard.ClassificationField; -import static com.mindee.TestingUtilities.assertStringEqualsFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit tests for PassportV1. diff --git a/src/test/java/com/mindee/product/receipt/ReceiptV5Test.java b/src/test/java/com/mindee/product/receipt/ReceiptV5Test.java index ba8ba24e6..2869317ca 100644 --- a/src/test/java/com/mindee/product/receipt/ReceiptV5Test.java +++ b/src/test/java/com/mindee/product/receipt/ReceiptV5Test.java @@ -1,17 +1,17 @@ package com.mindee.product.receipt; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; import com.mindee.parsing.standard.ClassificationField; -import static com.mindee.TestingUtilities.assertStringEqualsFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit tests for ReceiptV5. diff --git a/src/test/java/com/mindee/product/resume/ResumeV1Test.java b/src/test/java/com/mindee/product/resume/ResumeV1Test.java index 9df0abf02..9dac190ea 100644 --- a/src/test/java/com/mindee/product/resume/ResumeV1Test.java +++ b/src/test/java/com/mindee/product/resume/ResumeV1Test.java @@ -1,17 +1,17 @@ package com.mindee.product.resume; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; import com.mindee.parsing.standard.ClassificationField; -import static com.mindee.TestingUtilities.assertStringEqualsFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit tests for ResumeV1. diff --git a/src/test/java/com/mindee/product/us/bankcheck/BankCheckV1Test.java b/src/test/java/com/mindee/product/us/bankcheck/BankCheckV1Test.java index 8a39a8296..32f0605f9 100644 --- a/src/test/java/com/mindee/product/us/bankcheck/BankCheckV1Test.java +++ b/src/test/java/com/mindee/product/us/bankcheck/BankCheckV1Test.java @@ -1,18 +1,18 @@ package com.mindee.product.us.bankcheck; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.Page; import com.mindee.parsing.common.PredictResponse; import com.mindee.parsing.standard.ClassificationField; -import static com.mindee.TestingUtilities.assertStringEqualsFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit tests for BankCheckV1. diff --git a/src/test/java/com/mindee/product/us/healthcarecard/HealthcareCardV1Test.java b/src/test/java/com/mindee/product/us/healthcarecard/HealthcareCardV1Test.java index 3c15f9097..8bb81a957 100644 --- a/src/test/java/com/mindee/product/us/healthcarecard/HealthcareCardV1Test.java +++ b/src/test/java/com/mindee/product/us/healthcarecard/HealthcareCardV1Test.java @@ -1,17 +1,17 @@ package com.mindee.product.us.healthcarecard; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; import com.mindee.parsing.standard.ClassificationField; -import static com.mindee.TestingUtilities.assertStringEqualsFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit tests for HealthcareCardV1. diff --git a/src/test/java/com/mindee/product/us/usmail/UsMailV3Test.java b/src/test/java/com/mindee/product/us/usmail/UsMailV3Test.java index 67e772dc4..61b112263 100644 --- a/src/test/java/com/mindee/product/us/usmail/UsMailV3Test.java +++ b/src/test/java/com/mindee/product/us/usmail/UsMailV3Test.java @@ -1,17 +1,17 @@ package com.mindee.product.us.usmail; +import static com.mindee.TestingUtilities.assertStringEqualsFile; +import static com.mindee.TestingUtilities.getV1ResourcePathString; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; import com.mindee.parsing.standard.ClassificationField; -import static com.mindee.TestingUtilities.assertStringEqualsFile; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; - -import static com.mindee.TestingUtilities.getV1ResourcePathString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit tests for UsMailV3. diff --git a/src/test/java/com/mindee/workflow/WorkflowIT.java b/src/test/java/com/mindee/workflow/WorkflowIT.java index 6190f9a01..aa36488a7 100644 --- a/src/test/java/com/mindee/workflow/WorkflowIT.java +++ b/src/test/java/com/mindee/workflow/WorkflowIT.java @@ -1,5 +1,7 @@ package com.mindee.workflow; +import static com.mindee.TestingUtilities.getV1ResourcePath; + import com.mindee.MindeeClient; import com.mindee.PredictOptions; import com.mindee.WorkflowOptions; @@ -17,8 +19,6 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import static com.mindee.TestingUtilities.getV1ResourcePath; - public class WorkflowIT { private static MindeeClient client; private static LocalInputSource financialDocumentInputSource; From b8ad08e32ee73a5e068d1e0237bea7457b10ece9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ianar=C3=A9=20S=C3=A9vi?= Date: Fri, 19 Dec 2025 11:30:58 +0100 Subject: [PATCH 3/4] removeUnusedImports --- .github/workflows/_static-analysis.yml | 2 +- pom.xml | 32 ++++--------------- .../com/mindee/extraction/ExtractedPDF.java | 1 - src/main/java/com/mindee/geometry/Bbox.java | 1 - .../com/mindee/input/InputSourceUtils.java | 1 - .../mindee/parsing/common/ApiResponse.java | 1 - .../parsing/common/ExecutionPriority.java | 1 - .../v2/field/DynamicFieldDeserializer.java | 2 -- .../common/AsyncPredictResponseTest.java | 1 - .../com/mindee/parsing/common/ErrorTest.java | 1 - .../com/mindee/parsing/common/OcrTest.java | 2 -- .../businesscard/BusinessCardV1Test.java | 1 - .../mindee/product/cropper/CropperV1Test.java | 1 - .../deliverynote/DeliveryNoteV1Test.java | 1 - .../driverlicense/DriverLicenseV1Test.java | 1 - .../FinancialDocumentV1Test.java | 1 - .../BankAccountDetailsV1Test.java | 1 - .../BankAccountDetailsV2Test.java | 1 - .../fr/cartegrise/CarteGriseV1Test.java | 1 - .../fr/energybill/EnergyBillV1Test.java | 1 - .../fr/healthcard/HealthCardV1Test.java | 1 - .../product/fr/payslip/PayslipV2Test.java | 1 - .../product/fr/payslip/PayslipV3Test.java | 1 - .../InvoiceSplitterV1Test.java | 1 - .../MultiReceiptsDetectorV1Test.java | 1 - .../NutritionFactsLabelV1Test.java | 1 - .../product/passport/PassportV1Test.java | 1 - .../product/us/bankcheck/BankCheckV1Test.java | 1 - .../healthcarecard/HealthcareCardV1Test.java | 1 - .../product/us/usmail/UsMailV3Test.java | 1 - .../com/mindee/workflow/WorkflowTest.java | 2 -- 31 files changed, 7 insertions(+), 59 deletions(-) diff --git a/.github/workflows/_static-analysis.yml b/.github/workflows/_static-analysis.yml index 5c89e2b90..30acf6ee7 100644 --- a/.github/workflows/_static-analysis.yml +++ b/.github/workflows/_static-analysis.yml @@ -20,4 +20,4 @@ jobs: cache: "maven" - name: Check Code Style - run: mvn --update-snapshots --no-transfer-progress process-sources + run: mvn --update-snapshots --no-transfer-progress checkstyle:check spotless:check diff --git a/pom.xml b/pom.xml index 5bdb5993f..aa6087618 100644 --- a/pom.xml +++ b/pom.xml @@ -102,7 +102,8 @@ com.puppycrawl.tools checkstyle - 10.12.7 + + 10.14.2 @@ -111,32 +112,19 @@ true error - - - process-sources - - check - - - com.diffplug.spotless spotless-maven-plugin - 2.30.0 + + 2.46.1 + + - - - validate - - check - - - @@ -150,14 +138,6 @@ 8 - - com.diffplug.spotless - spotless-maven-plugin - - - org.apache.maven.plugins - maven-checkstyle-plugin - org.sonatype.central central-publishing-maven-plugin diff --git a/src/main/java/com/mindee/extraction/ExtractedPDF.java b/src/main/java/com/mindee/extraction/ExtractedPDF.java index eef26c013..fdc859aec 100644 --- a/src/main/java/com/mindee/extraction/ExtractedPDF.java +++ b/src/main/java/com/mindee/extraction/ExtractedPDF.java @@ -1,6 +1,5 @@ package com.mindee.extraction; -import com.mindee.MindeeException; import com.mindee.input.LocalInputSource; import java.io.ByteArrayOutputStream; import java.io.File; diff --git a/src/main/java/com/mindee/geometry/Bbox.java b/src/main/java/com/mindee/geometry/Bbox.java index 891a3565e..8a9e50812 100644 --- a/src/main/java/com/mindee/geometry/Bbox.java +++ b/src/main/java/com/mindee/geometry/Bbox.java @@ -1,6 +1,5 @@ package com.mindee.geometry; -import java.util.ArrayList; import java.util.Arrays; import java.util.List; import lombok.Getter; diff --git a/src/main/java/com/mindee/input/InputSourceUtils.java b/src/main/java/com/mindee/input/InputSourceUtils.java index 24a26e594..f21b861df 100644 --- a/src/main/java/com/mindee/input/InputSourceUtils.java +++ b/src/main/java/com/mindee/input/InputSourceUtils.java @@ -4,7 +4,6 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.URL; -import javax.imageio.ImageIO; import org.apache.pdfbox.Loader; import org.apache.pdfbox.io.RandomAccessReadBuffer; import org.apache.pdfbox.pdmodel.PDDocument; diff --git a/src/main/java/com/mindee/parsing/common/ApiResponse.java b/src/main/java/com/mindee/parsing/common/ApiResponse.java index fa887b3b4..860073259 100644 --- a/src/main/java/com/mindee/parsing/common/ApiResponse.java +++ b/src/main/java/com/mindee/parsing/common/ApiResponse.java @@ -4,7 +4,6 @@ import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import lombok.EqualsAndHashCode; -import lombok.Getter; /** * Base class for all responses from the Mindee API. diff --git a/src/main/java/com/mindee/parsing/common/ExecutionPriority.java b/src/main/java/com/mindee/parsing/common/ExecutionPriority.java index 0cde417cc..845300cdf 100644 --- a/src/main/java/com/mindee/parsing/common/ExecutionPriority.java +++ b/src/main/java/com/mindee/parsing/common/ExecutionPriority.java @@ -1,6 +1,5 @@ package com.mindee.parsing.common; -import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; /** diff --git a/src/main/java/com/mindee/parsing/v2/field/DynamicFieldDeserializer.java b/src/main/java/com/mindee/parsing/v2/field/DynamicFieldDeserializer.java index c2a0a831b..9601c1af5 100644 --- a/src/main/java/com/mindee/parsing/v2/field/DynamicFieldDeserializer.java +++ b/src/main/java/com/mindee/parsing/v2/field/DynamicFieldDeserializer.java @@ -6,8 +6,6 @@ import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** * Custom deserializer for {@link DynamicField}. diff --git a/src/test/java/com/mindee/parsing/common/AsyncPredictResponseTest.java b/src/test/java/com/mindee/parsing/common/AsyncPredictResponseTest.java index c583dc71b..6a899e1ac 100644 --- a/src/test/java/com/mindee/parsing/common/AsyncPredictResponseTest.java +++ b/src/test/java/com/mindee/parsing/common/AsyncPredictResponseTest.java @@ -6,7 +6,6 @@ import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.product.invoicesplitter.InvoiceSplitterV1; -import java.io.File; import java.io.IOException; import java.nio.file.Path; import org.junit.jupiter.api.Assertions; diff --git a/src/test/java/com/mindee/parsing/common/ErrorTest.java b/src/test/java/com/mindee/parsing/common/ErrorTest.java index cdef158af..c0d206f3b 100644 --- a/src/test/java/com/mindee/parsing/common/ErrorTest.java +++ b/src/test/java/com/mindee/parsing/common/ErrorTest.java @@ -3,7 +3,6 @@ import static com.mindee.TestingUtilities.getV1ResourcePath; import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.File; import java.io.IOException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/mindee/parsing/common/OcrTest.java b/src/test/java/com/mindee/parsing/common/OcrTest.java index 3fea8976d..bd2298a86 100644 --- a/src/test/java/com/mindee/parsing/common/OcrTest.java +++ b/src/test/java/com/mindee/parsing/common/OcrTest.java @@ -7,10 +7,8 @@ import com.mindee.parsing.common.ocr.Ocr; import com.mindee.parsing.common.ocr.Word; import com.mindee.product.receipt.ReceiptV5; -import java.io.File; import java.io.IOException; import java.nio.file.Files; -import java.nio.file.Paths; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/mindee/product/businesscard/BusinessCardV1Test.java b/src/test/java/com/mindee/product/businesscard/BusinessCardV1Test.java index 7b387eaff..6ac2b8bf2 100644 --- a/src/test/java/com/mindee/product/businesscard/BusinessCardV1Test.java +++ b/src/test/java/com/mindee/product/businesscard/BusinessCardV1Test.java @@ -7,7 +7,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; -import com.mindee.parsing.standard.ClassificationField; import java.io.File; import java.io.IOException; import org.junit.jupiter.api.Assertions; diff --git a/src/test/java/com/mindee/product/cropper/CropperV1Test.java b/src/test/java/com/mindee/product/cropper/CropperV1Test.java index e4ab47f11..cae31c929 100644 --- a/src/test/java/com/mindee/product/cropper/CropperV1Test.java +++ b/src/test/java/com/mindee/product/cropper/CropperV1Test.java @@ -8,7 +8,6 @@ import com.mindee.parsing.common.Document; import com.mindee.parsing.common.Page; import com.mindee.parsing.common.PredictResponse; -import com.mindee.parsing.standard.ClassificationField; import java.io.File; import java.io.IOException; import org.junit.jupiter.api.Assertions; diff --git a/src/test/java/com/mindee/product/deliverynote/DeliveryNoteV1Test.java b/src/test/java/com/mindee/product/deliverynote/DeliveryNoteV1Test.java index 028a463ac..c2a4a2c0d 100644 --- a/src/test/java/com/mindee/product/deliverynote/DeliveryNoteV1Test.java +++ b/src/test/java/com/mindee/product/deliverynote/DeliveryNoteV1Test.java @@ -7,7 +7,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; -import com.mindee.parsing.standard.ClassificationField; import java.io.File; import java.io.IOException; import org.junit.jupiter.api.Assertions; diff --git a/src/test/java/com/mindee/product/driverlicense/DriverLicenseV1Test.java b/src/test/java/com/mindee/product/driverlicense/DriverLicenseV1Test.java index 2eea61d84..27a00c36e 100644 --- a/src/test/java/com/mindee/product/driverlicense/DriverLicenseV1Test.java +++ b/src/test/java/com/mindee/product/driverlicense/DriverLicenseV1Test.java @@ -7,7 +7,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; -import com.mindee.parsing.standard.ClassificationField; import java.io.File; import java.io.IOException; import org.junit.jupiter.api.Assertions; diff --git a/src/test/java/com/mindee/product/financialdocument/FinancialDocumentV1Test.java b/src/test/java/com/mindee/product/financialdocument/FinancialDocumentV1Test.java index 9d67960d4..8cf754a66 100644 --- a/src/test/java/com/mindee/product/financialdocument/FinancialDocumentV1Test.java +++ b/src/test/java/com/mindee/product/financialdocument/FinancialDocumentV1Test.java @@ -10,7 +10,6 @@ import java.io.File; import java.io.IOException; import java.nio.file.Files; -import java.nio.file.Paths; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV1Test.java b/src/test/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV1Test.java index 129600cf1..27259de9f 100644 --- a/src/test/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV1Test.java +++ b/src/test/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV1Test.java @@ -7,7 +7,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; -import com.mindee.parsing.standard.ClassificationField; import java.io.File; import java.io.IOException; import org.junit.jupiter.api.Assertions; diff --git a/src/test/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV2Test.java b/src/test/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV2Test.java index 543762216..8ae2bb096 100644 --- a/src/test/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV2Test.java +++ b/src/test/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV2Test.java @@ -7,7 +7,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; -import com.mindee.parsing.standard.ClassificationField; import java.io.File; import java.io.IOException; import org.junit.jupiter.api.Assertions; diff --git a/src/test/java/com/mindee/product/fr/cartegrise/CarteGriseV1Test.java b/src/test/java/com/mindee/product/fr/cartegrise/CarteGriseV1Test.java index 4426162c5..b22a9c540 100644 --- a/src/test/java/com/mindee/product/fr/cartegrise/CarteGriseV1Test.java +++ b/src/test/java/com/mindee/product/fr/cartegrise/CarteGriseV1Test.java @@ -7,7 +7,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; -import com.mindee.parsing.standard.ClassificationField; import java.io.File; import java.io.IOException; import org.junit.jupiter.api.Assertions; diff --git a/src/test/java/com/mindee/product/fr/energybill/EnergyBillV1Test.java b/src/test/java/com/mindee/product/fr/energybill/EnergyBillV1Test.java index aa8f30ba0..e227ff368 100644 --- a/src/test/java/com/mindee/product/fr/energybill/EnergyBillV1Test.java +++ b/src/test/java/com/mindee/product/fr/energybill/EnergyBillV1Test.java @@ -7,7 +7,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; -import com.mindee.parsing.standard.ClassificationField; import java.io.File; import java.io.IOException; import org.junit.jupiter.api.Assertions; diff --git a/src/test/java/com/mindee/product/fr/healthcard/HealthCardV1Test.java b/src/test/java/com/mindee/product/fr/healthcard/HealthCardV1Test.java index 8fec17e1c..7522ae35a 100644 --- a/src/test/java/com/mindee/product/fr/healthcard/HealthCardV1Test.java +++ b/src/test/java/com/mindee/product/fr/healthcard/HealthCardV1Test.java @@ -7,7 +7,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; -import com.mindee.parsing.standard.ClassificationField; import java.io.File; import java.io.IOException; import org.junit.jupiter.api.Assertions; diff --git a/src/test/java/com/mindee/product/fr/payslip/PayslipV2Test.java b/src/test/java/com/mindee/product/fr/payslip/PayslipV2Test.java index 783dac7cd..ca315b66d 100644 --- a/src/test/java/com/mindee/product/fr/payslip/PayslipV2Test.java +++ b/src/test/java/com/mindee/product/fr/payslip/PayslipV2Test.java @@ -7,7 +7,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; -import com.mindee.parsing.standard.ClassificationField; import java.io.File; import java.io.IOException; import org.junit.jupiter.api.Assertions; diff --git a/src/test/java/com/mindee/product/fr/payslip/PayslipV3Test.java b/src/test/java/com/mindee/product/fr/payslip/PayslipV3Test.java index a33eed9dd..75be04f97 100644 --- a/src/test/java/com/mindee/product/fr/payslip/PayslipV3Test.java +++ b/src/test/java/com/mindee/product/fr/payslip/PayslipV3Test.java @@ -7,7 +7,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; -import com.mindee.parsing.standard.ClassificationField; import java.io.File; import java.io.IOException; import org.junit.jupiter.api.Assertions; diff --git a/src/test/java/com/mindee/product/invoicesplitter/InvoiceSplitterV1Test.java b/src/test/java/com/mindee/product/invoicesplitter/InvoiceSplitterV1Test.java index 4f730e590..efe8845fd 100644 --- a/src/test/java/com/mindee/product/invoicesplitter/InvoiceSplitterV1Test.java +++ b/src/test/java/com/mindee/product/invoicesplitter/InvoiceSplitterV1Test.java @@ -7,7 +7,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; -import com.mindee.parsing.standard.ClassificationField; import java.io.File; import java.io.IOException; import org.junit.jupiter.api.Assertions; diff --git a/src/test/java/com/mindee/product/multireceiptsdetector/MultiReceiptsDetectorV1Test.java b/src/test/java/com/mindee/product/multireceiptsdetector/MultiReceiptsDetectorV1Test.java index d7e06a59b..69683e37c 100644 --- a/src/test/java/com/mindee/product/multireceiptsdetector/MultiReceiptsDetectorV1Test.java +++ b/src/test/java/com/mindee/product/multireceiptsdetector/MultiReceiptsDetectorV1Test.java @@ -7,7 +7,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; -import com.mindee.parsing.standard.ClassificationField; import java.io.File; import java.io.IOException; import org.junit.jupiter.api.Assertions; diff --git a/src/test/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Test.java b/src/test/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Test.java index 0d8bd9b3d..ffdd6e524 100644 --- a/src/test/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Test.java +++ b/src/test/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Test.java @@ -7,7 +7,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; -import com.mindee.parsing.standard.ClassificationField; import java.io.File; import java.io.IOException; import org.junit.jupiter.api.Assertions; diff --git a/src/test/java/com/mindee/product/passport/PassportV1Test.java b/src/test/java/com/mindee/product/passport/PassportV1Test.java index 39f6e289d..c641260e5 100644 --- a/src/test/java/com/mindee/product/passport/PassportV1Test.java +++ b/src/test/java/com/mindee/product/passport/PassportV1Test.java @@ -7,7 +7,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; -import com.mindee.parsing.standard.ClassificationField; import java.io.File; import java.io.IOException; import org.junit.jupiter.api.Assertions; diff --git a/src/test/java/com/mindee/product/us/bankcheck/BankCheckV1Test.java b/src/test/java/com/mindee/product/us/bankcheck/BankCheckV1Test.java index 32f0605f9..93886cfbf 100644 --- a/src/test/java/com/mindee/product/us/bankcheck/BankCheckV1Test.java +++ b/src/test/java/com/mindee/product/us/bankcheck/BankCheckV1Test.java @@ -8,7 +8,6 @@ import com.mindee.parsing.common.Document; import com.mindee.parsing.common.Page; import com.mindee.parsing.common.PredictResponse; -import com.mindee.parsing.standard.ClassificationField; import java.io.File; import java.io.IOException; import org.junit.jupiter.api.Assertions; diff --git a/src/test/java/com/mindee/product/us/healthcarecard/HealthcareCardV1Test.java b/src/test/java/com/mindee/product/us/healthcarecard/HealthcareCardV1Test.java index 8bb81a957..307d7e115 100644 --- a/src/test/java/com/mindee/product/us/healthcarecard/HealthcareCardV1Test.java +++ b/src/test/java/com/mindee/product/us/healthcarecard/HealthcareCardV1Test.java @@ -7,7 +7,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; -import com.mindee.parsing.standard.ClassificationField; import java.io.File; import java.io.IOException; import org.junit.jupiter.api.Assertions; diff --git a/src/test/java/com/mindee/product/us/usmail/UsMailV3Test.java b/src/test/java/com/mindee/product/us/usmail/UsMailV3Test.java index 61b112263..877bb100c 100644 --- a/src/test/java/com/mindee/product/us/usmail/UsMailV3Test.java +++ b/src/test/java/com/mindee/product/us/usmail/UsMailV3Test.java @@ -7,7 +7,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.mindee.parsing.common.Document; import com.mindee.parsing.common.PredictResponse; -import com.mindee.parsing.standard.ClassificationField; import java.io.File; import java.io.IOException; import org.junit.jupiter.api.Assertions; diff --git a/src/test/java/com/mindee/workflow/WorkflowTest.java b/src/test/java/com/mindee/workflow/WorkflowTest.java index 24fdb039f..8719c8048 100644 --- a/src/test/java/com/mindee/workflow/WorkflowTest.java +++ b/src/test/java/com/mindee/workflow/WorkflowTest.java @@ -2,7 +2,6 @@ import static com.mindee.TestingUtilities.getResourcePath; import static com.mindee.TestingUtilities.getV1ResourcePath; -import static com.mindee.TestingUtilities.getV1ResourcePathString; import static org.mockito.Mockito.when; import com.fasterxml.jackson.databind.ObjectMapper; @@ -13,7 +12,6 @@ import com.mindee.parsing.common.WorkflowResponse; import com.mindee.pdf.PdfOperation; import com.mindee.product.generated.GeneratedV1; -import java.io.File; import java.io.IOException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; From 53675ccb2da4dc1aa014ee9e88ec6f212e493cbd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ianar=C3=A9=20S=C3=A9vi?= Date: Fri, 19 Dec 2025 13:26:26 +0100 Subject: [PATCH 4/4] eclipse test --- .github/workflows/_static-analysis.yml | 2 +- .gitignore | 2 + checkstyle.xml | 392 --------- eclipse-formatter.xml | 405 +++++++++ pom.xml | 22 +- .../java/com/mindee/AsyncPollingOptions.java | 6 +- .../java/com/mindee/CommandLineInterface.java | 171 ++-- .../java/com/mindee/InferenceParameters.java | 28 +- src/main/java/com/mindee/MindeeClient.java | 525 +++++------ src/main/java/com/mindee/MindeeClientV2.java | 12 +- .../cli/CommandLineInterfaceProducts.java | 201 +++-- .../java/com/mindee/cli/ProductProcessor.java | 14 +- .../com/mindee/extraction/ExtractedImage.java | 4 + .../com/mindee/extraction/ImageExtractor.java | 31 +- .../com/mindee/extraction/PDFExtractor.java | 45 +- src/main/java/com/mindee/geometry/Bbox.java | 5 +- .../java/com/mindee/geometry/BboxUtils.java | 28 +- .../com/mindee/geometry/BoundingBoxUtils.java | 30 +- src/main/java/com/mindee/geometry/MinMax.java | 1 + .../mindee/geometry/PolygonDeserializer.java | 4 +- .../com/mindee/geometry/PolygonUtils.java | 152 ++-- .../com/mindee/http/CustomEndpointInfo.java | 1 - src/main/java/com/mindee/http/Endpoint.java | 12 +- .../java/com/mindee/http/EndpointInfo.java | 1 - .../java/com/mindee/http/MindeeApiCommon.java | 4 +- .../java/com/mindee/http/MindeeApiV2.java | 18 +- .../java/com/mindee/http/MindeeHttpApi.java | 211 ++--- .../java/com/mindee/http/MindeeHttpApiV2.java | 151 ++-- .../mindee/http/MindeeHttpExceptionV2.java | 2 +- .../com/mindee/http/RequestParameters.java | 2 +- .../com/mindee/image/ImageCompressor.java | 28 +- .../java/com/mindee/image/ImageUtils.java | 10 +- .../com/mindee/input/InputSourceUtils.java | 10 +- .../com/mindee/input/LocalInputSource.java | 16 +- .../java/com/mindee/input/LocalResponse.java | 27 +- .../java/com/mindee/input/PageOptions.java | 8 +- .../java/com/mindee/input/URLInputSource.java | 21 +- .../com/mindee/parsing/SummaryHelper.java | 21 +- .../com/mindee/parsing/common/ApiRequest.java | 14 +- .../parsing/common/AsyncPredictResponse.java | 2 +- .../com/mindee/parsing/common/Document.java | 3 +- .../com/mindee/parsing/common/Execution.java | 51 +- .../mindee/parsing/common/ExecutionFile.java | 1 - .../com/mindee/parsing/common/Inference.java | 40 +- .../java/com/mindee/parsing/common/Job.java | 2 +- .../common/LocalDateTimeDeserializer.java | 26 +- .../java/com/mindee/parsing/common/Page.java | 7 +- .../java/com/mindee/parsing/common/Pages.java | 6 +- .../parsing/common/PredictResponse.java | 2 +- .../com/mindee/parsing/common/Prediction.java | 3 +- .../parsing/common/WorkflowResponse.java | 3 +- .../mindee/parsing/common/ocr/MvisionV1.java | 4 +- .../mindee/parsing/common/ocr/OcrPage.java | 28 +- ...ustomV1DocumentPredictionDeserializer.java | 8 +- .../com/mindee/parsing/custom/ListField.java | 16 +- .../mindee/parsing/custom/ListFieldValue.java | 7 +- .../mindee/parsing/custom/lineitems/Line.java | 26 +- .../custom/lineitems/LineGenerator.java | 27 +- .../parsing/custom/lineitems/LineItems.java | 2 +- .../custom/lineitems/LineItemsGenerator.java | 35 +- .../parsing/generated/GeneratedFeature.java | 22 +- .../parsing/generated/GeneratedObject.java | 36 +- .../GeneratedV1PredictionDeserializer.java | 12 +- .../mindee/parsing/standard/AddressField.java | 50 +- .../mindee/parsing/standard/AmountField.java | 13 +- .../mindee/parsing/standard/BaseField.java | 10 +- .../mindee/parsing/standard/BooleanField.java | 14 +- .../standard/CompanyRegistrationField.java | 11 +- .../mindee/parsing/standard/DateField.java | 16 +- .../mindee/parsing/standard/LocaleField.java | 23 +- .../parsing/standard/PaymentDetailsField.java | 22 +- .../mindee/parsing/standard/PositionData.java | 1 + .../mindee/parsing/standard/StringField.java | 22 +- .../com/mindee/parsing/standard/TaxField.java | 20 +- .../com/mindee/parsing/standard/Taxes.java | 2 +- .../parsing/standard/TaxesDeserializer.java | 5 +- .../parsing/v2/DataSchemaActiveOptions.java | 8 +- .../java/com/mindee/parsing/v2/Inference.java | 18 +- .../parsing/v2/InferenceActiveOptions.java | 26 +- .../com/mindee/parsing/v2/InferenceFile.java | 13 +- .../com/mindee/parsing/v2/InferenceModel.java | 6 +- .../mindee/parsing/v2/InferenceResult.java | 3 +- .../com/mindee/parsing/v2/JobResponse.java | 1 - .../mindee/parsing/v2/field/DynamicField.java | 22 +- .../parsing/v2/field/FieldConfidence.java | 10 +- .../parsing/v2/field/InferenceFields.java | 5 +- .../mindee/parsing/v2/field/ListField.java | 6 +- .../mindee/parsing/v2/field/ObjectField.java | 2 +- .../mindee/parsing/v2/field/SimpleField.java | 3 +- .../v2/field/SimpleFieldDeserializer.java | 4 +- src/main/java/com/mindee/pdf/PDFUtils.java | 48 +- src/main/java/com/mindee/pdf/PdfBoxApi.java | 20 +- .../java/com/mindee/pdf/PdfCompressor.java | 44 +- .../java/com/mindee/pdf/PdfPageImage.java | 10 +- .../barcodereader/BarcodeReaderV1.java | 3 +- .../BarcodeReaderV1Document.java | 24 +- .../product/billoflading/BillOfLadingV1.java | 3 +- .../billoflading/BillOfLadingV1Carrier.java | 15 +- .../BillOfLadingV1CarrierItem.java | 44 +- .../billoflading/BillOfLadingV1Consignee.java | 18 +- .../billoflading/BillOfLadingV1Document.java | 76 +- .../BillOfLadingV1NotifyParty.java | 18 +- .../billoflading/BillOfLadingV1Shipper.java | 18 +- .../product/businesscard/BusinessCardV1.java | 3 +- .../businesscard/BusinessCardV1Document.java | 55 +- .../com/mindee/product/cropper/CropperV1.java | 3 +- .../product/cropper/CropperV1Document.java | 1 - .../mindee/product/cropper/CropperV1Page.java | 13 +- .../product/custom/CustomV1Document.java | 1 - .../mindee/product/custom/CustomV1Page.java | 1 - .../product/deliverynote/DeliveryNoteV1.java | 3 +- .../deliverynote/DeliveryNoteV1Document.java | 34 +- .../driverlicense/DriverLicenseV1.java | 3 +- .../DriverLicenseV1Document.java | 58 +- .../FinancialDocumentV1Document.java | 194 ++--- .../FinancialDocumentV1LineItem.java | 68 +- .../BankAccountDetailsV1Document.java | 18 +- .../BankAccountDetailsV2Bban.java | 16 +- .../BankAccountDetailsV2Document.java | 22 +- .../product/fr/cartegrise/CarteGriseV1.java | 3 +- .../fr/cartegrise/CarteGriseV1Document.java | 170 +--- .../product/fr/energybill/EnergyBillV1.java | 3 +- .../fr/energybill/EnergyBillV1Document.java | 145 ++-- .../EnergyBillV1EnergyConsumer.java | 7 +- .../EnergyBillV1EnergySupplier.java | 7 +- .../energybill/EnergyBillV1EnergyUsage.java | 58 +- .../energybill/EnergyBillV1MeterDetail.java | 12 +- .../energybill/EnergyBillV1Subscription.java | 44 +- .../EnergyBillV1TaxesAndContribution.java | 44 +- .../product/fr/healthcard/HealthCardV1.java | 3 +- .../fr/healthcard/HealthCardV1Document.java | 27 +- .../mindee/product/fr/idcard/IdCardV1.java | 3 +- .../product/fr/idcard/IdCardV1Document.java | 51 +- .../product/fr/idcard/IdCardV1Page.java | 8 +- .../mindee/product/fr/idcard/IdCardV2.java | 3 +- .../product/fr/idcard/IdCardV2Document.java | 71 +- .../product/fr/idcard/IdCardV2Page.java | 13 +- .../mindee/product/fr/payslip/PayslipV2.java | 3 +- .../payslip/PayslipV2BankAccountDetail.java | 12 +- .../product/fr/payslip/PayslipV2Document.java | 61 +- .../product/fr/payslip/PayslipV2Employee.java | 34 +- .../product/fr/payslip/PayslipV2Employer.java | 28 +- .../fr/payslip/PayslipV2Employment.java | 32 +- .../fr/payslip/PayslipV2PayDetail.java | 92 +- .../fr/payslip/PayslipV2PayPeriod.java | 20 +- .../product/fr/payslip/PayslipV2Pto.java | 25 +- .../fr/payslip/PayslipV2SalaryDetail.java | 40 +- .../mindee/product/fr/payslip/PayslipV3.java | 3 +- .../payslip/PayslipV3BankAccountDetail.java | 12 +- .../product/fr/payslip/PayslipV3Document.java | 84 +- .../product/fr/payslip/PayslipV3Employee.java | 34 +- .../product/fr/payslip/PayslipV3Employer.java | 28 +- .../fr/payslip/PayslipV3Employment.java | 31 +- .../fr/payslip/PayslipV3PaidTimeOff.java | 42 +- .../fr/payslip/PayslipV3PayDetail.java | 92 +- .../fr/payslip/PayslipV3PayPeriod.java | 20 +- .../fr/payslip/PayslipV3SalaryDetail.java | 52 +- .../IndianPassportV1Document.java | 100 +-- .../InternationalIdV2Document.java | 84 +- .../com/mindee/product/invoice/InvoiceV4.java | 3 +- .../product/invoice/InvoiceV4Document.java | 175 ++-- .../product/invoice/InvoiceV4LineItem.java | 68 +- .../InvoiceSplitterV1Document.java | 24 +- .../InvoiceSplitterV1InvoicePageGroup.java | 22 +- .../MultiReceiptsDetectorV1Document.java | 13 +- .../NutritionFactsLabelV1AddedSugar.java | 25 +- .../NutritionFactsLabelV1Calorie.java | 25 +- .../NutritionFactsLabelV1Cholesterol.java | 25 +- .../NutritionFactsLabelV1DietaryFiber.java | 25 +- .../NutritionFactsLabelV1Document.java | 84 +- .../NutritionFactsLabelV1Nutrient.java | 42 +- .../NutritionFactsLabelV1Protein.java | 25 +- .../NutritionFactsLabelV1SaturatedFat.java | 25 +- .../NutritionFactsLabelV1ServingSize.java | 12 +- .../NutritionFactsLabelV1Sodium.java | 31 +- ...utritionFactsLabelV1TotalCarbohydrate.java | 25 +- .../NutritionFactsLabelV1TotalFat.java | 25 +- .../NutritionFactsLabelV1TotalSugar.java | 25 +- .../NutritionFactsLabelV1TransFat.java | 25 +- .../mindee/product/passport/PassportV1.java | 3 +- .../product/passport/PassportV1Document.java | 55 +- .../com/mindee/product/receipt/ReceiptV5.java | 3 +- .../product/receipt/ReceiptV5Document.java | 100 +-- .../product/receipt/ReceiptV5LineItem.java | 40 +- .../com/mindee/product/resume/ResumeV1.java | 3 +- .../product/resume/ResumeV1Certificate.java | 10 +- .../product/resume/ResumeV1Document.java | 207 ++--- .../product/resume/ResumeV1Education.java | 16 +- .../product/resume/ResumeV1Language.java | 5 +- .../ResumeV1ProfessionalExperience.java | 20 +- .../resume/ResumeV1SocialNetworksUrl.java | 5 +- .../product/us/bankcheck/BankCheckV1.java | 3 +- .../us/bankcheck/BankCheckV1Document.java | 35 +- .../product/us/bankcheck/BankCheckV1Page.java | 20 +- .../healthcarecard/HealthcareCardV1Copay.java | 15 +- .../HealthcareCardV1Document.java | 78 +- .../mindee/product/us/usmail/UsMailV3.java | 3 +- .../product/us/usmail/UsMailV3Document.java | 62 +- .../us/usmail/UsMailV3RecipientAddress.java | 24 +- .../us/usmail/UsMailV3SenderAddress.java | 20 +- .../java/com/mindee/MindeeClientTest.java | 339 ++++---- .../java/com/mindee/MindeeClientV2IT.java | 95 +- .../java/com/mindee/MindeeClientV2Test.java | 73 +- .../java/com/mindee/TestingUtilities.java | 21 +- .../mindee/extraction/ImageExtractorTest.java | 106 ++- .../InvoiceSplitterAutoExtractionIT.java | 46 +- .../mindee/extraction/PDFExtractorTest.java | 28 +- .../com/mindee/geometry/BboxUtilsTest.java | 50 +- .../mindee/geometry/BoundingBoxUtilsTest.java | 104 ++- .../com/mindee/geometry/PolygonSample.java | 12 +- .../com/mindee/geometry/PolygonUtilsTest.java | 47 +- .../com/mindee/http/MindeeHttpApiTest.java | 448 +++++----- .../com/mindee/input/FileCompressionTest.java | 274 +++--- .../mindee/input/LocalInputSourceTest.java | 31 +- .../com/mindee/input/LocalResponseV1Test.java | 26 +- .../com/mindee/input/LocalResponseV2Test.java | 19 +- .../com/mindee/input/URLInputSourceIT.java | 6 +- .../com/mindee/input/URLInputSourceTest.java | 6 +- .../common/AsyncPredictResponseTest.java | 37 +- .../mindee/parsing/common/CropperTest.java | 11 +- .../com/mindee/parsing/common/ErrorTest.java | 16 +- .../parsing/common/FullTextOcrTest.java | 27 +- .../com/mindee/parsing/common/OcrTest.java | 18 +- .../custom/lineitems/FakeListField.java | 815 +++++++++++------- .../custom/lineitems/LineGeneratorTest.java | 69 +- .../parsing/standard/DateFieldTest.java | 28 +- .../com/mindee/parsing/v2/InferenceTest.java | 56 +- .../java/com/mindee/pdf/PDFUtilsTest.java | 26 +- .../java/com/mindee/pdf/PdfOperationTest.java | 85 +- .../barcodereader/BarcodeReaderV1Test.java | 20 +- .../billoflading/BillOfLadingV1Test.java | 20 +- .../businesscard/BusinessCardV1Test.java | 20 +- .../mindee/product/cropper/CropperV1Test.java | 31 +- .../mindee/product/custom/CustomV1Test.java | 16 +- .../custom/CustomV1WithLineItemsTest.java | 43 +- .../deliverynote/DeliveryNoteV1Test.java | 20 +- .../driverlicense/DriverLicenseV1Test.java | 20 +- .../FinancialDocumentV1Test.java | 109 ++- .../BankAccountDetailsV1Test.java | 27 +- .../BankAccountDetailsV2Test.java | 27 +- .../fr/cartegrise/CarteGriseV1Test.java | 20 +- .../fr/energybill/EnergyBillV1Test.java | 20 +- .../fr/healthcard/HealthCardV1Test.java | 22 +- .../product/fr/idcard/IdCardV1Test.java | 31 +- .../product/fr/idcard/IdCardV2Test.java | 31 +- .../product/fr/payslip/PayslipV2Test.java | 20 +- .../product/fr/payslip/PayslipV3Test.java | 20 +- .../product/generated/GeneratedV1Test.java | 162 ++-- .../indianpassport/IndianPassportV1Test.java | 20 +- .../InternationalIdV2Test.java | 22 +- .../mindee/product/invoice/InvoiceV4Test.java | 20 +- .../InvoiceSplitterV1Test.java | 22 +- .../MultiReceiptsDetectorV1Test.java | 27 +- .../NutritionFactsLabelV1Test.java | 25 +- .../product/passport/PassportV1Test.java | 20 +- .../mindee/product/receipt/ReceiptV5Test.java | 22 +- .../mindee/product/resume/ResumeV1Test.java | 20 +- .../product/us/bankcheck/BankCheckV1Test.java | 31 +- .../healthcarecard/HealthcareCardV1Test.java | 22 +- .../product/us/usmail/UsMailV3Test.java | 20 +- .../java/com/mindee/workflow/WorkflowIT.java | 49 +- .../com/mindee/workflow/WorkflowTest.java | 95 +- 262 files changed, 5126 insertions(+), 6115 deletions(-) delete mode 100644 checkstyle.xml create mode 100644 eclipse-formatter.xml diff --git a/.github/workflows/_static-analysis.yml b/.github/workflows/_static-analysis.yml index 30acf6ee7..cc96ec2e8 100644 --- a/.github/workflows/_static-analysis.yml +++ b/.github/workflows/_static-analysis.yml @@ -20,4 +20,4 @@ jobs: cache: "maven" - name: Check Code Style - run: mvn --update-snapshots --no-transfer-progress checkstyle:check spotless:check + run: mvn --update-snapshots --no-transfer-progress spotless:check diff --git a/.gitignore b/.gitignore index 389f8e478..cbad0e621 100644 --- a/.gitignore +++ b/.gitignore @@ -36,6 +36,8 @@ hs_err_pid* .idea *.iml .run +.project +.settings # Mac OS .DS_Store diff --git a/checkstyle.xml b/checkstyle.xml deleted file mode 100644 index 21556b93a..000000000 --- a/checkstyle.xml +++ /dev/null @@ -1,392 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/eclipse-formatter.xml b/eclipse-formatter.xml new file mode 100644 index 000000000..c38bfde7f --- /dev/null +++ b/eclipse-formatter.xml @@ -0,0 +1,405 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pom.xml b/pom.xml index aa6087618..7f77f70f9 100644 --- a/pom.xml +++ b/pom.xml @@ -94,25 +94,6 @@ 1.8 - - org.apache.maven.plugins - maven-checkstyle-plugin - 3.6.0 - - - com.puppycrawl.tools - checkstyle - - 10.14.2 - - - - checkstyle.xml - true - true - error - - com.diffplug.spotless spotless-maven-plugin @@ -122,6 +103,9 @@ + + ${project.basedir}/eclipse-formatter.xml + diff --git a/src/main/java/com/mindee/AsyncPollingOptions.java b/src/main/java/com/mindee/AsyncPollingOptions.java index bcbb22f41..004c6f72a 100644 --- a/src/main/java/com/mindee/AsyncPollingOptions.java +++ b/src/main/java/com/mindee/AsyncPollingOptions.java @@ -22,11 +22,7 @@ public class AsyncPollingOptions { Integer maxRetries; @Builder - private AsyncPollingOptions( - Double initialDelaySec, - Double intervalSec, - Integer maxRetries - ) { + private AsyncPollingOptions(Double initialDelaySec, Double intervalSec, Integer maxRetries) { this.initialDelaySec = initialDelaySec == null ? 2.0 : initialDelaySec; this.intervalSec = intervalSec == null ? 1.5 : intervalSec; this.maxRetries = maxRetries == null ? 80 : maxRetries; diff --git a/src/main/java/com/mindee/CommandLineInterface.java b/src/main/java/com/mindee/CommandLineInterface.java index 7b4e908e7..3e19341ba 100644 --- a/src/main/java/com/mindee/CommandLineInterface.java +++ b/src/main/java/com/mindee/CommandLineInterface.java @@ -33,7 +33,7 @@ @Command( name = "CLI", description = "Invoke Off The Shelf API for invoice, receipt, and passports", - subcommands = {CommandLine.HelpCommand.class}, + subcommands = { CommandLine.HelpCommand.class }, mixinStandardHelpOptions = true ) public class CommandLineInterface implements ProductProcessor { @@ -42,7 +42,7 @@ public class CommandLineInterface implements ProductProcessor { CommandSpec spec; @Option( - names = {"-w", "--all-words"}, + names = { "-w", "--all-words" }, scope = ScopeType.INHERIT, paramLabel = "WORDS", description = "Include all document words in the response" @@ -50,43 +50,50 @@ public class CommandLineInterface implements ProductProcessor { private boolean words; @Option( - names = {"-f", "--full-text"}, + names = { "-f", "--full-text" }, scope = ScopeType.INHERIT, paramLabel = "FULL_TEXT", description = "Include full text response, if available" ) private boolean fullText; - private enum OutputChoices { summary, full, raw } + private enum OutputChoices { + summary, + full, + raw + } @Option( - names = {"-o", "--output-type"}, + names = { "-o", "--output-type" }, scope = ScopeType.INHERIT, paramLabel = "OUTPUT_TYPE", description = "Output type, one of:\n" - + " summary - document predictions\n" - + " full - all predictions\n" - + " raw - raw response from the server", + + " summary - document predictions\n" + + " full - all predictions\n" + + " raw - raw response from the server", defaultValue = "summary" ) private OutputChoices outputType; @Option( - names = {"-k", "--api-key"}, + names = { "-k", "--api-key" }, scope = ScopeType.INHERIT, paramLabel = "MINDEE_API_KEY", - description = "API key, if not set, will use system property") + description = "API key, if not set, will use system property" + ) private String apiKey; @Option( - names = {"-c", "--cut-doc"}, + names = { "-c", "--cut-doc" }, scope = ScopeType.INHERIT, paramLabel = "", - description = "Keep only the first 5 pages of the document") + description = "Keep only the first 5 pages of the document" + ) private boolean cutDoc; /** - * Instantiates all products one by one in a separate picocli instance and relays the command to them. + * Instantiates all products one by one in a separate picocli instance and relays the command to + * them. * * @param args CLI args. */ @@ -112,7 +119,10 @@ public static void main(String[] args) { /** * Adds all commands from CommandLineInterfaceProducts automatically. */ - @CommandLine.Command(mixinStandardHelpOptions = true, description = "Auto-generated product command") + @CommandLine.Command( + mixinStandardHelpOptions = true, + description = "Auto-generated product command" + ) public static class ProductCommandHandler implements Callable { private final CommandLineInterfaceProducts products; private final Method method; @@ -145,23 +155,20 @@ public Integer call() throws Exception { ) void customMethod( @Option( - names = {"-a", "--account"}, + names = { "-a", "--account" }, scope = ScopeType.LOCAL, required = true, paramLabel = "accountName", description = "The name of the account" - ) - String accountName, + ) String accountName, @Option( - names = {"-e", "--endpointName"}, + names = { "-e", "--endpointName" }, scope = ScopeType.LOCAL, required = true, paramLabel = "endpointName", description = "The name of the endpoint" - ) - String endpointName, - @Parameters(index = "0", scope = ScopeType.LOCAL, paramLabel = "") - File file + ) String endpointName, + @Parameters(index = "0", scope = ScopeType.LOCAL, paramLabel = "") File file ) throws IOException { MindeeClient mindeeClient = new MindeeClient(apiKey); @@ -170,14 +177,9 @@ void customMethod( Endpoint endpoint = new Endpoint(endpointName, accountName, "1"); if (cutDoc) { - document = mindeeClient.parse( - new LocalInputSource(file), - endpoint, - getDefaultPageOptions()); + document = mindeeClient.parse(new LocalInputSource(file), endpoint, getDefaultPageOptions()); } else { - document = mindeeClient.parse( - new LocalInputSource(file), - endpoint); + document = mindeeClient.parse(new LocalInputSource(file), endpoint); } System.out.println(document.toString()); } @@ -185,38 +187,33 @@ void customMethod( @Command(name = "generated", description = "Invokes a Generated API") void generatedMethod( @Option( - names = {"-a", "--account"}, + names = { "-a", "--account" }, scope = ScopeType.LOCAL, required = true, paramLabel = "accountName", description = "The name of the account" - ) - String accountName, + ) String accountName, @Option( - names = {"-e", "--endpointName"}, + names = { "-e", "--endpointName" }, scope = ScopeType.LOCAL, required = true, paramLabel = "endpointName", description = "The name of the endpoint" - ) - String endpointName, + ) String endpointName, @Option( - names = {"-v", "--productVersion"}, + names = { "-v", "--productVersion" }, scope = ScopeType.LOCAL, paramLabel = "productVersion", description = "The version of the endpoint", defaultValue = "1" - ) - String productVersion, + ) String productVersion, @Option( - names = {"-m", "--parsingMode"}, + names = { "-m", "--parsingMode" }, description = "Whether to parse the document in synchronous mode or polling.", scope = ScopeType.LOCAL, defaultValue = "async" - ) - String parsingMode, - @Parameters(index = "0", scope = ScopeType.LOCAL, paramLabel = "") - File file + ) String parsingMode, + @Parameters(index = "0", scope = ScopeType.LOCAL, paramLabel = "") File file ) throws IOException, InterruptedException { MindeeClient mindeeClient = new MindeeClient(apiKey); @@ -225,38 +222,29 @@ void generatedMethod( if (Objects.equals(parsingMode, "sync")) { if (cutDoc) { - PredictResponse document = mindeeClient.parse( - GeneratedV1.class, - endpoint, - new LocalInputSource(file), - getDefaultPageOptions() - ); + PredictResponse document = mindeeClient + .parse(GeneratedV1.class, endpoint, new LocalInputSource(file), getDefaultPageOptions()); System.out.println(document.toString()); } else { - PredictResponse document = mindeeClient.parse( - GeneratedV1.class, - endpoint, - new LocalInputSource(file) - ); + PredictResponse document = mindeeClient + .parse(GeneratedV1.class, endpoint, new LocalInputSource(file)); System.out.println(document.toString()); } } else if (Objects.equals(parsingMode, "async")) { if (cutDoc) { - AsyncPredictResponse document = mindeeClient.enqueueAndParse( + AsyncPredictResponse document = mindeeClient + .enqueueAndParse( GeneratedV1.class, endpoint, new LocalInputSource(file), PredictOptions.builder().build(), getDefaultPageOptions(), AsyncPollingOptions.builder().build() - ); + ); System.out.println(document.toString()); } else { - AsyncPredictResponse document = mindeeClient.enqueueAndParse( - GeneratedV1.class, - endpoint, - new LocalInputSource(file) - ); + AsyncPredictResponse document = mindeeClient + .enqueueAndParse(GeneratedV1.class, endpoint, new LocalInputSource(file)); System.out.println(document.toString()); } } else { @@ -266,31 +254,40 @@ void generatedMethod( protected PageOptions getDefaultPageOptions() { return new PageOptions.Builder() - .pageIndexes(new Integer[]{0, 1, 2, 3, 4}) - .operation(PageOptionsOperation.KEEP_ONLY) - .build(); + .pageIndexes(new Integer[] { 0, 1, 2, 3, 4 }) + .operation(PageOptionsOperation.KEEP_ONLY) + .build(); } private String wordsOutput(Ocr ocr) { StringBuilder output = new StringBuilder(); output.append("\n#############\nDocument Text\n#############\n::\n "); - output.append( - Arrays.stream(ocr.toString().split(String.format("%n"))) - .collect(Collectors.joining(String.format("%n "))) - ); + output + .append( + Arrays + .stream(ocr.toString().split(String.format("%n"))) + .collect(Collectors.joining(String.format("%n "))) + ); output.append("\n"); return output.toString(); } @Override - public > String standardProductOutput(Class productClass, File file) - throws IOException { + public > String standardProductOutput( + Class productClass, + File file + ) throws IOException { MindeeClient mindeeClient = new MindeeClient(apiKey); LocalInputSource inputSource = new LocalInputSource(file); PredictResponse response; - PredictOptions predictOptions = PredictOptions.builder().allWords(words).fullText(fullText).build(); + PredictOptions predictOptions = PredictOptions + .builder() + .allWords(words) + .fullText(fullText) + .build(); if (cutDoc) { - response = mindeeClient.parse(productClass, inputSource, predictOptions, getDefaultPageOptions()); + response = mindeeClient + .parse(productClass, inputSource, predictOptions, getDefaultPageOptions()); } else { response = mindeeClient.parse(productClass, inputSource, predictOptions); } @@ -304,9 +301,7 @@ private String wordsOutput(Ocr ocr) { output.append(response.getRawResponse()); break; default: - output.append( - response.getDocument().getInference().getPrediction().toString() - ); + output.append(response.getDocument().getInference().getPrediction().toString()); } if (words) { output.append(wordsOutput(response.getDocument().getOcr())); @@ -315,20 +310,24 @@ private String wordsOutput(Ocr ocr) { } @Override - public > String standardProductAsyncOutput(Class productClass, File file) - throws IOException, InterruptedException { + public > String standardProductAsyncOutput( + Class productClass, + File file + ) throws IOException, InterruptedException { MindeeClient mindeeClient = new MindeeClient(apiKey); LocalInputSource inputSource = new LocalInputSource(file); AsyncPredictResponse response; - PredictOptions predictOptions = PredictOptions.builder().allWords(words).fullText(fullText).build(); + PredictOptions predictOptions = PredictOptions + .builder() + .allWords(words) + .fullText(fullText) + .build(); if (cutDoc) { - response = mindeeClient.enqueueAndParse( - productClass, inputSource, predictOptions, getDefaultPageOptions(), null - ); + response = mindeeClient + .enqueueAndParse(productClass, inputSource, predictOptions, getDefaultPageOptions(), null); } else { - response = mindeeClient.enqueueAndParse( - productClass, inputSource, predictOptions, null, null - ); + response = mindeeClient + .enqueueAndParse(productClass, inputSource, predictOptions, null, null); } StringBuilder output = new StringBuilder(); @@ -340,9 +339,7 @@ productClass, inputSource, predictOptions, getDefaultPageOptions(), null output.append(response.getRawResponse()); break; default: - output.append( - response.getDocumentObj().getInference().getPrediction().toString() - ); + output.append(response.getDocumentObj().getInference().getPrediction().toString()); } if (words) { output.append(wordsOutput(response.getDocumentObj().getOcr())); diff --git a/src/main/java/com/mindee/InferenceParameters.java b/src/main/java/com/mindee/InferenceParameters.java index 81c043bdb..f27e84f40 100644 --- a/src/main/java/com/mindee/InferenceParameters.java +++ b/src/main/java/com/mindee/InferenceParameters.java @@ -36,7 +36,8 @@ public final class InferenceParameters { */ private final String alias; /** - * Webhook IDs to call after all processing is finished. If empty, no webhooks will be used. + * Webhook IDs to call after all processing is finished. + * If empty, no webhooks will be used. */ private final String[] webhookIds; /** @@ -44,7 +45,8 @@ public final class InferenceParameters { */ private final AsyncPollingOptions pollingOptions; /** - * Additional text context used by the model during inference. Not recommended, for specific use only. + * Additional text context used by the model during inference. + * Not recommended, for specific use only. */ private final String textContext; /** @@ -73,7 +75,7 @@ public static final class Builder { private Boolean polygon = null; private Boolean confidence = null; private String alias; - private String[] webhookIds = new String[]{}; + private String[] webhookIds = new String[] {}; private String textContext; private String dataSchema; private AsyncPollingOptions pollingOptions = AsyncPollingOptions.builder().build(); @@ -142,16 +144,16 @@ public Builder pollingOptions(AsyncPollingOptions pollingOptions) { /** Build an immutable {@link InferenceParameters} instance. */ public InferenceParameters build() { return new InferenceParameters( - modelId, - rag, - rawText, - polygon, - confidence, - alias, - webhookIds, - pollingOptions, - textContext, - dataSchema + modelId, + rag, + rawText, + polygon, + confidence, + alias, + webhookIds, + pollingOptions, + textContext, + dataSchema ); } } diff --git a/src/main/java/com/mindee/MindeeClient.java b/src/main/java/com/mindee/MindeeClient.java index c5c9a7127..32d961ceb 100644 --- a/src/main/java/com/mindee/MindeeClient.java +++ b/src/main/java/com/mindee/MindeeClient.java @@ -61,6 +61,7 @@ public MindeeClient(MindeeApi mindeeApi) { /** * Create a MindeeClient. + * * @param pdfOperation The PdfOperation implementation to be used by the created MindeeClient. * @param mindeeApi The MindeeApi implementation to be used by the created MindeeClient. */ @@ -76,31 +77,24 @@ private static MindeeApi createDefaultApi(String apiKey) { } else { mindeeSettings = new MindeeSettings(); } - return MindeeHttpApi.builder() - .mindeeSettings(mindeeSettings) - .build(); + return MindeeHttpApi.builder().mindeeSettings(mindeeSettings).build(); } /** * Parse a document from an async queue. + * * @param Type of inference. * @param type Type of inference; * @param jobId ID of the job. * @return A valid prediction. */ - public AsyncPredictResponse parseQueued( - Class type, - String jobId - ) { - return this.mindeeApi.documentQueueGet( - type, - new Endpoint(type), - jobId - ); + public AsyncPredictResponse parseQueued(Class type, String jobId) { + return this.mindeeApi.documentQueueGet(type, new Endpoint(type), jobId); } /** * Send a local file to an async queue. + * * @param Type of inference. * @param type Type of inference. * @param localInputSource A local input source file. @@ -111,17 +105,20 @@ public AsyncPredictResponse enqueue( Class type, LocalInputSource localInputSource ) throws IOException { - return this.enqueue( + return this + .enqueue( type, new Endpoint(type), localInputSource.getFile(), localInputSource.getFilename(), null, - null); + null + ); } /** * Retrieves the file after applying page operations to it. + * * @param localInputSource Local input source to apply operations to. * @param pageOptions Options to apply. * @return A byte array of the file after applying page operations. @@ -135,15 +132,16 @@ protected byte[] getSplitFile( if (pageOptions == null || !localInputSource.isPdf()) { splitFile = localInputSource.getFile(); } else { - splitFile = pdfOperation.split( - new SplitQuery(localInputSource.getFile(), pageOptions) - ).getFile(); + splitFile = pdfOperation + .split(new SplitQuery(localInputSource.getFile(), pageOptions)) + .getFile(); } return splitFile; } /** * Send a local file to an async queue. + * * @param Type of inference. * @param type Type of inference. * @param localInputSource A local input source file. @@ -158,18 +156,20 @@ public AsyncPredictResponse enqueue( PredictOptions predictOptions, PageOptions pageOptions ) throws IOException { - return this.enqueue( + return this + .enqueue( type, new Endpoint(type), getSplitFile(localInputSource, pageOptions), localInputSource.getFilename(), predictOptions, - null - ); + null + ); } /** * Send a local file to an async queue. + * * @param Type of inference. * @param type Type of inference. * @param localInputSource A local input source file. @@ -182,18 +182,20 @@ public AsyncPredictResponse enqueue( LocalInputSource localInputSource, PredictOptions predictOptions ) throws IOException { - return this.enqueue( + return this + .enqueue( type, new Endpoint(type), localInputSource.getFile(), localInputSource.getFilename(), predictOptions, null - ); + ); } /** * Send a remote file to an async queue. + * * @param Type of inference. * @param type Type of inference. * @param sourceUrl A URL to a remote file. @@ -205,18 +207,12 @@ public AsyncPredictResponse enqueue( URL sourceUrl ) throws IOException { InputSourceUtils.validateUrl(sourceUrl); - return this.enqueue( - type, - new Endpoint(type), - null, - null, - null, - sourceUrl - ); + return this.enqueue(type, new Endpoint(type), null, null, null, sourceUrl); } /** * Send a remote file to an async queue. + * * @param Type of inference. * @param type Type of inference. * @param sourceUrl A URL to a remote file. @@ -230,14 +226,7 @@ public AsyncPredictResponse enqueue( PredictOptions predictOptions ) throws IOException { InputSourceUtils.validateUrl(sourceUrl); - return this.enqueue( - type, - new Endpoint(type), - null, - null, - predictOptions, - sourceUrl - ); + return this.enqueue(type, new Endpoint(type), null, null, predictOptions, sourceUrl); } private AsyncPredictResponse enqueue( @@ -248,17 +237,19 @@ private AsyncPredictResponse enqueue( PredictOptions predictOptions, URL urlInputSource ) throws IOException { - RequestParameters params = RequestParameters.builder() - .file(file) - .fileName(filename) - .predictOptions(predictOptions) - .urlInputSource(urlInputSource) - .build(); + RequestParameters params = RequestParameters + .builder() + .file(file) + .fileName(filename) + .predictOptions(predictOptions) + .urlInputSource(urlInputSource) + .build(); return this.mindeeApi.predictAsyncPost(type, endpoint, params); } /** * Send a local file to an async queue, poll, and parse when complete. + * * @param Type of inference. * @param type Type of inference. * @param localInputSource A local input source file. @@ -270,18 +261,21 @@ public AsyncPredictResponse enqueueAndParse( Class type, LocalInputSource localInputSource ) throws IOException, InterruptedException { - return this.enqueueAndParse( - type, - new Endpoint(type), - null, - localInputSource.getFile(), - localInputSource.getFilename(), - null, - null); + return this + .enqueueAndParse( + type, + new Endpoint(type), + null, + localInputSource.getFile(), + localInputSource.getFilename(), + null, + null + ); } /** * Send a local file to an async queue, poll, and parse when complete. + * * @param Type of inference. * @param type Type of inference. * @param localInputSource A local input source file. @@ -295,19 +289,21 @@ public AsyncPredictResponse enqueueAndParse( LocalInputSource localInputSource, AsyncPollingOptions pollingOptions ) throws IOException, InterruptedException { - return this.enqueueAndParse( - type, - new Endpoint(type), - pollingOptions, - localInputSource.getFile(), - localInputSource.getFilename(), - null, - null - ); + return this + .enqueueAndParse( + type, + new Endpoint(type), + pollingOptions, + localInputSource.getFile(), + localInputSource.getFilename(), + null, + null + ); } /** * Send a local file to an async queue, poll, and parse when complete. + * * @param Type of inference. * @param type Type of inference. * @param localInputSource A local input source file. @@ -325,19 +321,21 @@ public AsyncPredictResponse enqueueAndParse( PageOptions pageOptions, AsyncPollingOptions pollingOptions ) throws IOException, InterruptedException { - return this.enqueueAndParse( - type, - new Endpoint(type), - pollingOptions, - getSplitFile(localInputSource, pageOptions), - localInputSource.getFilename(), - predictOptions, - null - ); + return this + .enqueueAndParse( + type, + new Endpoint(type), + pollingOptions, + getSplitFile(localInputSource, pageOptions), + localInputSource.getFilename(), + predictOptions, + null + ); } /** * Send a local file to an async queue, poll, and parse when complete. + * * @param Type of inference. * @param type Type of inference. * @param localInputSource A local input source file. @@ -353,7 +351,8 @@ public AsyncPredictResponse enqueueAndParse( PredictOptions predictOptions, AsyncPollingOptions pollingOptions ) throws IOException, InterruptedException { - return this.enqueueAndParse( + return this + .enqueueAndParse( type, new Endpoint(type), pollingOptions, @@ -361,11 +360,12 @@ public AsyncPredictResponse enqueueAndParse( localInputSource.getFilename(), predictOptions, null - ); + ); } /** * Send a local file to an async queue, poll, and parse when complete. + * * @param Type of inference. * @param type Type of inference. * @param localInputSource A local input source file. @@ -379,7 +379,8 @@ public AsyncPredictResponse enqueueAndParse( LocalInputSource localInputSource, PredictOptions predictOptions ) throws IOException, InterruptedException { - return this.enqueueAndParse( + return this + .enqueueAndParse( type, new Endpoint(type), null, @@ -387,11 +388,12 @@ public AsyncPredictResponse enqueueAndParse( localInputSource.getFilename(), predictOptions, null - ); + ); } /** * Send a remote file to an async queue, poll, and parse when complete. + * * @param Type of inference. * @param type Type of inference. * @param sourceUrl A URL to a remote file. @@ -404,19 +406,12 @@ public AsyncPredictResponse enqueueAndParse( URL sourceUrl ) throws IOException, InterruptedException { InputSourceUtils.validateUrl(sourceUrl); - return this.enqueueAndParse( - type, - new Endpoint(type), - null, - null, - null, - null, - sourceUrl - ); + return this.enqueueAndParse(type, new Endpoint(type), null, null, null, null, sourceUrl); } /** * Validate async polling options. + * * @param pollingOptions Options for async call parameters * @throws MindeeException Throws if settings aren't set properly. */ @@ -425,19 +420,20 @@ private void validateAsyncParams(AsyncPollingOptions pollingOptions) { Double minimumIntervalSec = 1.0; Integer minimumRetry = 2; if (pollingOptions.getInitialDelaySec() < minimumInitialDelaySec) { - throw new MindeeException(String.format( - "Cannot set initial delay to less than %.0f second(s)", minimumInitialDelaySec - )); + throw new MindeeException( + String + .format("Cannot set initial delay to less than %.0f second(s)", minimumInitialDelaySec) + ); } if (pollingOptions.getIntervalSec() < minimumIntervalSec) { - throw new MindeeException(String.format( - "Cannot set auto-poll delay to less than %.0f second(s)", minimumIntervalSec - )); + throw new MindeeException( + String.format("Cannot set auto-poll delay to less than %.0f second(s)", minimumIntervalSec) + ); } if (pollingOptions.getMaxRetries() < minimumRetry) { - throw new MindeeException(String.format( - "Cannot set async retries to less than %d attempts", minimumRetry - )); + throw new MindeeException( + String.format("Cannot set async retries to less than %d attempts", minimumRetry) + ); } } @@ -458,12 +454,12 @@ private AsyncPredictResponse enqueueAndParse( final int intervalSec = (int) (pollingOptions.getIntervalSec() * 1000); AsyncPredictResponse enqueueResponse = enqueue( - type, - endpoint, - file, - filename, - predictOptions, - urlInputSource + type, + endpoint, + file, + filename, + predictOptions, + urlInputSource ); String jobId = enqueueResponse.getJob().getId(); @@ -481,11 +477,14 @@ private AsyncPredictResponse enqueueAndParse( retryCount++; Thread.sleep(intervalSec); } - throw new RuntimeException("Max retries exceeded: " + retryCount +". Failed to get the document."); + throw new RuntimeException( + "Max retries exceeded: " + retryCount + ". Failed to get the document." + ); } /** * Send a local file to a workflow execution. + * * @param workflowId ID of the workflow to send the document to. * @param localInputSource A local input source file. * @param workflowOptions Options for the workflow execution. @@ -497,18 +496,22 @@ public WorkflowResponse executeWorkflow( LocalInputSource localInputSource, WorkflowOptions workflowOptions ) throws IOException { - return this.mindeeApi.executeWorkflowPost( + return this.mindeeApi + .executeWorkflowPost( GeneratedV1.class, workflowId, - RequestParameters.builder() - .file(localInputSource.getFile()) - .fileName(localInputSource.getFilename()) - .workflowOptions(workflowOptions) - .build() - ); + RequestParameters + .builder() + .file(localInputSource.getFile()) + .fileName(localInputSource.getFilename()) + .workflowOptions(workflowOptions) + .build() + ); } + /** * Send a local file to a workflow execution. + * * @param workflowId ID of the workflow to send the document to. * @param localInputSource A local input source file. * @return A workflow response. @@ -518,19 +521,22 @@ public WorkflowResponse executeWorkflow( String workflowId, LocalInputSource localInputSource ) throws IOException { - return this.mindeeApi.executeWorkflowPost( + return this.mindeeApi + .executeWorkflowPost( GeneratedV1.class, workflowId, - RequestParameters.builder() - .file(localInputSource.getFile()) - .fileName(localInputSource.getFilename()) - .workflowOptions(WorkflowOptions.builder().build()) - .build() - ); + RequestParameters + .builder() + .file(localInputSource.getFile()) + .fileName(localInputSource.getFilename()) + .workflowOptions(WorkflowOptions.builder().build()) + .build() + ); } /** * Send a local file to a Standard prediction API and parse the results. + * * @param Type of inference. * @param type Type of inference. * @param localInputSource A local input source file. @@ -541,18 +547,20 @@ public PredictResponse parse( Class type, LocalInputSource localInputSource ) throws IOException { - return this.parse( + return this + .parse( type, new Endpoint(type), localInputSource.getFile(), localInputSource.getFilename(), null, null - ); + ); } /** * Send a local file to a Standard prediction API and parse the results. + * * @param Type of inference. * @param type Type of inference. * @param localInputSource A local input source file. @@ -565,18 +573,20 @@ public PredictResponse parse( LocalInputSource localInputSource, PredictOptions predictOptions ) throws IOException { - return this.parse( + return this + .parse( type, new Endpoint(type), localInputSource.getFile(), localInputSource.getFilename(), predictOptions, null - ); + ); } /** * Send a local file to a Standard prediction API and parse the results. + * * @param Type of inference. * @param type Type of inference. * @param localInputSource A local input source file. @@ -589,18 +599,20 @@ public PredictResponse parse( LocalInputSource localInputSource, PageOptions pageOptions ) throws IOException { - return this.parse( + return this + .parse( type, new Endpoint(type), getSplitFile(localInputSource, pageOptions), localInputSource.getFilename(), null, null - ); + ); } /** * Send a local file to a Standard prediction API and parse the results. + * * @param Type of inference. * @param type Type of inference. * @param localInputSource A local input source file. @@ -615,18 +627,20 @@ public PredictResponse parse( PredictOptions predictOptions, PageOptions pageOptions ) throws IOException { - return this.parse( + return this + .parse( type, new Endpoint(type), getSplitFile(localInputSource, pageOptions), localInputSource.getFilename(), predictOptions, null - ); + ); } /** * Send a remote file to a Standard prediction API and parse the results. + * * @param Type of inference. * @param type Type of inference. * @param urlInputSource A URL to a remote file. @@ -643,6 +657,7 @@ public PredictResponse parse( /** * Send a remote file to a Standard prediction API and parse the results. + * * @param Type of inference. * @param type Type of inference. * @param urlInputSource A URL to a remote file. @@ -667,17 +682,19 @@ private PredictResponse parse( PredictOptions predictOptions, URL urlInputSource ) throws IOException { - RequestParameters params = RequestParameters.builder() - .file(file) - .fileName(filename) - .predictOptions(predictOptions) - .urlInputSource(urlInputSource) - .build(); + RequestParameters params = RequestParameters + .builder() + .file(file) + .fileName(filename) + .predictOptions(predictOptions) + .urlInputSource(urlInputSource) + .build(); return this.mindeeApi.predictPost(type, endpoint, params); } /** * Send a local file to a Custom prediction API and parse the results. + * * @param localInputSource A local input source file. * @param endpoint Custom endpoint to send the document to. * @return an instance of {@link PredictResponse}. @@ -687,15 +704,12 @@ public PredictResponse parse( LocalInputSource localInputSource, Endpoint endpoint ) throws IOException { - return this.parse( - localInputSource.getFile(), - localInputSource.getFilename(), - endpoint, - null); + return this.parse(localInputSource.getFile(), localInputSource.getFilename(), endpoint, null); } /** * Send a local file to a Custom prediction API and parse the results. + * * @param localInputSource A local input source file. * @param endpoint Custom endpoint to send the document to. * @param pageOptions Page options for PDF documents. @@ -707,24 +721,24 @@ public PredictResponse parse( Endpoint endpoint, PageOptions pageOptions ) throws IOException { - return this.parse( - getSplitFile(localInputSource, pageOptions), - localInputSource.getFilename(), - endpoint, null - ); + return this + .parse( + getSplitFile(localInputSource, pageOptions), + localInputSource.getFilename(), + endpoint, + null + ); } /** * Send a remote file to a Custom prediction API and parse the results. + * * @param documentUrl A URL to a remote file. * @param endpoint Custom endpoint to send the document to. * @return an instance of {@link PredictResponse}. * @throws IOException Throws if the file can't be accessed. */ - public PredictResponse parse( - URL documentUrl, - Endpoint endpoint - ) throws IOException { + public PredictResponse parse(URL documentUrl, Endpoint endpoint) throws IOException { InputSourceUtils.validateUrl(documentUrl); return this.parse(null, null, endpoint, documentUrl); } @@ -735,18 +749,22 @@ private PredictResponse parse( Endpoint endpoint, URL urlInputSource ) throws IOException { - return this.mindeeApi.predictPost( - CustomV1.class, - endpoint, - RequestParameters.builder() + return this.mindeeApi + .predictPost( + CustomV1.class, + endpoint, + RequestParameters + .builder() .file(file) .fileName(filename) .urlInputSource(urlInputSource) - .build()); + .build() + ); } /** * Send a local file to a Generated prediction async API queue. + * * @param Type of inference. * @param type Type of inference. * @param localInputSource A local input source file. @@ -759,18 +777,20 @@ public AsyncPredictResponse enqueue( Endpoint endpoint, LocalInputSource localInputSource ) throws IOException { - return this.enqueue( - type, - endpoint, - localInputSource.getFile(), - localInputSource.getFilename(), - null, - null - ); + return this + .enqueue( + type, + endpoint, + localInputSource.getFile(), + localInputSource.getFilename(), + null, + null + ); } /** * Send a local file to a Generated prediction async API queue. + * * @param Type of inference. * @param type Type of inference. * @param localInputSource A local input source file. @@ -787,18 +807,20 @@ public AsyncPredictResponse enqueue( PredictOptions predictOptions, PageOptions pageOptions ) throws IOException { - return this.enqueue( - type, - endpoint, - getSplitFile(localInputSource, pageOptions), - localInputSource.getFilename(), - predictOptions, - null - ); + return this + .enqueue( + type, + endpoint, + getSplitFile(localInputSource, pageOptions), + localInputSource.getFilename(), + predictOptions, + null + ); } /** * Send a remote file to a Generated prediction async API queue. + * * @param Type of inference. * @param type Type of inference. * @param endpoint Custom endpoint to send the document to. @@ -812,18 +834,12 @@ public AsyncPredictResponse enqueue( URL sourceUrl ) throws IOException { InputSourceUtils.validateUrl(sourceUrl); - return this.enqueue( - type, - endpoint, - null, - null, - null, - sourceUrl - ); + return this.enqueue(type, endpoint, null, null, null, sourceUrl); } /** * Send a remote file to a Generated prediction async API queue. + * * @param Type of inference. * @param type Type of inference. * @param sourceUrl A URL to a remote file. @@ -839,19 +855,12 @@ public AsyncPredictResponse enqueue( PredictOptions predictOptions ) throws IOException { InputSourceUtils.validateUrl(sourceUrl); - return this.enqueue( - type, - endpoint, - null, - null, - predictOptions, - sourceUrl - ); + return this.enqueue(type, endpoint, null, null, predictOptions, sourceUrl); } - /** * Send a local file to a Generated prediction API async queue, poll, and parse when complete. + * * @param Type of inference. * @param type Type of inference. * @param localInputSource A local input source file. @@ -865,18 +874,21 @@ public AsyncPredictResponse enqueueAndParse( Endpoint endpoint, LocalInputSource localInputSource ) throws IOException, InterruptedException { - return this.enqueueAndParse( - type, - endpoint, - null, - localInputSource.getFile(), - localInputSource.getFilename(), - null, - null); + return this + .enqueueAndParse( + type, + endpoint, + null, + localInputSource.getFile(), + localInputSource.getFilename(), + null, + null + ); } /** * Send a local file to a Generated prediction API async queue, poll, and parse when complete. + * * @param Type of inference. * @param type Type of inference. * @param localInputSource A local input source file. @@ -892,19 +904,21 @@ public AsyncPredictResponse enqueueAndParse( LocalInputSource localInputSource, AsyncPollingOptions pollingOptions ) throws IOException, InterruptedException { - return this.enqueueAndParse( - type, - endpoint, - pollingOptions, - localInputSource.getFile(), - localInputSource.getFilename(), - null, - null - ); + return this + .enqueueAndParse( + type, + endpoint, + pollingOptions, + localInputSource.getFile(), + localInputSource.getFilename(), + null, + null + ); } /** * Send a local file to a Generated prediction API async queue, poll, and parse when complete. + * * @param Type of inference. * @param type Type of inference. * @param localInputSource A local input source file. @@ -924,19 +938,21 @@ public AsyncPredictResponse enqueueAndParse( PageOptions pageOptions, AsyncPollingOptions pollingOptions ) throws IOException, InterruptedException { - return this.enqueueAndParse( - type, - endpoint, - pollingOptions, - getSplitFile(localInputSource, pageOptions), - localInputSource.getFilename(), - predictOptions, - null - ); + return this + .enqueueAndParse( + type, + endpoint, + pollingOptions, + getSplitFile(localInputSource, pageOptions), + localInputSource.getFilename(), + predictOptions, + null + ); } /** * Send a remote file to a Generated prediction API async queue, poll, and parse when complete. + * * @param Type of inference. * @param type Type of inference. * @param endpoint Custom endpoint to send the document to. @@ -951,19 +967,12 @@ public AsyncPredictResponse enqueueAndParse( URL sourceUrl ) throws IOException, InterruptedException { InputSourceUtils.validateUrl(sourceUrl); - return this.enqueueAndParse( - type, - endpoint, - null, - null, - null, - null, - sourceUrl - ); + return this.enqueueAndParse(type, endpoint, null, null, null, null, sourceUrl); } /** * Send a local file to a Generated prediction API and parse the results. + * * @param Type of inference. * @param type Type of inference. * @param localInputSource A local input source file. @@ -976,18 +985,20 @@ public PredictResponse parse( Endpoint endpoint, LocalInputSource localInputSource ) throws IOException { - return this.parse( - type, - endpoint, - localInputSource.getFile(), - localInputSource.getFilename(), - null, - null - ); + return this + .parse( + type, + endpoint, + localInputSource.getFile(), + localInputSource.getFilename(), + null, + null + ); } /** * Send a local file to a Generated prediction API and parse the results. + * * @param Type of inference. * @param type Type of inference. * @param localInputSource A local input source file. @@ -1002,18 +1013,20 @@ public PredictResponse parse( LocalInputSource localInputSource, PredictOptions predictOptions ) throws IOException { - return this.parse( - type, - endpoint, - localInputSource.getFile(), - localInputSource.getFilename(), - predictOptions, - null - ); + return this + .parse( + type, + endpoint, + localInputSource.getFile(), + localInputSource.getFilename(), + predictOptions, + null + ); } /** * Send a local file to a Generated prediction API and parse the results. + * * @param Type of inference. * @param type Type of inference. * @param localInputSource A local input source file. @@ -1028,18 +1041,20 @@ public PredictResponse parse( LocalInputSource localInputSource, PageOptions pageOptions ) throws IOException { - return this.parse( - type, - endpoint, - getSplitFile(localInputSource, pageOptions), - localInputSource.getFilename(), - null, - null - ); + return this + .parse( + type, + endpoint, + getSplitFile(localInputSource, pageOptions), + localInputSource.getFilename(), + null, + null + ); } /** * Send a local file to a Standard prediction API and parse the results. + * * @param Type of inference. * @param type Type of inference. * @param localInputSource A local input source file. @@ -1056,18 +1071,20 @@ public PredictResponse parse( PredictOptions predictOptions, PageOptions pageOptions ) throws IOException { - return this.parse( - type, - endpoint, - getSplitFile(localInputSource, pageOptions), - localInputSource.getFilename(), - predictOptions, - null - ); + return this + .parse( + type, + endpoint, + getSplitFile(localInputSource, pageOptions), + localInputSource.getFilename(), + predictOptions, + null + ); } /** * Send a remote file to a Generated prediction API and parse the results. + * * @param Type of inference. * @param type Type of inference. * @param endpoint Custom endpoint to send the document to. @@ -1086,6 +1103,7 @@ public PredictResponse parse( /** * Send a remote file to a Generated prediction API and parse the results. + * * @param Type of inference. * @param type Type of inference. * @param documentUrl A URL to a remote file. @@ -1106,6 +1124,7 @@ public PredictResponse parse( /** * Parse a document from a Generated prediction API async queue. + * * @param Type of inference. * @param type Type of inference. * @param endpoint Custom endpoint to send the document to. @@ -1117,17 +1136,14 @@ public AsyncPredictResponse parseQueued( Endpoint endpoint, String jobId ) { - return this.mindeeApi.documentQueueGet( - type, - endpoint, - jobId - ); + return this.mindeeApi.documentQueueGet(type, endpoint, jobId); } /** * Load a local prediction. * Typically used when wanting to load from a webhook callback. * However, any kind of Mindee response may be loaded. + * * @param Type of inference. * @param type Type of inference. * @param localResponse A loaded local response. @@ -1140,10 +1156,9 @@ public AsyncPredictResponse loadPrediction( ) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType parametricType = objectMapper.getTypeFactory().constructParametricType( - AsyncPredictResponse.class, - type - ); + JavaType parametricType = objectMapper + .getTypeFactory() + .constructParametricType(AsyncPredictResponse.class, type); return objectMapper.readValue(localResponse.getFile(), parametricType); } diff --git a/src/main/java/com/mindee/MindeeClientV2.java b/src/main/java/com/mindee/MindeeClientV2.java index cf8a68942..12097af80 100644 --- a/src/main/java/com/mindee/MindeeClientV2.java +++ b/src/main/java/com/mindee/MindeeClientV2.java @@ -26,7 +26,6 @@ public MindeeClientV2(String apiKey) { this(createDefaultApiV2(apiKey)); } - /** Inject both a PDF implementation and an HTTP implementation. */ public MindeeClientV2(MindeeApiV2 mindeeApi) { this.mindeeApi = mindeeApi; @@ -42,7 +41,6 @@ public JobResponse enqueueInference( return mindeeApi.reqPostInferenceEnqueue(inputSource, params); } - /** * Enqueue a document in the asynchronous queue. */ @@ -77,6 +75,7 @@ public InferenceResponse getInference(String inferenceId) { /** * Send a local file to an async queue, poll, and parse when complete. + * * @param inputSource The input source to send. * @param options The options to send along with the file. * @return an instance of {@link InferenceResponse}. @@ -92,10 +91,9 @@ public InferenceResponse enqueueAndGetInference( return pollAndFetch(job, options); } - - /** * Send a local file to an async queue, poll, and parse when complete. + * * @param inputSource The input source to send. * @param options The options to send along with the file. * @return an instance of {@link InferenceResponse}. @@ -111,9 +109,9 @@ public InferenceResponse enqueueAndGetInference( return pollAndFetch(job, options); } - /** * Common logic for polling an asynchronous job for local & url files. + * * @param initialJob The initial job response. * @return an instance of {@link InferenceResponse}. * @throws InterruptedException Throws if interrupted. @@ -152,9 +150,7 @@ private static MindeeApiV2 createDefaultApiV2(String apiKey) { MindeeSettingsV2 settings = apiKey == null || apiKey.trim().isEmpty() ? new MindeeSettingsV2() : new MindeeSettingsV2(apiKey); - return MindeeHttpApiV2.builder() - .mindeeSettings(settings) - .build(); + return MindeeHttpApiV2.builder().mindeeSettings(settings).build(); } private static void validatePollingOptions(AsyncPollingOptions p) { diff --git a/src/main/java/com/mindee/cli/CommandLineInterfaceProducts.java b/src/main/java/com/mindee/cli/CommandLineInterfaceProducts.java index 36fd18bd4..ab7d4e8d4 100644 --- a/src/main/java/com/mindee/cli/CommandLineInterfaceProducts.java +++ b/src/main/java/com/mindee/cli/CommandLineInterfaceProducts.java @@ -37,208 +37,299 @@ public class CommandLineInterfaceProducts { /** * Default constructor. + * * @param processor Processor instance to render the products. */ public CommandLineInterfaceProducts(ProductProcessor processor) { this.processor = processor; } - @CommandLine.Command(name = "fr-bank-account-details", description = "Parse using FR Bank Account Details") + @CommandLine.Command( + name = "fr-bank-account-details", + description = "Parse using FR Bank Account Details" + ) void bankAccountDetailsV2Method( - @CommandLine.Parameters(index = "0", paramLabel = "", scope = CommandLine.ScopeType.LOCAL) - File file + @CommandLine.Parameters( + index = "0", + paramLabel = "", + scope = CommandLine.ScopeType.LOCAL + ) File file ) throws IOException, InterruptedException { System.out.println(processor.standardProductOutput(BankAccountDetailsV2.class, file)); } @CommandLine.Command(name = "us-bank-check", description = "Parse using US Bank Check") void bankCheckV1Method( - @CommandLine.Parameters(index = "0", paramLabel = "", scope = CommandLine.ScopeType.LOCAL) - File file + @CommandLine.Parameters( + index = "0", + paramLabel = "", + scope = CommandLine.ScopeType.LOCAL + ) File file ) throws IOException, InterruptedException { System.out.println(processor.standardProductOutput(BankCheckV1.class, file)); } @CommandLine.Command(name = "barcode-reader", description = "Parse using Barcode Reader") void barcodeReaderV1Method( - @CommandLine.Parameters(index = "0", paramLabel = "", scope = CommandLine.ScopeType.LOCAL) - File file + @CommandLine.Parameters( + index = "0", + paramLabel = "", + scope = CommandLine.ScopeType.LOCAL + ) File file ) throws IOException, InterruptedException { System.out.println(processor.standardProductOutput(BarcodeReaderV1.class, file)); } @CommandLine.Command(name = "bill-of-lading", description = "Parse using Bill of Lading") void billOfLadingV1Method( - @CommandLine.Parameters(index = "0", paramLabel = "", scope = CommandLine.ScopeType.LOCAL) - File file + @CommandLine.Parameters( + index = "0", + paramLabel = "", + scope = CommandLine.ScopeType.LOCAL + ) File file ) throws IOException, InterruptedException { System.out.println(processor.standardProductAsyncOutput(BillOfLadingV1.class, file)); } @CommandLine.Command(name = "business-card", description = "Parse using Business Card") void businessCardV1Method( - @CommandLine.Parameters(index = "0", paramLabel = "", scope = CommandLine.ScopeType.LOCAL) - File file + @CommandLine.Parameters( + index = "0", + paramLabel = "", + scope = CommandLine.ScopeType.LOCAL + ) File file ) throws IOException, InterruptedException { System.out.println(processor.standardProductAsyncOutput(BusinessCardV1.class, file)); } @CommandLine.Command(name = "fr-carte-grise", description = "Parse using FR Carte Grise") void carteGriseV1Method( - @CommandLine.Parameters(index = "0", paramLabel = "", scope = CommandLine.ScopeType.LOCAL) - File file + @CommandLine.Parameters( + index = "0", + paramLabel = "", + scope = CommandLine.ScopeType.LOCAL + ) File file ) throws IOException, InterruptedException { System.out.println(processor.standardProductOutput(CarteGriseV1.class, file)); } @CommandLine.Command(name = "cropper", description = "Parse using Cropper") void cropperV1Method( - @CommandLine.Parameters(index = "0", paramLabel = "", scope = CommandLine.ScopeType.LOCAL) - File file + @CommandLine.Parameters( + index = "0", + paramLabel = "", + scope = CommandLine.ScopeType.LOCAL + ) File file ) throws IOException, InterruptedException { System.out.println(processor.standardProductOutput(CropperV1.class, file)); } @CommandLine.Command(name = "delivery-note", description = "Parse using Delivery note") void deliveryNoteV1Method( - @CommandLine.Parameters(index = "0", paramLabel = "", scope = CommandLine.ScopeType.LOCAL) - File file + @CommandLine.Parameters( + index = "0", + paramLabel = "", + scope = CommandLine.ScopeType.LOCAL + ) File file ) throws IOException, InterruptedException { System.out.println(processor.standardProductAsyncOutput(DeliveryNoteV1.class, file)); } @CommandLine.Command(name = "driver-license", description = "Parse using Driver License") void driverLicenseV1Method( - @CommandLine.Parameters(index = "0", paramLabel = "", scope = CommandLine.ScopeType.LOCAL) - File file + @CommandLine.Parameters( + index = "0", + paramLabel = "", + scope = CommandLine.ScopeType.LOCAL + ) File file ) throws IOException, InterruptedException { System.out.println(processor.standardProductAsyncOutput(DriverLicenseV1.class, file)); } @CommandLine.Command(name = "fr-energy-bill", description = "Parse using FR Energy Bill") void energyBillV1Method( - @CommandLine.Parameters(index = "0", paramLabel = "", scope = CommandLine.ScopeType.LOCAL) - File file + @CommandLine.Parameters( + index = "0", + paramLabel = "", + scope = CommandLine.ScopeType.LOCAL + ) File file ) throws IOException, InterruptedException { System.out.println(processor.standardProductAsyncOutput(EnergyBillV1.class, file)); } @CommandLine.Command(name = "financial-document", description = "Parse using Financial Document") void financialDocumentV1Method( - @CommandLine.Parameters(index = "0", paramLabel = "", scope = CommandLine.ScopeType.LOCAL) - File file + @CommandLine.Parameters( + index = "0", + paramLabel = "", + scope = CommandLine.ScopeType.LOCAL + ) File file ) throws IOException, InterruptedException { System.out.println(processor.standardProductAsyncOutput(FinancialDocumentV1.class, file)); } @CommandLine.Command(name = "fr-health-card", description = "Parse using FR Health Card") void healthCardV1Method( - @CommandLine.Parameters(index = "0", paramLabel = "", scope = CommandLine.ScopeType.LOCAL) - File file + @CommandLine.Parameters( + index = "0", + paramLabel = "", + scope = CommandLine.ScopeType.LOCAL + ) File file ) throws IOException, InterruptedException { System.out.println(processor.standardProductAsyncOutput(HealthCardV1.class, file)); } @CommandLine.Command(name = "us-healthcare-card", description = "Parse using US Healthcare Card") void healthcareCardV1Method( - @CommandLine.Parameters(index = "0", paramLabel = "", scope = CommandLine.ScopeType.LOCAL) - File file + @CommandLine.Parameters( + index = "0", + paramLabel = "", + scope = CommandLine.ScopeType.LOCAL + ) File file ) throws IOException, InterruptedException { System.out.println(processor.standardProductAsyncOutput(HealthcareCardV1.class, file)); } - @CommandLine.Command(name = "fr-carte-nationale-d-identite", description = "Parse using FR Carte Nationale d'Identité") + @CommandLine.Command( + name = "fr-carte-nationale-d-identite", + description = "Parse using FR Carte Nationale d'Identité" + ) void idCardV2Method( - @CommandLine.Parameters(index = "0", paramLabel = "", scope = CommandLine.ScopeType.LOCAL) - File file + @CommandLine.Parameters( + index = "0", + paramLabel = "", + scope = CommandLine.ScopeType.LOCAL + ) File file ) throws IOException, InterruptedException { System.out.println(processor.standardProductOutput(IdCardV2.class, file)); } - @CommandLine.Command(name = "ind-passport-india", description = "Parse using IND Passport - India") + @CommandLine.Command( + name = "ind-passport-india", + description = "Parse using IND Passport - India" + ) void indianPassportV1Method( - @CommandLine.Parameters(index = "0", paramLabel = "", scope = CommandLine.ScopeType.LOCAL) - File file + @CommandLine.Parameters( + index = "0", + paramLabel = "", + scope = CommandLine.ScopeType.LOCAL + ) File file ) throws IOException, InterruptedException { System.out.println(processor.standardProductAsyncOutput(IndianPassportV1.class, file)); } @CommandLine.Command(name = "international-id", description = "Parse using International ID") void internationalIdV2Method( - @CommandLine.Parameters(index = "0", paramLabel = "", scope = CommandLine.ScopeType.LOCAL) - File file + @CommandLine.Parameters( + index = "0", + paramLabel = "", + scope = CommandLine.ScopeType.LOCAL + ) File file ) throws IOException, InterruptedException { System.out.println(processor.standardProductAsyncOutput(InternationalIdV2.class, file)); } @CommandLine.Command(name = "invoice-splitter", description = "Parse using Invoice Splitter") void invoiceSplitterV1Method( - @CommandLine.Parameters(index = "0", paramLabel = "", scope = CommandLine.ScopeType.LOCAL) - File file + @CommandLine.Parameters( + index = "0", + paramLabel = "", + scope = CommandLine.ScopeType.LOCAL + ) File file ) throws IOException, InterruptedException { System.out.println(processor.standardProductAsyncOutput(InvoiceSplitterV1.class, file)); } @CommandLine.Command(name = "invoice", description = "Parse using Invoice") void invoiceV4Method( - @CommandLine.Parameters(index = "0", paramLabel = "", scope = CommandLine.ScopeType.LOCAL) - File file + @CommandLine.Parameters( + index = "0", + paramLabel = "", + scope = CommandLine.ScopeType.LOCAL + ) File file ) throws IOException, InterruptedException { System.out.println(processor.standardProductAsyncOutput(InvoiceV4.class, file)); } - @CommandLine.Command(name = "multi-receipts-detector", description = "Parse using Multi Receipts Detector") + @CommandLine.Command( + name = "multi-receipts-detector", + description = "Parse using Multi Receipts Detector" + ) void multiReceiptsDetectorV1Method( - @CommandLine.Parameters(index = "0", paramLabel = "", scope = CommandLine.ScopeType.LOCAL) - File file + @CommandLine.Parameters( + index = "0", + paramLabel = "", + scope = CommandLine.ScopeType.LOCAL + ) File file ) throws IOException, InterruptedException { System.out.println(processor.standardProductOutput(MultiReceiptsDetectorV1.class, file)); } - @CommandLine.Command(name = "nutrition-facts-label", description = "Parse using Nutrition Facts Label") + @CommandLine.Command( + name = "nutrition-facts-label", + description = "Parse using Nutrition Facts Label" + ) void nutritionFactsLabelV1Method( - @CommandLine.Parameters(index = "0", paramLabel = "", scope = CommandLine.ScopeType.LOCAL) - File file + @CommandLine.Parameters( + index = "0", + paramLabel = "", + scope = CommandLine.ScopeType.LOCAL + ) File file ) throws IOException, InterruptedException { System.out.println(processor.standardProductAsyncOutput(NutritionFactsLabelV1.class, file)); } @CommandLine.Command(name = "passport", description = "Parse using Passport") void passportV1Method( - @CommandLine.Parameters(index = "0", paramLabel = "", scope = CommandLine.ScopeType.LOCAL) - File file + @CommandLine.Parameters( + index = "0", + paramLabel = "", + scope = CommandLine.ScopeType.LOCAL + ) File file ) throws IOException, InterruptedException { System.out.println(processor.standardProductOutput(PassportV1.class, file)); } @CommandLine.Command(name = "fr-payslip", description = "Parse using FR Payslip") void payslipV3Method( - @CommandLine.Parameters(index = "0", paramLabel = "", scope = CommandLine.ScopeType.LOCAL) - File file + @CommandLine.Parameters( + index = "0", + paramLabel = "", + scope = CommandLine.ScopeType.LOCAL + ) File file ) throws IOException, InterruptedException { System.out.println(processor.standardProductAsyncOutput(PayslipV3.class, file)); } @CommandLine.Command(name = "receipt", description = "Parse using Receipt") void receiptV5Method( - @CommandLine.Parameters(index = "0", paramLabel = "", scope = CommandLine.ScopeType.LOCAL) - File file + @CommandLine.Parameters( + index = "0", + paramLabel = "", + scope = CommandLine.ScopeType.LOCAL + ) File file ) throws IOException, InterruptedException { System.out.println(processor.standardProductAsyncOutput(ReceiptV5.class, file)); } @CommandLine.Command(name = "resume", description = "Parse using Resume") void resumeV1Method( - @CommandLine.Parameters(index = "0", paramLabel = "", scope = CommandLine.ScopeType.LOCAL) - File file + @CommandLine.Parameters( + index = "0", + paramLabel = "", + scope = CommandLine.ScopeType.LOCAL + ) File file ) throws IOException, InterruptedException { System.out.println(processor.standardProductAsyncOutput(ResumeV1.class, file)); } @CommandLine.Command(name = "us-us-mail", description = "Parse using US US Mail") void usMailV3Method( - @CommandLine.Parameters(index = "0", paramLabel = "", scope = CommandLine.ScopeType.LOCAL) - File file + @CommandLine.Parameters( + index = "0", + paramLabel = "", + scope = CommandLine.ScopeType.LOCAL + ) File file ) throws IOException, InterruptedException { System.out.println(processor.standardProductAsyncOutput(UsMailV3.class, file)); } diff --git a/src/main/java/com/mindee/cli/ProductProcessor.java b/src/main/java/com/mindee/cli/ProductProcessor.java index d44167ac8..181ecf2ee 100644 --- a/src/main/java/com/mindee/cli/ProductProcessor.java +++ b/src/main/java/com/mindee/cli/ProductProcessor.java @@ -11,22 +11,27 @@ @CommandLine.Command( name = "CLI", scope = CommandLine.ScopeType.INHERIT, - subcommands = {CommandLine.HelpCommand.class}, + subcommands = { CommandLine.HelpCommand.class }, description = "Invoke Off The Shelf API for invoice, receipt, and passports" ) public interface ProductProcessor { /** * Process a product synchronously. + * * @param productClass Product class to be processed for synchronous products. * @param file Input file. * @param Type of the product. * @return A string representation of the result of the parsing. * @throws IOException Throws if the parsing goes wrong. */ - > String standardProductOutput(Class productClass, File file) throws IOException; + > String standardProductOutput( + Class productClass, + File file + ) throws IOException; /** * Process a product asynchronously. + * * @param productClass Product class to be processed for asynchronous products. * @param file Input file. * @param Type of the product. @@ -34,5 +39,8 @@ public interface ProductProcessor { * @throws IOException Throws if the parsing goes wrong. * @throws InterruptedException Throws if the polling is interrupted. */ - > String standardProductAsyncOutput(Class productClass, File file) throws IOException, InterruptedException; + > String standardProductAsyncOutput( + Class productClass, + File file + ) throws IOException, InterruptedException; } diff --git a/src/main/java/com/mindee/extraction/ExtractedImage.java b/src/main/java/com/mindee/extraction/ExtractedImage.java index f6adfcdd5..e5e383238 100644 --- a/src/main/java/com/mindee/extraction/ExtractedImage.java +++ b/src/main/java/com/mindee/extraction/ExtractedImage.java @@ -21,6 +21,7 @@ public class ExtractedImage { /** * Default constructor. + * * @param image Buffered image object. * @param filename Name of the extracted image. * @param saveFormat Format to save the image as, defaults to PNG. @@ -34,6 +35,7 @@ public ExtractedImage(BufferedImage image, String filename, String saveFormat) { /** * Write the image to a file. * Uses the default image format and filename. + * * @param outputPath the output directory (must exist). * @throws IOException Throws if the file can't be accessed. */ @@ -46,6 +48,7 @@ public void writeToFile(String outputPath) throws IOException { /** * Write the image to a file. * Uses the default image format and filename. + * * @param outputPath the output directory (must exist). * @throws IOException Throws if the file can't be accessed. */ @@ -57,6 +60,7 @@ public void writeToFile(Path outputPath) throws IOException { /** * Return the image in a format suitable for sending to MindeeClient for parsing. + * * @return an instance of {@link LocalInputSource} * @throws IOException Throws if the file can't be accessed. */ diff --git a/src/main/java/com/mindee/extraction/ImageExtractor.java b/src/main/java/com/mindee/extraction/ImageExtractor.java index c89803611..403d497e2 100644 --- a/src/main/java/com/mindee/extraction/ImageExtractor.java +++ b/src/main/java/com/mindee/extraction/ImageExtractor.java @@ -25,6 +25,7 @@ public class ImageExtractor { /** * Init from a path. + * * @param filePath Path to the file. * @throws IOException Throws if the file can't be accessed. */ @@ -34,6 +35,7 @@ public ImageExtractor(String filePath) throws IOException { /** * Init from a {@link LocalInputSource}. + * * @param source The local source. * @throws IOException Throws if the file can't be accessed. */ @@ -67,6 +69,7 @@ public int getPageCount() { /** * Extract multiple images on a given page from a list of fields having position data. + * * @param Type of field (needs to support positioning data). * @param fields List of Fields to extract. * @param pageIndex The page index to extract, begins at 0. @@ -81,6 +84,7 @@ public List extractImagesFromPage( /** * Extract multiple images on a given page from a list of fields having position data. + * * @param Type of field (needs to support positioning data). * @param fields List of Fields to extract. * @param pageIndex The page index to extract, begins at 0. @@ -108,12 +112,13 @@ private List extractFromPage( String outputName ) { String[] splitName = InputSourceUtils.splitNameStrict(outputName); - String filename = String.format("%s_page-%3s.%s", splitName[0], pageIndex + 1, splitName[1]) - .replace(" ", "0"); + String filename = String + .format("%s_page-%3s.%s", splitName[0], pageIndex + 1, splitName[1]) + .replace(" ", "0"); List extractedImages = new ArrayList<>(); for (int i = 0; i < fields.size(); i++) { - ExtractedImage extractedImage = extractImage(fields.get(i), pageIndex, i+1, filename); + ExtractedImage extractedImage = extractImage(fields.get(i), pageIndex, i + 1, filename); if (extractedImage != null) { extractedImages.add(extractedImage); } @@ -123,12 +128,14 @@ private List extractFromPage( /** * Extract a single image from a field having position data. + * * @param Type of field (needs to support positioning data). * @param field The field to extract. * @param index The index to use for naming the extracted image. * @param filename Name of the file. * @param pageIndex The page index to extract, begins at 0. - * @return The {@link ExtractedImage}, or null if the field does not have valid position data. + * @return The {@link ExtractedImage}, or null if the field does not have valid + * position data. */ public ExtractedImage extractImage( FieldT field, @@ -144,21 +151,27 @@ public ExtractedImage extractImage( } Bbox bbox = BboxUtils.generate(boundingBox); String fieldFilename = splitName[0] - + String.format("_%3s", index).replace(" ", "0") - + "." - + saveFormat; + + String.format("_%3s", index).replace(" ", "0") + + "." + + saveFormat; return new ExtractedImage(extractImage(bbox, pageIndex), fieldFilename, saveFormat); } /** * Extract a single image from a field having position data. + * * @param Type of field (needs to support positioning data). * @param field The field to extract. * @param index The index to use for naming the extracted image. * @param pageIndex The page index to extract, begins at 0. - * @return The {@link ExtractedImage}, or null if the field does not have valid position data. + * @return The {@link ExtractedImage}, or null if the field does not have valid + * position data. */ - public ExtractedImage extractImage(FieldT field, int pageIndex, int index) { + public ExtractedImage extractImage( + FieldT field, + int pageIndex, + int index + ) { return extractImage(field, pageIndex, index, this.filename); } diff --git a/src/main/java/com/mindee/extraction/PDFExtractor.java b/src/main/java/com/mindee/extraction/PDFExtractor.java index b9a0a7ecb..7f014ad8e 100644 --- a/src/main/java/com/mindee/extraction/PDFExtractor.java +++ b/src/main/java/com/mindee/extraction/PDFExtractor.java @@ -55,8 +55,14 @@ public PDFExtractor(LocalInputSource source) throws IOException { BufferedImage bufferedImage = byteArrayToBufferedImage(source.getFile()); PDImageXObject pdImage = LosslessFactory.createFromImage(document, bufferedImage); try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) { - contentStream.drawImage(pdImage, 100, 600, (float) pdImage.getWidth() / 2, - (float) pdImage.getHeight() / 2); + contentStream + .drawImage( + pdImage, + 100, + 600, + (float) pdImage.getWidth() / 2, + (float) pdImage.getHeight() / 2 + ); } this.sourcePdf = document; @@ -92,8 +98,9 @@ public static BufferedImage byteArrayToBufferedImage(byte[] byteArray) throws IO * @return A list of extracted files. * @throws IOException Throws if the file can't be accessed. */ - public List extractSubDocuments(List> pageIndexes) - throws IOException { + public List extractSubDocuments( + List> pageIndexes + ) throws IOException { List extractedPDFs = new ArrayList<>(); for (List pageIndexElement : pageIndexes) { @@ -101,14 +108,21 @@ public List extractSubDocuments(List> pageIndexes) throw new MindeeException("Empty indexes not allowed for extraction."); } String[] splitName = InputSourceUtils.splitNameStrict(filename); - String fieldFilename = - splitName[0] + String.format("_%3s", pageIndexElement.get(0) + 1).replace(" ", "0") - + "-" - + String.format("%3s", pageIndexElement.get(pageIndexElement.size() - 1) + 1) - .replace(" ", "0") + "." + splitName[1]; - extractedPDFs.add( - new ExtractedPDF(Loader.loadPDF(mergePdfPages(this.sourcePdf, pageIndexElement, false)), - fieldFilename)); + String fieldFilename = splitName[0] + + String.format("_%3s", pageIndexElement.get(0) + 1).replace(" ", "0") + + "-" + + String + .format("%3s", pageIndexElement.get(pageIndexElement.size() - 1) + 1) + .replace(" ", "0") + + "." + + splitName[1]; + extractedPDFs + .add( + new ExtractedPDF( + Loader.loadPDF(mergePdfPages(this.sourcePdf, pageIndexElement, false)), + fieldFilename + ) + ); } return extractedPDFs; } @@ -124,9 +138,10 @@ public List extractInvoices( List pageIndexes ) throws IOException { - List> indexes = - pageIndexes.stream().map(InvoiceSplitterV1InvoicePageGroup::getPageIndexes) - .collect(Collectors.toList()); + List> indexes = pageIndexes + .stream() + .map(InvoiceSplitterV1InvoicePageGroup::getPageIndexes) + .collect(Collectors.toList()); return extractSubDocuments(indexes); } diff --git a/src/main/java/com/mindee/geometry/Bbox.java b/src/main/java/com/mindee/geometry/Bbox.java index 8a9e50812..4f4f3dd8b 100644 --- a/src/main/java/com/mindee/geometry/Bbox.java +++ b/src/main/java/com/mindee/geometry/Bbox.java @@ -34,12 +34,13 @@ public Bbox(double minX, double maxX, double minY, double maxY) { * Get the Bbox as a Polygon. */ public Polygon getAsPolygon() { - List points = Arrays.asList( + List points = Arrays + .asList( new Point(this.minX, this.minY), new Point(this.maxX, this.minY), new Point(this.maxX, this.maxY), new Point(this.minX, this.maxY) - ); + ); return new Polygon(points); } } diff --git a/src/main/java/com/mindee/geometry/BboxUtils.java b/src/main/java/com/mindee/geometry/BboxUtils.java index 8ee0db999..0b4ca8bcd 100644 --- a/src/main/java/com/mindee/geometry/BboxUtils.java +++ b/src/main/java/com/mindee/geometry/BboxUtils.java @@ -20,22 +20,19 @@ public static Bbox generate(Polygon polygon) { return null; } - DoubleSummaryStatistics statsX = polygon.getCoordinates() - .stream() - .mapToDouble(Point::getX) - .summaryStatistics(); + DoubleSummaryStatistics statsX = polygon + .getCoordinates() + .stream() + .mapToDouble(Point::getX) + .summaryStatistics(); - DoubleSummaryStatistics statsY = polygon.getCoordinates() - .stream() - .mapToDouble(Point::getY) - .summaryStatistics(); + DoubleSummaryStatistics statsY = polygon + .getCoordinates() + .stream() + .mapToDouble(Point::getY) + .summaryStatistics(); - return new Bbox( - statsX.getMin(), - statsX.getMax(), - statsY.getMin(), - statsY.getMax() - ); + return new Bbox(statsX.getMin(), statsX.getMax(), statsY.getMin(), statsY.getMax()); } /** @@ -47,8 +44,7 @@ public static Bbox generate(List polygons) { return null; } - Optional mergedPolygon = polygons.stream() - .reduce(PolygonUtils::combine); + Optional mergedPolygon = polygons.stream().reduce(PolygonUtils::combine); if (!mergedPolygon.isPresent()) { return null; diff --git a/src/main/java/com/mindee/geometry/BoundingBoxUtils.java b/src/main/java/com/mindee/geometry/BoundingBoxUtils.java index 413f7ce59..d4b8e31bf 100644 --- a/src/main/java/com/mindee/geometry/BoundingBoxUtils.java +++ b/src/main/java/com/mindee/geometry/BoundingBoxUtils.java @@ -11,18 +11,26 @@ private BoundingBoxUtils() { } public static Polygon createBoundingBoxFrom(Polygon polygon) { - DoubleSummaryStatistics xStatistics = polygon.getCoordinates().stream() - .mapToDouble(Point::getX) - .summaryStatistics(); + DoubleSummaryStatistics xStatistics = polygon + .getCoordinates() + .stream() + .mapToDouble(Point::getX) + .summaryStatistics(); - DoubleSummaryStatistics yStatistics = polygon.getCoordinates() - .stream().mapToDouble(Point::getY) - .summaryStatistics(); + DoubleSummaryStatistics yStatistics = polygon + .getCoordinates() + .stream() + .mapToDouble(Point::getY) + .summaryStatistics(); - return new Polygon(Arrays.asList( - new Point(xStatistics.getMin(), yStatistics.getMin()), - new Point(xStatistics.getMax(), yStatistics.getMin()), - new Point(xStatistics.getMax(), yStatistics.getMax()), - new Point(xStatistics.getMin(), yStatistics.getMax()))); + return new Polygon( + Arrays + .asList( + new Point(xStatistics.getMin(), yStatistics.getMin()), + new Point(xStatistics.getMax(), yStatistics.getMin()), + new Point(xStatistics.getMax(), yStatistics.getMax()), + new Point(xStatistics.getMin(), yStatistics.getMax()) + ) + ); } } diff --git a/src/main/java/com/mindee/geometry/MinMax.java b/src/main/java/com/mindee/geometry/MinMax.java index 38fdba751..6dead2368 100644 --- a/src/main/java/com/mindee/geometry/MinMax.java +++ b/src/main/java/com/mindee/geometry/MinMax.java @@ -1,4 +1,5 @@ package com.mindee.geometry; + import lombok.Getter; /** Minimum and maximum values. */ diff --git a/src/main/java/com/mindee/geometry/PolygonDeserializer.java b/src/main/java/com/mindee/geometry/PolygonDeserializer.java index a9567f000..22b4ead3b 100644 --- a/src/main/java/com/mindee/geometry/PolygonDeserializer.java +++ b/src/main/java/com/mindee/geometry/PolygonDeserializer.java @@ -31,7 +31,9 @@ public Polygon deserialize( ) throws IOException { ArrayNode node = jsonParser.getCodec().readTree(jsonParser); - List> polygonList = mapper.readerFor(new TypeReference>>() {}).readValue(node); + TypeReference>> typeRef = new TypeReference>>() { + }; + List> polygonList = mapper.readerFor(typeRef).readValue(node); return PolygonUtils.getFrom(polygonList); } diff --git a/src/main/java/com/mindee/geometry/PolygonUtils.java b/src/main/java/com/mindee/geometry/PolygonUtils.java index aca931750..ee32a294f 100644 --- a/src/main/java/com/mindee/geometry/PolygonUtils.java +++ b/src/main/java/com/mindee/geometry/PolygonUtils.java @@ -17,9 +17,10 @@ private PolygonUtils() { * Create a Polygon from a list of a list of floats. */ public static Polygon getFrom(List> polygon) { - List coordinates = polygon.stream() - .map(coordinate -> new Point(coordinate.get(0), coordinate.get(1))) - .collect(Collectors.toList()); + List coordinates = polygon + .stream() + .map(coordinate -> new Point(coordinate.get(0), coordinate.get(1))) + .collect(Collectors.toList()); return new Polygon(coordinates); } @@ -29,12 +30,8 @@ public static Polygon getFrom(List> polygon) { public static Point getCentroid(List vertices) { int verticesSum = vertices.size(); - double xSum = vertices.stream() - .map(Point::getX) - .mapToDouble(Double::doubleValue).sum(); - double ySum = vertices.stream() - .map(Point::getY) - .mapToDouble(Double::doubleValue).sum(); + double xSum = vertices.stream().map(Point::getX).mapToDouble(Double::doubleValue).sum(); + double ySum = vertices.stream().map(Point::getY).mapToDouble(Double::doubleValue).sum(); return new Point(xSum / verticesSum, ySum / verticesSum); } @@ -94,58 +91,70 @@ public static boolean isPointInPolygonY(Point centroid, Polygon polygon) { } public static Double getMinYCoordinate(Polygon polygon) { - OptionalDouble min = polygon.getCoordinates().stream() - .map(Point::getY) - .mapToDouble(Double::doubleValue).min(); + OptionalDouble min = polygon + .getCoordinates() + .stream() + .map(Point::getY) + .mapToDouble(Double::doubleValue) + .min(); if (min.isPresent()) { return min.getAsDouble(); } throw new IllegalStateException( - "The min Y could not be found " + "The min Y could not be found " + "because it seems that there is no coordinates in the current polygon." ); } public static Double getMaxYCoordinate(Polygon polygon) { - OptionalDouble max = polygon.getCoordinates().stream() - .map(Point::getY) - .mapToDouble(Double::doubleValue).max(); + OptionalDouble max = polygon + .getCoordinates() + .stream() + .map(Point::getY) + .mapToDouble(Double::doubleValue) + .max(); if (max.isPresent()) { return max.getAsDouble(); } throw new IllegalStateException( - "The max Y could not be found " + "The max Y could not be found " + "because it seems that there is no coordinates in the current polygon." ); } public static Double getMinXCoordinate(Polygon polygon) { - OptionalDouble min = polygon.getCoordinates().stream() - .map(Point::getX) - .mapToDouble(Double::doubleValue).min(); + OptionalDouble min = polygon + .getCoordinates() + .stream() + .map(Point::getX) + .mapToDouble(Double::doubleValue) + .min(); if (min.isPresent()) { return min.getAsDouble(); } throw new IllegalStateException( - "The min X could not be found " + "The min X could not be found " + "because it seems that there is no coordinates in the current polygon." ); } public static Double getMaxXCoordinate(Polygon polygon) { - OptionalDouble max = polygon.getCoordinates().stream() - .map(Point::getX) - .mapToDouble(Double::doubleValue).max(); + OptionalDouble max = polygon + .getCoordinates() + .stream() + .map(Point::getX) + .mapToDouble(Double::doubleValue) + .max(); if (max.isPresent()) { return max.getAsDouble(); } throw new IllegalStateException( - "The max X could not be found " + "The max X could not be found " + "because it seems that there is no coordinates in the current polygon." ); } @@ -165,47 +174,78 @@ public static Polygon combine(Polygon base, Polygon target) { target = base; } - Double maxx = Math.max( - target.getCoordinates().stream() + Double maxx = Math + .max( + target + .getCoordinates() + .stream() .map(Point::getX) - .max(Double::compareTo).orElse(Double.MIN_VALUE), - base.getCoordinates().stream() + .max(Double::compareTo) + .orElse(Double.MIN_VALUE), + base + .getCoordinates() + .stream() .map(Point::getX) - .max(Double::compareTo).orElse(Double.MIN_VALUE)); - - Double minx = Math.min( - target.getCoordinates().stream() + .max(Double::compareTo) + .orElse(Double.MIN_VALUE) + ); + + Double minx = Math + .min( + target + .getCoordinates() + .stream() .map(Point::getX) - .min(Double::compareTo).orElse(Double.MAX_VALUE), - base.getCoordinates().stream() + .min(Double::compareTo) + .orElse(Double.MAX_VALUE), + base + .getCoordinates() + .stream() .map(Point::getX) - .min(Double::compareTo).orElse(Double.MAX_VALUE)); - - Double maxy = Math.max( - target.getCoordinates().stream() + .min(Double::compareTo) + .orElse(Double.MAX_VALUE) + ); + + Double maxy = Math + .max( + target + .getCoordinates() + .stream() .map(Point::getY) - .max(Double::compareTo).orElse(Double.MIN_VALUE), - base.getCoordinates().stream() + .max(Double::compareTo) + .orElse(Double.MIN_VALUE), + base + .getCoordinates() + .stream() .map(Point::getY) - .max(Double::compareTo).orElse(Double.MIN_VALUE) - ); - - Double miny = Math.min( - target.getCoordinates().stream() + .max(Double::compareTo) + .orElse(Double.MIN_VALUE) + ); + + Double miny = Math + .min( + target + .getCoordinates() + .stream() .map(Point::getY) - .min(Double::compareTo).orElse(Double.MAX_VALUE), - base.getCoordinates().stream() + .min(Double::compareTo) + .orElse(Double.MAX_VALUE), + base + .getCoordinates() + .stream() .map(Point::getY) - .min(Double::compareTo).orElse(Double.MAX_VALUE) - ); + .min(Double::compareTo) + .orElse(Double.MAX_VALUE) + ); return new Polygon( - Arrays.asList( - new Point(minx, miny), - new Point(maxx, miny), - new Point(maxx, maxy), - new Point(minx, maxy) - ) + Arrays + .asList( + new Point(minx, miny), + new Point(maxx, miny), + new Point(maxx, maxy), + new Point(minx, maxy) + ) ); } } diff --git a/src/main/java/com/mindee/http/CustomEndpointInfo.java b/src/main/java/com/mindee/http/CustomEndpointInfo.java index 76892e213..a872a701f 100644 --- a/src/main/java/com/mindee/http/CustomEndpointInfo.java +++ b/src/main/java/com/mindee/http/CustomEndpointInfo.java @@ -6,7 +6,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - /** * Endpoint settings for custom documents. */ diff --git a/src/main/java/com/mindee/http/Endpoint.java b/src/main/java/com/mindee/http/Endpoint.java index a57339694..4b074203a 100644 --- a/src/main/java/com/mindee/http/Endpoint.java +++ b/src/main/java/com/mindee/http/Endpoint.java @@ -41,19 +41,17 @@ public Endpoint(Class documentClass) { // that means it could be custom document if (endpointAnnotation == null) { - CustomEndpointInfo customEndpointAnnotation = documentClass.getAnnotation( - CustomEndpointInfo.class - ); - if (customEndpointAnnotation == null) { + CustomEndpointInfo annotation = documentClass.getAnnotation(CustomEndpointInfo.class); + if (annotation == null) { throw new MindeeException( "The class is not supported as a prediction model. " + "The endpoint attribute is missing. " + "Please refer to the document or contact support." ); } - this.endpointName = customEndpointAnnotation.endpointName(); - this.accountName = customEndpointAnnotation.accountName(); - this.version = customEndpointAnnotation.version(); + this.endpointName = annotation.endpointName(); + this.accountName = annotation.accountName(); + this.version = annotation.version(); return; } this.endpointName = endpointAnnotation.endpointName(); diff --git a/src/main/java/com/mindee/http/EndpointInfo.java b/src/main/java/com/mindee/http/EndpointInfo.java index d0f06e7c3..08b30b874 100644 --- a/src/main/java/com/mindee/http/EndpointInfo.java +++ b/src/main/java/com/mindee/http/EndpointInfo.java @@ -6,7 +6,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - /** * Base info for all endpoints. */ diff --git a/src/main/java/com/mindee/http/MindeeApiCommon.java b/src/main/java/com/mindee/http/MindeeApiCommon.java index ebbe66f2f..0f3c68632 100644 --- a/src/main/java/com/mindee/http/MindeeApiCommon.java +++ b/src/main/java/com/mindee/http/MindeeApiCommon.java @@ -10,6 +10,7 @@ public abstract class MindeeApiCommon { /** * Retrieves the user agent. + * * @return the user agent. */ protected String getUserAgent() { @@ -35,6 +36,7 @@ protected String getUserAgent() { /** * Checks if the status code is out of the 2xx-3xx range. + * * @param statusCode the status code to check. * @return {@code true} if the status code is in the 2xx range, false otherwise. */ @@ -45,7 +47,7 @@ protected boolean isInvalidStatusCode(int statusCode) { protected String readRawResponse(HttpEntity responseEntity) throws IOException { ByteArrayOutputStream contentRead = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; - for (int length; (length = responseEntity.getContent().read(buffer)) != -1; ) { + for (int length; (length = responseEntity.getContent().read(buffer)) != -1;) { contentRead.write(buffer, 0, length); } return contentRead.toString("UTF-8"); diff --git a/src/main/java/com/mindee/http/MindeeApiV2.java b/src/main/java/com/mindee/http/MindeeApiV2.java index 59fa37c02..3f327ce22 100644 --- a/src/main/java/com/mindee/http/MindeeApiV2.java +++ b/src/main/java/com/mindee/http/MindeeApiV2.java @@ -14,6 +14,7 @@ public abstract class MindeeApiV2 extends MindeeApiCommon { /** * Send a file to the prediction queue with a local file. + * * @param inputSource Local input source from URL. * @param options parameters. */ @@ -24,6 +25,7 @@ public abstract JobResponse reqPostInferenceEnqueue( /** * Send a file to the prediction queue with a remote file. + * * @param inputSource Remote input source from URL. * @param options parameters. */ @@ -34,14 +36,14 @@ public abstract JobResponse reqPostInferenceEnqueue( /** * Attempts to poll the queue. + * * @param jobId id of the job to get. */ - public abstract JobResponse reqGetJob( - String jobId - ); + public abstract JobResponse reqGetJob(String jobId); /** * Retrieves the inference from a 302 redirect. + * * @param inferenceId ID of the inference to poll. */ abstract public InferenceResponse reqGetInference(String inferenceId); @@ -51,11 +53,11 @@ public abstract JobResponse reqGetJob( */ protected ErrorResponse makeUnknownError(int statusCode) { return new ErrorResponse( - "Unknown Error", - "The server returned an Unknown error.", - statusCode, - statusCode + "-000", - null + "Unknown Error", + "The server returned an Unknown error.", + statusCode, + statusCode + "-000", + null ); } } diff --git a/src/main/java/com/mindee/http/MindeeHttpApi.java b/src/main/java/com/mindee/http/MindeeHttpApi.java index 2278e285d..3e97434e4 100644 --- a/src/main/java/com/mindee/http/MindeeHttpApi.java +++ b/src/main/java/com/mindee/http/MindeeHttpApi.java @@ -80,15 +80,7 @@ public final class MindeeHttpApi extends MindeeApi { private final Function workflowUrlFromId; public MindeeHttpApi(MindeeSettings mindeeSettings) { - this( - mindeeSettings, - null, - null, - null, - null, - null, - null - ); + this(mindeeSettings, null, null, null, null, null, null); } @Builder @@ -112,29 +104,28 @@ private MindeeHttpApi( if (urlFromEndpoint != null) { this.urlFromEndpoint = urlFromEndpoint; } else { - this.urlFromEndpoint = buildProductPredicBasetUrl.andThen( - (url) -> url.concat("/predict")); + this.urlFromEndpoint = buildProductPredicBasetUrl.andThen((url) -> url.concat("/predict")); } if (asyncUrlFromWorkflow != null) { this.asyncUrlFromWorkflow = asyncUrlFromWorkflow; } else { - this.asyncUrlFromWorkflow = this.buildWorkflowPredictBaseUrl.andThen( - (url) -> url.concat("/predict_async")); + this.asyncUrlFromWorkflow = this.buildWorkflowPredictBaseUrl + .andThen((url) -> url.concat("/predict_async")); } if (asyncUrlFromEndpoint != null) { this.asyncUrlFromEndpoint = asyncUrlFromEndpoint; } else { - this.asyncUrlFromEndpoint = this.buildProductPredicBasetUrl.andThen( - (url) -> url.concat("/predict_async")); + this.asyncUrlFromEndpoint = this.buildProductPredicBasetUrl + .andThen((url) -> url.concat("/predict_async")); } if (documentUrlFromEndpoint != null) { this.documentUrlFromEndpoint = documentUrlFromEndpoint; } else { - this.documentUrlFromEndpoint = this.buildProductPredicBasetUrl.andThen( - (url) -> url.concat("/documents/queue/")); + this.documentUrlFromEndpoint = this.buildProductPredicBasetUrl + .andThen((url) -> url.concat("/documents/queue/")); } if (workflowUrlFromEndpoint != null) { @@ -157,10 +148,9 @@ public AsyncPredictResponse documentQueueGet( // required to register jackson date module format to deserialize mapper.findAndRegisterModules(); - JavaType parametricType = mapper.getTypeFactory().constructParametricType( - AsyncPredictResponse.class, - documentClass - ); + JavaType parametricType = mapper + .getTypeFactory() + .constructParametricType(AsyncPredictResponse.class, documentClass); if (this.mindeeSettings.getApiKey().isPresent()) { get.setHeader(HttpHeaders.AUTHORIZATION, this.mindeeSettings.getApiKey().get()); @@ -168,32 +158,29 @@ public AsyncPredictResponse documentQueueGet( get.setHeader(HttpHeaders.USER_AGENT, getUserAgent()); try (CloseableHttpClient httpClient = httpClientBuilder.build()) { - return httpClient.execute( - get, response -> { - HttpEntity responseEntity = response.getEntity(); - int statusCode = response.getCode(); - if (isInvalidStatusCode(statusCode)) { - throw getHttpError(parametricType, response); - } - String rawResponse = readRawResponse(responseEntity); - AsyncPredictResponse mappedResponse = - mapper.readValue(rawResponse, parametricType); - mappedResponse.setRawResponse(rawResponse); - if ( - mappedResponse.getJob() != null - && mappedResponse.getJob().getError() != null - && mappedResponse.getJob().getError().getCode() != null - ) { - throw new MindeeHttpException( - 500, - mappedResponse.getJob().getError().getMessage(), - mappedResponse.getJob().getError().getDetails().toString(), - mappedResponse.getJob().getError().getCode() - ); - } - return mappedResponse; - } - ); + return httpClient.execute(get, response -> { + HttpEntity responseEntity = response.getEntity(); + int statusCode = response.getCode(); + if (isInvalidStatusCode(statusCode)) { + throw getHttpError(parametricType, response); + } + String rawResponse = readRawResponse(responseEntity); + AsyncPredictResponse mappedResponse = mapper.readValue(rawResponse, parametricType); + mappedResponse.setRawResponse(rawResponse); + if ( + mappedResponse.getJob() != null + && mappedResponse.getJob().getError() != null + && mappedResponse.getJob().getError().getCode() != null + ) { + throw new MindeeHttpException( + 500, + mappedResponse.getJob().getError().getMessage(), + mappedResponse.getJob().getError().getDetails().toString(), + mappedResponse.getJob().getError().getCode() + ); + } + return mappedResponse; + }); } catch (IOException err) { throw new MindeeException(err.getMessage(), err); } @@ -213,27 +200,24 @@ public PredictResponse predictPost( // required to register jackson date module format to deserialize mapper.findAndRegisterModules(); - JavaType parametricType = mapper.getTypeFactory().constructParametricType( - PredictResponse.class, - documentClass - ); + JavaType parametricType = mapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, documentClass); try (CloseableHttpClient httpClient = httpClientBuilder.build()) { - return httpClient.execute( - post, response -> { - HttpEntity responseEntity = response.getEntity(); - int statusCode = response.getCode(); - if (isInvalidStatusCode(statusCode)) { - throw getHttpError(parametricType, response); - } - if (responseEntity.getContentLength() == 0) { - throw new MindeeException("Empty response from server."); - } - String rawResponse = readRawResponse(responseEntity); - PredictResponse mappedResponse = mapper.readValue(rawResponse, parametricType); - mappedResponse.setRawResponse(rawResponse); - return mappedResponse; - } - ); + return httpClient.execute(post, response -> { + HttpEntity responseEntity = response.getEntity(); + int statusCode = response.getCode(); + if (isInvalidStatusCode(statusCode)) { + throw getHttpError(parametricType, response); + } + if (responseEntity.getContentLength() == 0) { + throw new MindeeException("Empty response from server."); + } + String rawResponse = readRawResponse(responseEntity); + PredictResponse mappedResponse = mapper.readValue(rawResponse, parametricType); + mappedResponse.setRawResponse(rawResponse); + return mappedResponse; + }); } catch (IOException err) { throw new MindeeException(err.getMessage(), err); } @@ -258,34 +242,29 @@ public AsyncPredictResponse predictAsyncPost( // required to register jackson date module format to deserialize mapper.findAndRegisterModules(); - JavaType parametricType = mapper.getTypeFactory().constructParametricType( - AsyncPredictResponse.class, - documentClass - ); + JavaType parametricType = mapper + .getTypeFactory() + .constructParametricType(AsyncPredictResponse.class, documentClass); try (CloseableHttpClient httpClient = httpClientBuilder.build()) { - return httpClient.execute( - post, response -> { - HttpEntity responseEntity = response.getEntity(); - int statusCode = response.getCode(); - if (isInvalidStatusCode(statusCode)) { - throw getHttpError(parametricType, response); - } - if (responseEntity.getContentLength() == 0) { - throw new MindeeException("Empty response from server."); - } - String rawResponse = readRawResponse(responseEntity); - AsyncPredictResponse mappedResponse = - mapper.readValue(rawResponse, parametricType); - mappedResponse.setRawResponse(rawResponse); - return mappedResponse; - } - ); + return httpClient.execute(post, response -> { + HttpEntity responseEntity = response.getEntity(); + int statusCode = response.getCode(); + if (isInvalidStatusCode(statusCode)) { + throw getHttpError(parametricType, response); + } + if (responseEntity.getContentLength() == 0) { + throw new MindeeException("Empty response from server."); + } + String rawResponse = readRawResponse(responseEntity); + AsyncPredictResponse mappedResponse = mapper.readValue(rawResponse, parametricType); + mappedResponse.setRawResponse(rawResponse); + return mappedResponse; + }); } catch (IOException err) { throw new MindeeException(err.getMessage(), err); } } - /** * POST a prediction request for a workflow response. */ @@ -300,10 +279,9 @@ public WorkflowResponse executeWorkflowPost( // required to register jackson date module format to deserialize mapper.findAndRegisterModules(); - JavaType parametricType = mapper.getTypeFactory().constructParametricType( - WorkflowResponse.class, - documentClass - ); + JavaType parametricType = mapper + .getTypeFactory() + .constructParametricType(WorkflowResponse.class, documentClass); try (CloseableHttpClient httpClient = httpClientBuilder.build()) { return httpClient.execute(post, response -> { HttpEntity responseEntity = response.getEntity(); @@ -324,7 +302,6 @@ public WorkflowResponse executeWorkflowPost( } } - private MindeeHttpException getHttpError( JavaType parametricType, ClassicHttpResponse response @@ -362,12 +339,12 @@ private MindeeHttpException getHttpError( private String buildProductPredictBaseUrl(Endpoint endpoint) { return this.mindeeSettings.getBaseUrl() - + "/products/" - + endpoint.getAccountName() - + "/" - + endpoint.getEndpointName() - + "/v" - + endpoint.getVersion(); + + "/products/" + + endpoint.getAccountName() + + "/" + + endpoint.getEndpointName() + + "/v" + + endpoint.getVersion(); } private String buildWorkflowPredictBaseUrl(String workflowId) { @@ -402,9 +379,7 @@ private HttpPost buildHttpPost( return post; } - private List buildPostParams( - RequestParameters requestParameters - ) { + private List buildPostParams(RequestParameters requestParameters) { ArrayList params = new ArrayList(); if (Boolean.TRUE.equals(requestParameters.getPredictOptions().getCropper())) { params.add(new BasicNameValuePair("cropper", "true")); @@ -412,7 +387,8 @@ private List buildPostParams( if (Boolean.TRUE.equals(requestParameters.getPredictOptions().getFullText())) { params.add(new BasicNameValuePair("full_text_ocr", "true")); } - if (Boolean.TRUE.equals(requestParameters.getWorkflowOptions().getRag()) + if ( + Boolean.TRUE.equals(requestParameters.getWorkflowOptions().getRag()) || Boolean.TRUE.equals(requestParameters.getPredictOptions().getRag()) ) { params.add(new BasicNameValuePair("rag", "true")); @@ -426,42 +402,33 @@ private HttpEntity buildHttpBody( if (requestParameters.getFile() != null) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.EXTENDED); - builder.addBinaryBody( + builder + .addBinaryBody( "document", requestParameters.getFile(), ContentType.DEFAULT_BINARY, requestParameters.getFileName() - ); + ); if (Boolean.TRUE.equals(requestParameters.getPredictOptions().getAllWords())) { builder.addTextBody("include_mvision", "true"); } if (requestParameters.getWorkflowOptions().getPriority() != null) { - builder.addTextBody( - "priority", - requestParameters.getWorkflowOptions().getPriority().getValue() - ); + builder + .addTextBody("priority", requestParameters.getWorkflowOptions().getPriority().getValue()); } if (requestParameters.getWorkflowOptions().getAlias() != null) { - builder.addTextBody( - "alias", - requestParameters.getWorkflowOptions().getAlias().toLowerCase() - ); + builder + .addTextBody("alias", requestParameters.getWorkflowOptions().getAlias().toLowerCase()); } if (requestParameters.getWorkflowOptions().getPublicUrl() != null) { - builder.addTextBody( - "public_url", - requestParameters.getWorkflowOptions().getPublicUrl() - ); + builder.addTextBody("public_url", requestParameters.getWorkflowOptions().getPublicUrl()); } return builder.build(); } else if (requestParameters.getFileUrl() != null) { Map urlMap = new HashMap<>(); urlMap.put("document", requestParameters.getFileUrl()); - return new StringEntity( - mapper.writeValueAsString(urlMap), - ContentType.APPLICATION_JSON - ); + return new StringEntity(mapper.writeValueAsString(urlMap), ContentType.APPLICATION_JSON); } else { throw new MindeeException("Either document bytes or a document URL are needed"); } diff --git a/src/main/java/com/mindee/http/MindeeHttpApiV2.java b/src/main/java/com/mindee/http/MindeeHttpApiV2.java index d2698db31..ad1c1e67e 100644 --- a/src/main/java/com/mindee/http/MindeeHttpApiV2.java +++ b/src/main/java/com/mindee/http/MindeeHttpApiV2.java @@ -45,19 +45,12 @@ public final class MindeeHttpApiV2 extends MindeeApiV2 { */ private final HttpClientBuilder httpClientBuilder; - public MindeeHttpApiV2(MindeeSettingsV2 mindeeSettings) { - this( - mindeeSettings, - null - ); + this(mindeeSettings, null); } @Builder - private MindeeHttpApiV2( - MindeeSettingsV2 mindeeSettings, - HttpClientBuilder httpClientBuilder - ) { + private MindeeHttpApiV2(MindeeSettingsV2 mindeeSettings, HttpClientBuilder httpClientBuilder) { this.mindeeSettings = mindeeSettings; if (httpClientBuilder != null) { @@ -71,7 +64,7 @@ private MindeeHttpApiV2( * Enqueues a doc with the POST method. * * @param inputSource Input source to send. - * @param options Options to send the file along with. + * @param options Options to send the file along with. * @return A job response. */ @Override @@ -84,22 +77,22 @@ public JobResponse reqPostInferenceEnqueue( MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.EXTENDED); - builder.addBinaryBody( + builder + .addBinaryBody( "file", inputSource.getFile(), ContentType.DEFAULT_BINARY, inputSource.getFilename() - ); + ); post.setEntity(buildHttpBody(builder, options)); return executeEnqueue(post); } - /** * Enqueues a doc with the POST method. * * @param inputSource Input source to send. - * @param options Options to send the file along with. + * @param options Options to send the file along with. * @return A job response. */ @Override @@ -112,47 +105,41 @@ public JobResponse reqPostInferenceEnqueue( MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.EXTENDED); - builder.addTextBody( - "url", - inputSource.getUrl() - ); + builder.addTextBody("url", inputSource.getUrl()); post.setEntity(buildHttpBody(builder, options)); return executeEnqueue(post); } /** * Executes an enqueue action, common to URL & local inputs. + * * @param post HTTP Post object. * @return a valid job response. */ private JobResponse executeEnqueue(HttpPost post) { mapper.findAndRegisterModules(); try (CloseableHttpClient httpClient = httpClientBuilder.build()) { - return httpClient.execute( - post, response -> { - HttpEntity responseEntity = response.getEntity(); - int statusCode = response.getCode(); - if (isInvalidStatusCode(statusCode)) { - throw getHttpError(response); - } - try { - String raw = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8); - - return deserializeOrThrow(raw, JobResponse.class, response.getCode()); - } finally { - EntityUtils.consumeQuietly(responseEntity); - } - } - ); + return httpClient.execute(post, response -> { + HttpEntity responseEntity = response.getEntity(); + int statusCode = response.getCode(); + if (isInvalidStatusCode(statusCode)) { + throw getHttpError(response); + } + try { + String raw = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8); + + return deserializeOrThrow(raw, JobResponse.class, response.getCode()); + } finally { + EntityUtils.consumeQuietly(responseEntity); + } + }); } catch (IOException err) { throw new MindeeException(err.getMessage(), err); } } @Override - public JobResponse reqGetJob( - String jobId - ) { + public JobResponse reqGetJob(String jobId) { String url = this.mindeeSettings.getBaseUrl() + "/jobs/" + jobId; HttpGet get = new HttpGet(url); @@ -161,30 +148,25 @@ public JobResponse reqGetJob( get.setHeader(HttpHeaders.AUTHORIZATION, this.mindeeSettings.getApiKey().get()); } get.setHeader(HttpHeaders.USER_AGENT, getUserAgent()); - RequestConfig noRedirect = - RequestConfig.custom() - .setRedirectsEnabled(false) - .build(); + RequestConfig noRedirect = RequestConfig.custom().setRedirectsEnabled(false).build(); get.setConfig(noRedirect); mapper.findAndRegisterModules(); try (CloseableHttpClient httpClient = httpClientBuilder.build()) { - return httpClient.execute( - get, response -> { - HttpEntity responseEntity = response.getEntity(); - int statusCode = response.getCode(); - if (isInvalidStatusCode(statusCode)) { - throw getHttpError(response); - } - try { - String raw = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8); - - return deserializeOrThrow(raw, JobResponse.class, response.getCode()); - } finally { - EntityUtils.consumeQuietly(responseEntity); - } - } - ); + return httpClient.execute(get, response -> { + HttpEntity responseEntity = response.getEntity(); + int statusCode = response.getCode(); + if (isInvalidStatusCode(statusCode)) { + throw getHttpError(response); + } + try { + String raw = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8); + + return deserializeOrThrow(raw, JobResponse.class, response.getCode()); + } finally { + EntityUtils.consumeQuietly(responseEntity); + } + }); } catch (IOException err) { throw new MindeeException(err.getMessage(), err); } @@ -203,24 +185,21 @@ public InferenceResponse reqGetInference(String inferenceId) { mapper.findAndRegisterModules(); - try (CloseableHttpClient httpClient = httpClientBuilder - .build()) { - - return httpClient.execute( - get, - response -> { - HttpEntity entity = response.getEntity(); - int status = response.getCode(); - try { - if (isInvalidStatusCode(status)) { - throw getHttpError(response); - } - String raw = EntityUtils.toString(entity, StandardCharsets.UTF_8); - return deserializeOrThrow(raw, InferenceResponse.class, status); - } finally { - EntityUtils.consumeQuietly(entity); - } - }); + try (CloseableHttpClient httpClient = httpClientBuilder.build()) { + + return httpClient.execute(get, response -> { + HttpEntity entity = response.getEntity(); + int status = response.getCode(); + try { + if (isInvalidStatusCode(status)) { + throw getHttpError(response); + } + String raw = EntityUtils.toString(entity, StandardCharsets.UTF_8); + return deserializeOrThrow(raw, InferenceResponse.class, status); + } finally { + EntityUtils.consumeQuietly(entity); + } + }); } catch (IOException err) { throw new MindeeException(err.getMessage(), err); } @@ -245,11 +224,7 @@ private MindeeHttpExceptionV2 getHttpError(ClassicHttpResponse response) { } } - - private HttpEntity buildHttpBody( - MultipartEntityBuilder builder, - InferenceParameters params - ) { + private HttpEntity buildHttpBody(MultipartEntityBuilder builder, InferenceParameters params) { builder.addTextBody("model_id", params.getModelId()); if (params.getRag() != null) { builder.addTextBody("rag", params.getRag().toString().toLowerCase()); @@ -278,11 +253,7 @@ private HttpEntity buildHttpBody( return builder.build(); } - - private HttpPost buildHttpPost( - String url, - InferenceParameters params - ) { + private HttpPost buildHttpPost(String url, InferenceParameters params) { HttpPost post; try { URIBuilder uriBuilder = new URIBuilder(url); @@ -301,9 +272,11 @@ private HttpPost buildHttpPost( return post; } - private R deserializeOrThrow( - String body, Class clazz, int httpStatus) throws MindeeHttpExceptionV2 { + String body, + Class clazz, + int httpStatus + ) throws MindeeHttpExceptionV2 { if (httpStatus >= 200 && httpStatus < 400) { try { @@ -311,7 +284,9 @@ private R deserializeOrThrow( model.setRawResponse(body); return model; } catch (Exception exception) { - throw new MindeeException("Couldn't deserialize server response:\n" + exception.getMessage()); + throw new MindeeException( + "Couldn't deserialize server response:\n" + exception.getMessage() + ); } } diff --git a/src/main/java/com/mindee/http/MindeeHttpExceptionV2.java b/src/main/java/com/mindee/http/MindeeHttpExceptionV2.java index 056a72747..86db6657e 100644 --- a/src/main/java/com/mindee/http/MindeeHttpExceptionV2.java +++ b/src/main/java/com/mindee/http/MindeeHttpExceptionV2.java @@ -13,7 +13,7 @@ public class MindeeHttpExceptionV2 extends MindeeException { /** Error details. */ private final String detail; - public MindeeHttpExceptionV2(int status, String detail) { + public MindeeHttpExceptionV2(int status, String detail) { super(detail); this.status = status; this.detail = detail; diff --git a/src/main/java/com/mindee/http/RequestParameters.java b/src/main/java/com/mindee/http/RequestParameters.java index 50e913227..c05dffd22 100644 --- a/src/main/java/com/mindee/http/RequestParameters.java +++ b/src/main/java/com/mindee/http/RequestParameters.java @@ -34,7 +34,7 @@ private RequestParameters( } else { this.predictOptions = predictOptions; } - if (workflowOptions == null){ + if (workflowOptions == null) { this.workflowOptions = WorkflowOptions.builder().build(); } else { this.workflowOptions = workflowOptions; diff --git a/src/main/java/com/mindee/image/ImageCompressor.java b/src/main/java/com/mindee/image/ImageCompressor.java index 5cbe890e8..8a58231d4 100644 --- a/src/main/java/com/mindee/image/ImageCompressor.java +++ b/src/main/java/com/mindee/image/ImageCompressor.java @@ -17,7 +17,8 @@ */ public final class ImageCompressor { public static BufferedImage resize( - BufferedImage inputImage, Integer newWidth, + BufferedImage inputImage, + Integer newWidth, Integer newHeight ) { Image scaledImage = inputImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH); @@ -30,21 +31,25 @@ public static BufferedImage resize( return outImage; } - public static byte[] compressImage( - byte[] imageData, Integer quality, Integer maxWidth, + byte[] imageData, + Integer quality, + Integer maxWidth, Integer maxHeight ) throws IOException { ByteArrayInputStream bis = new ByteArrayInputStream(imageData); BufferedImage original = ImageIO.read(bis); - ImageUtils.Dimensions dimensions = - ImageUtils.calculateNewDimensions(original, maxWidth, maxHeight); + ImageUtils.Dimensions dimensions = ImageUtils + .calculateNewDimensions(original, maxWidth, maxHeight); return compressImage(original, quality, dimensions.width, dimensions.height); } - public static byte[] compressImage(byte[] imageData, Integer quality, Integer finalWidth) - throws IOException { + public static byte[] compressImage( + byte[] imageData, + Integer quality, + Integer finalWidth + ) throws IOException { return compressImage(imageData, quality, finalWidth, null); } @@ -74,7 +79,10 @@ public static BufferedImage removeAlphaChannel(BufferedImage original) { return original; } BufferedImage newImage = new BufferedImage( - original.getWidth(), original.getHeight(), BufferedImage.TYPE_INT_RGB); + original.getWidth(), + original.getHeight(), + BufferedImage.TYPE_INT_RGB + ); Graphics2D g = newImage.createGraphics(); g.drawImage(original, 0, 0, null); g.dispose(); @@ -82,11 +90,11 @@ public static BufferedImage removeAlphaChannel(BufferedImage original) { } public static byte[] encodeToJpegByteArray( - BufferedImage image, float quality + BufferedImage image, + float quality ) throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - Iterator writers = ImageIO.getImageWritersByFormatName("jpg"); ImageWriter writer = writers.next(); diff --git a/src/main/java/com/mindee/image/ImageUtils.java b/src/main/java/com/mindee/image/ImageUtils.java index bd2d17bf8..2e5a43bc1 100644 --- a/src/main/java/com/mindee/image/ImageUtils.java +++ b/src/main/java/com/mindee/image/ImageUtils.java @@ -33,10 +33,12 @@ public static Dimensions calculateNewDimensions( return new Dimensions(original.getWidth(), original.getHeight()); } - double widthRatio = - maxWidth != null ? (double) maxWidth / original.getWidth() : Double.POSITIVE_INFINITY; - double heightRatio = - maxHeight != null ? (double) maxHeight / original.getHeight() : Double.POSITIVE_INFINITY; + double widthRatio = maxWidth != null + ? (double) maxWidth / original.getWidth() + : Double.POSITIVE_INFINITY; + double heightRatio = maxHeight != null + ? (double) maxHeight / original.getHeight() + : Double.POSITIVE_INFINITY; double scaleFactor = Math.min(widthRatio, heightRatio); diff --git a/src/main/java/com/mindee/input/InputSourceUtils.java b/src/main/java/com/mindee/input/InputSourceUtils.java index f21b861df..9ebbc15a9 100644 --- a/src/main/java/com/mindee/input/InputSourceUtils.java +++ b/src/main/java/com/mindee/input/InputSourceUtils.java @@ -64,14 +64,17 @@ public static String[] splitNameStrict(String filename) throws MindeeException { } else { throw new MindeeException("File name must include a valid extension."); } - return new String[] {name, extension}; + return new String[] { name, extension }; } /** * Returns true if the file is a PDF. */ public static boolean isPdf(byte[] fileBytes) { - try (PDDocument document = Loader.loadPDF(new RandomAccessReadBuffer(new ByteArrayInputStream(fileBytes)))) { + try ( + PDDocument document = Loader + .loadPDF(new RandomAccessReadBuffer(new ByteArrayInputStream(fileBytes))) + ) { return true; } catch (IOException e) { return false; @@ -96,7 +99,8 @@ public static void validateUrl(URL inputUrl) { */ public static boolean hasSourceText(byte[] fileBytes) { try { - PDDocument document = Loader.loadPDF(new RandomAccessReadBuffer(new ByteArrayInputStream(fileBytes))); + PDDocument document = Loader + .loadPDF(new RandomAccessReadBuffer(new ByteArrayInputStream(fileBytes))); PDFTextStripper stripper = new PDFTextStripper(); for (int i = 0; i < document.getNumberOfPages(); i++) { diff --git a/src/main/java/com/mindee/input/LocalInputSource.java b/src/main/java/com/mindee/input/LocalInputSource.java index d7a695b0e..46fc006c4 100644 --- a/src/main/java/com/mindee/input/LocalInputSource.java +++ b/src/main/java/com/mindee/input/LocalInputSource.java @@ -57,6 +57,7 @@ public LocalInputSource(String fileAsBase64, String filename) { /** * Get the number of pages in the document. + * * @return the number of pages in the current file. * @throws IOException If an I/O error occurs during the PDF operation. */ @@ -76,9 +77,7 @@ public int getPageCount() throws IOException { public void applyPageOptions(PageOptions pageOptions) throws IOException { if (pageOptions != null && this.isPdf()) { PdfOperation pdfOperation = new PdfBoxApi(); - this.file = pdfOperation.split( - new SplitQuery(this.file, pageOptions) - ).getFile(); + this.file = pdfOperation.split(new SplitQuery(this.file, pageOptions)).getFile(); } } @@ -91,8 +90,11 @@ public boolean hasSourceText() { } public void compress( - Integer quality, Integer maxWidth, Integer maxHeight, - Boolean forceSourceText, Boolean disableSourceText + Integer quality, + Integer maxWidth, + Integer maxHeight, + Boolean forceSourceText, + Boolean disableSourceText ) throws IOException { if (isPdf()) { this.file = PdfCompressor.compressPdf(this.file, quality, forceSourceText, disableSourceText); @@ -102,7 +104,9 @@ public void compress( } public void compress( - Integer quality, Integer maxWidth, Integer maxHeight, + Integer quality, + Integer maxWidth, + Integer maxHeight, Boolean forceSourceText ) throws IOException { this.compress(quality, maxWidth, maxHeight, forceSourceText, true); diff --git a/src/main/java/com/mindee/input/LocalResponse.java b/src/main/java/com/mindee/input/LocalResponse.java index 44f327d54..437a1f043 100644 --- a/src/main/java/com/mindee/input/LocalResponse.java +++ b/src/main/java/com/mindee/input/LocalResponse.java @@ -29,17 +29,17 @@ public class LocalResponse { /** * Load from an {@link InputStream}. + * * @param input will be decoded as UTF-8. */ public LocalResponse(InputStream input) { - this.file = this.getBytes( - new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)) - .lines() - ); + this.file = this + .getBytes(new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)).lines()); } /** * Load from a {@link String}. + * * @param input will be decoded as UTF-8. */ public LocalResponse(String input) { @@ -48,22 +48,20 @@ public LocalResponse(String input) { /** * Load from a {@link File}. + * * @param input will be decoded as UTF-8. */ public LocalResponse(File input) throws IOException { - this.file = this.getBytes( - Files.lines(input.toPath(), StandardCharsets.UTF_8) - ); + this.file = this.getBytes(Files.lines(input.toPath(), StandardCharsets.UTF_8)); } /** * Load from a {@link Path}. + * * @param input will be decoded as UTF-8. */ public LocalResponse(Path input) throws IOException { - this.file = this.getBytes( - Files.lines(input, StandardCharsets.UTF_8) - ); + this.file = this.getBytes(Files.lines(input, StandardCharsets.UTF_8)); } private byte[] getBytes(Stream stream) { @@ -72,14 +70,15 @@ private byte[] getBytes(Stream stream) { /** * Get the HMAC signature of the payload. + * * @param secretKey Your secret key from the Mindee platform. * @return The generated HMAC signature. */ public String getHmacSignature(String secretKey) { String algorithm = "HmacSHA256"; SecretKeySpec secretKeySpec = new SecretKeySpec( - secretKey.getBytes(StandardCharsets.UTF_8), - algorithm + secretKey.getBytes(StandardCharsets.UTF_8), + algorithm ); Mac mac; try { @@ -98,6 +97,7 @@ public String getHmacSignature(String secretKey) { /** * Verify that the payload's signature matches the one received from the server. + * * @param secretKey Your secret key from the Mindee platform. * @param signature The signature from the "X-Mindee-Hmac-Signature" HTTP header. * @return true if the signatures match. @@ -106,13 +106,12 @@ public boolean isValidHmacSignature(String secretKey, String signature) { return signature.equals(getHmacSignature(secretKey)); } - /** * Deserialize this local JSON payload into a specific {@link CommonResponse} * subtype: {@code InferenceResponse}, {@code JobResponse}. * * @param responseClass the concrete class to instantiate - * @param generic {@link CommonResponse} + * @param generic {@link CommonResponse} * @return Either a {@code InferenceResponse} or {@code JobResponse} instance. * @throws MindeeException if the payload cannot be deserialized into the requested type */ diff --git a/src/main/java/com/mindee/input/PageOptions.java b/src/main/java/com/mindee/input/PageOptions.java index 2f3cfb564..6e3fc7822 100644 --- a/src/main/java/com/mindee/input/PageOptions.java +++ b/src/main/java/com/mindee/input/PageOptions.java @@ -29,6 +29,7 @@ public class PageOptions { /** * Default constructor. + * * @deprecated Use the Builder pattern instead. */ @Deprecated @@ -38,13 +39,11 @@ public PageOptions(List pages) { /** * Constructor with operation. + * * @deprecated Use the Builder pattern instead. */ @Deprecated - public PageOptions( - List pages, - PageOptionsOperation operation - ) { + public PageOptions(List pages, PageOptionsOperation operation) { this(pages, operation, 0); } @@ -80,6 +79,7 @@ public Builder operation(PageOptionsOperation operation) { this.operation = operation; return this; } + public Builder onMinPages(Integer onMinPages) { this.onMinPages = onMinPages; return this; diff --git a/src/main/java/com/mindee/input/URLInputSource.java b/src/main/java/com/mindee/input/URLInputSource.java index 73c6f4798..7d0b19e39 100644 --- a/src/main/java/com/mindee/input/URLInputSource.java +++ b/src/main/java/com/mindee/input/URLInputSource.java @@ -39,6 +39,7 @@ public class URLInputSource { /** * Creates a new builder for an URLInputSource. + * * @param url URL to fetch the file from. * @return An instance of {@link URLInputSource}. */ @@ -76,8 +77,9 @@ protected HttpURLConnection createConnection(String urlString) throws IOExceptio connection.setInstanceFollowRedirects(true); if (username != null && password != null) { - String encodedCredentials = - Base64.getEncoder().encodeToString((username + ":" + password).getBytes()); + String encodedCredentials = Base64 + .getEncoder() + .encodeToString((username + ":" + password).getBytes()); connection.setRequestProperty("Authorization", "Basic " + encodedCredentials); } if (token != null) { @@ -89,7 +91,8 @@ protected HttpURLConnection createConnection(String urlString) throws IOExceptio private HttpURLConnection handleRedirects(HttpURLConnection connection) throws IOException { int status = connection.getResponseCode(); - if (status == HttpURLConnection.HTTP_MOVED_TEMP + if ( + status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER || status == 307 @@ -99,7 +102,7 @@ private HttpURLConnection handleRedirects(HttpURLConnection connection) throws I connection.disconnect(); HttpURLConnection newConnection = createConnection(newUrl); - return handleRedirects(newConnection); // Recursive call to handle multiple redirects + return handleRedirects(newConnection); // Recursive call to handle multiple redirects } return connection; } @@ -110,8 +113,10 @@ private void saveTempFile(InputStream in) throws IOException { Path tempFile = Files.createTempFile(prefix, ".tmp"); localFilename = tempFile.toString(); - try (InputStream inputStream = in; - OutputStream outputStream = Files.newOutputStream(tempFile)) { + try ( + InputStream inputStream = in; + OutputStream outputStream = Files.newOutputStream(tempFile) + ) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { @@ -120,7 +125,6 @@ private void saveTempFile(InputStream in) throws IOException { } } - private void saveFile(InputStream in, String filepath) throws IOException { File outputFile = new File(filepath); @@ -146,7 +150,7 @@ public LocalInputSource toLocalInputSource() throws IOException { private String generateDefaultFilename() { return "mindee_temp_" - + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")); + + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")); } /** @@ -235,7 +239,6 @@ public Builder withLocalFilename(String filename) { return this; } - /** * Build the {@link URLInputSource} object. * diff --git a/src/main/java/com/mindee/parsing/SummaryHelper.java b/src/main/java/com/mindee/parsing/SummaryHelper.java index 9060ea93e..007cd222c 100644 --- a/src/main/java/com/mindee/parsing/SummaryHelper.java +++ b/src/main/java/com/mindee/parsing/SummaryHelper.java @@ -35,16 +35,18 @@ public static String formatString(String str) { * Given a list of fields, return a string. */ public static String arrayToString(List list, String delimiter) { - return list.stream() - .map(T::toString) - .collect(Collectors.joining(String.format(delimiter))); + return list.stream().map(T::toString).collect(Collectors.joining(String.format(delimiter))); } - public static String arrayToString(List lineItems, int[] columnSizes) { - return lineItems.stream() + public static String arrayToString( + List lineItems, + int[] columnSizes + ) { + return lineItems + .stream() .map(T::toTableLine) - .collect(Collectors.joining( - String.format("%n%s%n ", SummaryHelper.lineSeparator(columnSizes, "-"))) + .collect( + Collectors.joining(String.format("%n%s%n ", SummaryHelper.lineSeparator(columnSizes, "-"))) ); } @@ -55,10 +57,7 @@ public static String formatForDisplay(String inputValue, Integer maxColSize) { if (inputValue == null || inputValue.isEmpty()) { return ""; } - String outputValue = inputValue - .replace("\n", "\\n") - .replace("\t", "\\t") - .replace("\r", "\\r"); + String outputValue = inputValue.replace("\n", "\\n").replace("\t", "\\t").replace("\r", "\\r"); if (maxColSize == null || outputValue.length() <= maxColSize) { return outputValue; } else { diff --git a/src/main/java/com/mindee/parsing/common/ApiRequest.java b/src/main/java/com/mindee/parsing/common/ApiRequest.java index 45dd899cf..7b4bb8e09 100644 --- a/src/main/java/com/mindee/parsing/common/ApiRequest.java +++ b/src/main/java/com/mindee/parsing/common/ApiRequest.java @@ -6,7 +6,6 @@ import lombok.EqualsAndHashCode; import lombok.Getter; - /** * Information from Mindee about the api request. */ @@ -43,12 +42,11 @@ public class ApiRequest { private String url; public String toString() { - return - String.format("###########%n") - + String.format("API Request%n") - + String.format("###########%n") - + String.format(":Status: %s%n", this.status) - + String.format(":Status Code: %s%n", this.statusCode) - + String.format(":Error: %s%n", this.error); + return String.format("###########%n") + + String.format("API Request%n") + + String.format("###########%n") + + String.format(":Status: %s%n", this.status) + + String.format(":Status Code: %s%n", this.statusCode) + + String.format(":Error: %s%n", this.error); } } diff --git a/src/main/java/com/mindee/parsing/common/AsyncPredictResponse.java b/src/main/java/com/mindee/parsing/common/AsyncPredictResponse.java index 929066fa7..64847f2ed 100644 --- a/src/main/java/com/mindee/parsing/common/AsyncPredictResponse.java +++ b/src/main/java/com/mindee/parsing/common/AsyncPredictResponse.java @@ -10,7 +10,7 @@ * Represent a `predict` response from Mindee API. * * @param Set the prediction model used to parse the document. The response object will be - * instantiated based on this parameter. + * instantiated based on this parameter. */ @Data @EqualsAndHashCode(callSuper = true) diff --git a/src/main/java/com/mindee/parsing/common/Document.java b/src/main/java/com/mindee/parsing/common/Document.java index cb2dd8ac3..6d68f2d36 100644 --- a/src/main/java/com/mindee/parsing/common/Document.java +++ b/src/main/java/com/mindee/parsing/common/Document.java @@ -42,8 +42,7 @@ public class Document { @Override public String toString() { - return - String.format("########%n") + return String.format("########%n") + String.format("Document%n") + String.format("########%n") + String.format(":Mindee ID: %s%n", id) diff --git a/src/main/java/com/mindee/parsing/common/Execution.java b/src/main/java/com/mindee/parsing/common/Execution.java index dd75d8f3c..575071b5f 100644 --- a/src/main/java/com/mindee/parsing/common/Execution.java +++ b/src/main/java/com/mindee/parsing/common/Execution.java @@ -103,18 +103,43 @@ public class Execution { @Override public String toString() { - return ":batch_name: " + batchName + "\n" - + ":created_at: " + createdAt + "\n" - + ":file: " + file + "\n" - + ":id: " + id + "\n" - + ":inference: " + inference + "\n" - + ":priority: " + priority + "\n" - + ":reviewed_at: " + reviewedAt + "\n" - + ":available_at: " + availableAt + "\n" - + ":reviewed_prediction: " + reviewedPrediction + "\n" - + ":status: " + status + "\n" - + ":type: " + type + "\n" - + ":uploaded_at: " + uploadedAt + "\n" - + ":workflow_id: " + workflowId; + return ":batch_name: " + + batchName + + "\n" + + ":created_at: " + + createdAt + + "\n" + + ":file: " + + file + + "\n" + + ":id: " + + id + + "\n" + + ":inference: " + + inference + + "\n" + + ":priority: " + + priority + + "\n" + + ":reviewed_at: " + + reviewedAt + + "\n" + + ":available_at: " + + availableAt + + "\n" + + ":reviewed_prediction: " + + reviewedPrediction + + "\n" + + ":status: " + + status + + "\n" + + ":type: " + + type + + "\n" + + ":uploaded_at: " + + uploadedAt + + "\n" + + ":workflow_id: " + + workflowId; } } diff --git a/src/main/java/com/mindee/parsing/common/ExecutionFile.java b/src/main/java/com/mindee/parsing/common/ExecutionFile.java index 5795a4050..c2dd23c89 100644 --- a/src/main/java/com/mindee/parsing/common/ExecutionFile.java +++ b/src/main/java/com/mindee/parsing/common/ExecutionFile.java @@ -28,7 +28,6 @@ public class ExecutionFile { @JsonProperty("alias") private String alias; - @Override public String toString() { return "\n :name: " + name + "\n" + " :alias: " + alias; diff --git a/src/main/java/com/mindee/parsing/common/Inference.java b/src/main/java/com/mindee/parsing/common/Inference.java index 45af102e2..f91fcd041 100644 --- a/src/main/java/com/mindee/parsing/common/Inference.java +++ b/src/main/java/com/mindee/parsing/common/Inference.java @@ -9,7 +9,7 @@ /** * Common inference data. * - * @param Page prediction (can be the same as TDocumentPrediction). + * @param Page prediction (can be the same as TDocumentPrediction). * @param Document prediction (can be the same as TPagePrediction). */ @Getter @@ -44,15 +44,14 @@ public abstract class Inference page.getExtras().getFullTextOcr().getContent()).collect( - Collectors.joining("\n")))); + this.extras + .setFullTextOcr( + String + .join( + "\n", + this.pages + .stream() + .map(page -> page.getExtras().getFullTextOcr().getContent()) + .collect(Collectors.joining("\n")) + ) + ); } } return this.extras; diff --git a/src/main/java/com/mindee/parsing/common/Job.java b/src/main/java/com/mindee/parsing/common/Job.java index 0bddaad71..b8b886882 100644 --- a/src/main/java/com/mindee/parsing/common/Job.java +++ b/src/main/java/com/mindee/parsing/common/Job.java @@ -17,7 +17,7 @@ @JsonIgnoreProperties(ignoreUnknown = true) @AllArgsConstructor @NoArgsConstructor -public class Job{ +public class Job { /** * The time at which the job finished. diff --git a/src/main/java/com/mindee/parsing/common/LocalDateTimeDeserializer.java b/src/main/java/com/mindee/parsing/common/LocalDateTimeDeserializer.java index 6cf4d7b62..33fa5e8f5 100644 --- a/src/main/java/com/mindee/parsing/common/LocalDateTimeDeserializer.java +++ b/src/main/java/com/mindee/parsing/common/LocalDateTimeDeserializer.java @@ -22,21 +22,23 @@ public class LocalDateTimeDeserializer extends JsonDeserializer { @Override public LocalDateTime deserialize( JsonParser jsonParser, - DeserializationContext deserializationContext) throws IOException { + DeserializationContext deserializationContext + ) throws IOException { DateTimeFormatter formatter = new DateTimeFormatterBuilder() - .parseCaseInsensitive() - .append(DateTimeFormatter.ISO_LOCAL_DATE) - .appendLiteral('T') - .append(DateTimeFormatter.ISO_LOCAL_TIME) - .optionalStart() - .appendOffsetId() - .toFormatter(); + .parseCaseInsensitive() + .append(DateTimeFormatter.ISO_LOCAL_DATE) + .appendLiteral('T') + .append(DateTimeFormatter.ISO_LOCAL_TIME) + .optionalStart() + .appendOffsetId() + .toFormatter(); String dateString = jsonParser.getValueAsString(); - TemporalAccessor temporalAccessor = formatter.parseBest(dateString, ZonedDateTime::from, - LocalDateTime::from); + TemporalAccessor temporalAccessor = formatter + .parseBest(dateString, ZonedDateTime::from, LocalDateTime::from); if (temporalAccessor instanceof ZonedDateTime) { - return ((ZonedDateTime) temporalAccessor).withZoneSameInstant(ZoneOffset.UTC) - .toLocalDateTime(); + return ((ZonedDateTime) temporalAccessor) + .withZoneSameInstant(ZoneOffset.UTC) + .toLocalDateTime(); } else { return ((LocalDateTime) temporalAccessor); } diff --git a/src/main/java/com/mindee/parsing/common/Page.java b/src/main/java/com/mindee/parsing/common/Page.java index 2d3b4e9f8..070c00900 100644 --- a/src/main/java/com/mindee/parsing/common/Page.java +++ b/src/main/java/com/mindee/parsing/common/Page.java @@ -39,13 +39,14 @@ public class Page { @Override public String toString() { return String.format("Page %s%n", this.getPageId()) - + String.format("------%n") - + prediction.toString(); + + String.format("------%n") + + prediction.toString(); } /** * Returns true if there are no predictions in this page. - * Accessing prediction values when this is true may result in a {@link NullPointerException} + * Accessing prediction values when this is true may result in a + * {@link NullPointerException} */ public boolean isPredictionEmpty() { // diff --git a/src/main/java/com/mindee/parsing/common/Pages.java b/src/main/java/com/mindee/parsing/common/Pages.java index 7ad02b862..ae4b002fb 100644 --- a/src/main/java/com/mindee/parsing/common/Pages.java +++ b/src/main/java/com/mindee/parsing/common/Pages.java @@ -1,17 +1,17 @@ package com.mindee.parsing.common; + import java.util.ArrayList; import java.util.stream.Collectors; /** * List of all pages in the inference. + * * @param */ public class Pages extends ArrayList> { @Override public String toString() { - return this.stream() - .map(Page::toString) - .collect(Collectors.joining(String.format("%n"))); + return this.stream().map(Page::toString).collect(Collectors.joining(String.format("%n"))); } /** diff --git a/src/main/java/com/mindee/parsing/common/PredictResponse.java b/src/main/java/com/mindee/parsing/common/PredictResponse.java index 4dc3e8a69..ad6c9f782 100644 --- a/src/main/java/com/mindee/parsing/common/PredictResponse.java +++ b/src/main/java/com/mindee/parsing/common/PredictResponse.java @@ -9,7 +9,7 @@ * Represent a `predict` response from Mindee API. * * @param Set the prediction model used to parse the document. The response object will be - * instantiated based on this parameter. + * instantiated based on this parameter. */ @Data @EqualsAndHashCode(callSuper = true) diff --git a/src/main/java/com/mindee/parsing/common/Prediction.java b/src/main/java/com/mindee/parsing/common/Prediction.java index 2e1275700..54dd812ac 100644 --- a/src/main/java/com/mindee/parsing/common/Prediction.java +++ b/src/main/java/com/mindee/parsing/common/Prediction.java @@ -6,7 +6,8 @@ public abstract class Prediction { /** * Returns true if there are no predictions values. - * Accessing prediction values when this is true may result in a {@link NullPointerException} + * Accessing prediction values when this is true may result in a + * {@link NullPointerException} */ public abstract boolean isEmpty(); } diff --git a/src/main/java/com/mindee/parsing/common/WorkflowResponse.java b/src/main/java/com/mindee/parsing/common/WorkflowResponse.java index 4c3d5e2b0..439905c26 100644 --- a/src/main/java/com/mindee/parsing/common/WorkflowResponse.java +++ b/src/main/java/com/mindee/parsing/common/WorkflowResponse.java @@ -23,5 +23,6 @@ public class WorkflowResponse extends ApiResponse { /** * Default product is GeneratedV1. */ - public static class Default extends WorkflowResponse {} + public static class Default extends WorkflowResponse { + } } diff --git a/src/main/java/com/mindee/parsing/common/ocr/MvisionV1.java b/src/main/java/com/mindee/parsing/common/ocr/MvisionV1.java index bd8444752..c27622f4f 100644 --- a/src/main/java/com/mindee/parsing/common/ocr/MvisionV1.java +++ b/src/main/java/com/mindee/parsing/common/ocr/MvisionV1.java @@ -19,7 +19,9 @@ public class MvisionV1 { @Override public String toString() { - return this.getPages().stream() + return this + .getPages() + .stream() .map(OcrPage::toString) .collect(Collectors.joining(String.format("%n"))); } diff --git a/src/main/java/com/mindee/parsing/common/ocr/OcrPage.java b/src/main/java/com/mindee/parsing/common/ocr/OcrPage.java index d116a545d..ce283e566 100644 --- a/src/main/java/com/mindee/parsing/common/ocr/OcrPage.java +++ b/src/main/java/com/mindee/parsing/common/ocr/OcrPage.java @@ -28,23 +28,18 @@ public OcrPage(@JsonProperty("all_words") List allWords) { this.allWords = allWords; // make sure words are sorted from top to bottom - this.allWords.sort( - (word1, word2) -> PolygonUtils.CompareOnY(word1.getPolygon(), word2.getPolygon()) - ); + this.allWords + .sort((word1, word2) -> PolygonUtils.CompareOnY(word1.getPolygon(), word2.getPolygon())); } /** * Determine if two words are on the same line. */ private boolean areWordsOnSameLine(Word currentWord, Word nextWord) { - boolean currentInNext = PolygonUtils.isPointInPolygonY( - currentWord.getPolygon().getCentroid(), - nextWord.getPolygon() - ); - boolean nextInCurrent = PolygonUtils.isPointInPolygonY( - nextWord.getPolygon().getCentroid(), - currentWord.getPolygon() - ); + boolean currentInNext = PolygonUtils + .isPointInPolygonY(currentWord.getPolygon().getCentroid(), nextWord.getPolygon()); + boolean nextInCurrent = PolygonUtils + .isPointInPolygonY(nextWord.getPolygon().getCentroid(), currentWord.getPolygon()); // We need to check both to eliminate any issues due to word order. return currentInNext || nextInCurrent; } @@ -79,7 +74,8 @@ protected List> toLines() { } current = null; if (!line.isEmpty()) { - line.sort((word1, word2) -> PolygonUtils.CompareOnX(word1.getPolygon(), word2.getPolygon())); + line + .sort((word1, word2) -> PolygonUtils.CompareOnX(word1.getPolygon(), word2.getPolygon())); lines.add(line); } } @@ -97,8 +93,10 @@ public List> getAllLines() { } public String toString() { - return this.getAllLines().stream() - .map(words -> words.stream().map(Word::getText).collect(Collectors.joining(" "))) - .collect(Collectors.joining(String.format("%n"))); + return this + .getAllLines() + .stream() + .map(words -> words.stream().map(Word::getText).collect(Collectors.joining(" "))) + .collect(Collectors.joining(String.format("%n"))); } } diff --git a/src/main/java/com/mindee/parsing/custom/CustomV1DocumentPredictionDeserializer.java b/src/main/java/com/mindee/parsing/custom/CustomV1DocumentPredictionDeserializer.java index 27fb4385d..2977466d4 100644 --- a/src/main/java/com/mindee/parsing/custom/CustomV1DocumentPredictionDeserializer.java +++ b/src/main/java/com/mindee/parsing/custom/CustomV1DocumentPredictionDeserializer.java @@ -38,14 +38,14 @@ public CustomV1Document deserialize( Map classificationFields = new HashMap<>(); Map fields = new HashMap<>(); - for (Iterator> subNode = node.fields(); subNode.hasNext(); ) { + for (Iterator> subNode = node.fields(); subNode.hasNext();) { Map.Entry pageNode = subNode.next(); if (pageNode.getValue().has("value")) { - classificationFields.put(pageNode.getKey(), - mapper.readerFor(new TypeReference() {}) - .readValue(pageNode.getValue())); + classificationFields + .put(pageNode.getKey(), mapper.readerFor(new TypeReference() { + }).readValue(pageNode.getValue())); } else { fields.put(pageNode.getKey(), mapper.readerFor(new TypeReference() { }).readValue(pageNode.getValue())); diff --git a/src/main/java/com/mindee/parsing/custom/ListField.java b/src/main/java/com/mindee/parsing/custom/ListField.java index 0c800e331..91cf00739 100644 --- a/src/main/java/com/mindee/parsing/custom/ListField.java +++ b/src/main/java/com/mindee/parsing/custom/ListField.java @@ -36,6 +36,7 @@ public ListField() { /** * Returns true if there are no values. + * * @return true if there are no values. */ public boolean isEmpty() { @@ -44,24 +45,25 @@ public boolean isEmpty() { /** * Get all the value contents. + * * @return all the values as a list of strings. */ public List getContentsList() { - return values.stream() - .map(ListFieldValue::getContent) - .collect(Collectors.toList()); + return values.stream().map(ListFieldValue::getContent).collect(Collectors.toList()); } /** * Get all the joined value contents. + * * @param separator the separator to use between values. * @return all the values as a single string. */ public String getContentsString(String separator) { - return String.format("%s", - values.stream() - .map(ListFieldValue::toString) - .collect(Collectors.joining(separator))); + return String + .format( + "%s", + values.stream().map(ListFieldValue::toString).collect(Collectors.joining(separator)) + ); } @Override diff --git a/src/main/java/com/mindee/parsing/custom/ListFieldValue.java b/src/main/java/com/mindee/parsing/custom/ListFieldValue.java index 57259d02c..833094e49 100644 --- a/src/main/java/com/mindee/parsing/custom/ListFieldValue.java +++ b/src/main/java/com/mindee/parsing/custom/ListFieldValue.java @@ -8,7 +8,6 @@ import lombok.EqualsAndHashCode; import lombok.Getter; - /** * A single value in a ListField. */ @@ -43,11 +42,7 @@ public class ListFieldValue { public ListFieldValue() { } - public ListFieldValue( - String content, - double confidence, - Polygon polygon - ) { + public ListFieldValue(String content, double confidence, Polygon polygon) { this.confidence = confidence; this.polygon = polygon; this.content = content; diff --git a/src/main/java/com/mindee/parsing/custom/lineitems/Line.java b/src/main/java/com/mindee/parsing/custom/lineitems/Line.java index ed41f2197..0ba2d41b3 100644 --- a/src/main/java/com/mindee/parsing/custom/lineitems/Line.java +++ b/src/main/java/com/mindee/parsing/custom/lineitems/Line.java @@ -11,7 +11,6 @@ import lombok.Getter; import lombok.Setter; - /** * Represent a single line. */ @@ -23,10 +22,7 @@ public class Line { @Setter private Bbox bbox; - public Line( - Integer rowNumber, - Map fields - ) { + public Line(Integer rowNumber, Map fields) { this.rowNumber = rowNumber; this.fields = fields; this.heightTolerance = 0.0; @@ -38,39 +34,39 @@ public Line(Integer rowNumber, Double heightTolerance) { this.heightTolerance = heightTolerance; } - public void addField( - String name, - ListFieldValue fieldValue - ) { + public void addField(String name, ListFieldValue fieldValue) { if (fields.containsKey(name)) { StringField existingField = fields.get(name); - Polygon mergedPolygon = PolygonUtils.combine( + Polygon mergedPolygon = PolygonUtils + .combine( BoundingBoxUtils.createBoundingBoxFrom(existingField.getPolygon()), BoundingBoxUtils.createBoundingBoxFrom(fieldValue.getPolygon()) - ); + ); String content = existingField.getValue() == null ? fieldValue.getContent() : String.join(" ", existingField.getValue(), fieldValue.getContent()); - fields.replace( + fields + .replace( name, new StringField( content, existingField.getConfidence() * fieldValue.getConfidence(), mergedPolygon ) - ); + ); } else { - fields.put( + fields + .put( name, new StringField( fieldValue.getContent(), fieldValue.getConfidence(), fieldValue.getPolygon() ) - ); + ); } } } diff --git a/src/main/java/com/mindee/parsing/custom/lineitems/LineGenerator.java b/src/main/java/com/mindee/parsing/custom/lineitems/LineGenerator.java index 998ca2424..1cad9a874 100644 --- a/src/main/java/com/mindee/parsing/custom/lineitems/LineGenerator.java +++ b/src/main/java/com/mindee/parsing/custom/lineitems/LineGenerator.java @@ -12,7 +12,6 @@ import java.util.Map; import org.apache.commons.math3.util.Precision; - /** * Get lines. */ @@ -21,10 +20,7 @@ public final class LineGenerator { private LineGenerator() { } - public static PreparedLines prepareLines( - Map fields, - List anchors - ) { + public static PreparedLines prepareLines(Map fields, List anchors) { Anchor bestAnchor = null; Collection lines = null; int lineCount = 0; @@ -33,10 +29,7 @@ public static PreparedLines prepareLines( if (anchorColumn == null) { throw new IllegalStateException("The field selected for the anchor was not found."); } - Collection currentLines = createLines( - anchorColumn.getValues(), - anchor.getTolerance() - ); + Collection currentLines = createLines(anchorColumn.getValues(), anchor.getTolerance()); if (currentLines.size() > lineCount) { bestAnchor = anchor; lines = currentLines; @@ -46,10 +39,7 @@ public static PreparedLines prepareLines( if (lines == null) { throw new IllegalStateException("Could not determine which anchor to use."); } - return new PreparedLines( - bestAnchor, - new ArrayList<>(lines) - ); + return new PreparedLines(bestAnchor, new ArrayList<>(lines)); } private static Collection createLines(List anchorValues, double tolerance) { @@ -64,15 +54,10 @@ private static Collection createLines(List anchorValues, d currentValue = anchorValue; Bbox currentFieldBbox = currentValue.getPolygon().getAsBbox(); if ( - Precision.equals( - currentLine.getBbox().getMinY(), - currentFieldBbox.getMinY(), - tolerance - ) + Precision.equals(currentLine.getBbox().getMinY(), currentFieldBbox.getMinY(), tolerance) ) { - currentLine.setBbox( - BboxUtils.merge(Arrays.asList(currentLine.getBbox(), currentFieldBbox)) - ); + currentLine + .setBbox(BboxUtils.merge(Arrays.asList(currentLine.getBbox(), currentFieldBbox))); } else { // when it is a new line table.put(lineNumber, currentLine); diff --git a/src/main/java/com/mindee/parsing/custom/lineitems/LineItems.java b/src/main/java/com/mindee/parsing/custom/lineitems/LineItems.java index 692f5cd11..5f9bcd269 100644 --- a/src/main/java/com/mindee/parsing/custom/lineitems/LineItems.java +++ b/src/main/java/com/mindee/parsing/custom/lineitems/LineItems.java @@ -3,7 +3,6 @@ import java.util.List; import lombok.Getter; - /** * Line items details. */ @@ -13,6 +12,7 @@ public class LineItems { /** * Default constructor. + * * @param rows */ public LineItems(List rows) { diff --git a/src/main/java/com/mindee/parsing/custom/lineitems/LineItemsGenerator.java b/src/main/java/com/mindee/parsing/custom/lineitems/LineItemsGenerator.java index 990f41a3d..93fabaf08 100644 --- a/src/main/java/com/mindee/parsing/custom/lineitems/LineItemsGenerator.java +++ b/src/main/java/com/mindee/parsing/custom/lineitems/LineItemsGenerator.java @@ -28,10 +28,11 @@ public static LineItems generate( Map fields, List anchors ) { - Map fieldsToTransformIntoLines = fields.entrySet() - .stream() - .filter(field -> fieldNames.contains(field.getKey())) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + Map fieldsToTransformIntoLines = fields + .entrySet() + .stream() + .filter(field -> fieldNames.contains(field.getKey())) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); return generate(fieldsToTransformIntoLines, anchors); } @@ -44,13 +45,12 @@ public static LineItems generate( Map fields, Anchor anchor ) { - Map fieldsToTransformIntoLines = fields.entrySet() - .stream() - .filter(field -> fieldNames.contains(field.getKey())) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - List anchors = new ArrayList<>( - Collections.singletonList(anchor) - ); + Map fieldsToTransformIntoLines = fields + .entrySet() + .stream() + .filter(field -> fieldNames.contains(field.getKey())) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + List anchors = new ArrayList<>(Collections.singletonList(anchor)); return generate(fieldsToTransformIntoLines, anchors); } @@ -58,14 +58,11 @@ private static LineItems generate( Map fieldsToTransformIntoLines, List anchors ) { - PreparedLines preparedLines = LineGenerator.prepareLines( - fieldsToTransformIntoLines, - anchors - ); + PreparedLines preparedLines = LineGenerator.prepareLines(fieldsToTransformIntoLines, anchors); List lines = populateLines( - fieldsToTransformIntoLines, - preparedLines.getLines(), - preparedLines.getAnchor().getTolerance() + fieldsToTransformIntoLines, + preparedLines.getLines(), + preparedLines.getAnchor().getTolerance() ); return new LineItems(lines); } @@ -83,7 +80,7 @@ private static List populateLines( MinMax minMaxY = listFieldValue.getPolygon().getMinMaxY(); if ( - Math.abs(minMaxY.getMax() - currentLine.getBbox().getMaxY()) <= tolerance + Math.abs(minMaxY.getMax() - currentLine.getBbox().getMaxY()) <= tolerance && Math.abs(minMaxY.getMin() - currentLine.getBbox().getMinY()) <= tolerance ) { currentLine.addField(field.getKey(), listFieldValue); diff --git a/src/main/java/com/mindee/parsing/generated/GeneratedFeature.java b/src/main/java/com/mindee/parsing/generated/GeneratedFeature.java index e6dd2e714..7c0d37f36 100644 --- a/src/main/java/com/mindee/parsing/generated/GeneratedFeature.java +++ b/src/main/java/com/mindee/parsing/generated/GeneratedFeature.java @@ -11,20 +11,20 @@ /** *

- * A generic feature which can represent any OTS Mindee return prediction. + * A generic feature which can represent any OTS Mindee return prediction. *

*

- * The Mindee API can return either lists or objects. - * Here we represent all features as a list, to simplify any code that interacts with this class. + * The Mindee API can return either lists or objects. + * Here we represent all features as a list, to simplify any code that interacts with this class. *

*

- * If you want, you can "cast" the raw hashmap into one of the standard Mindee fields: + * If you want, you can "cast" the raw hashmap into one of the standard Mindee fields: *

*
    - *
  • StringField - asStringField()
  • - *
  • AmountField - asAmountField()
  • - *
  • DateField - asDateField()
  • - *
  • ClassificationField - asClassificationField()
  • + *
  • StringField - asStringField()
  • + *
  • AmountField - asAmountField()
  • + *
  • DateField - asDateField()
  • + *
  • ClassificationField - asClassificationField()
  • *
* This will not work for any feature which is a list in the Mindee return. * @@ -35,6 +35,7 @@ public class GeneratedFeature extends ArrayList { /** * Whether the original feature is a list. + * * @param isList Whether the feature is a list. */ public GeneratedFeature(boolean isList) { @@ -44,6 +45,7 @@ public GeneratedFeature(boolean isList) { /** * Represent the feature as a standard {@link StringField}. * Only works for non-list features. + * * @return An instance of a {@link StringField}. */ public StringField asStringField() { @@ -55,6 +57,7 @@ public StringField asStringField() { /** * Represent the feature as a standard {@link BooleanField}. + * * @return An instance of a {@link BooleanField}. */ public BooleanField asBooleanField() { @@ -67,6 +70,7 @@ public BooleanField asBooleanField() { /** * Represent the feature as a standard {@link AmountField}. * Only works for non-list features. + * * @return An instance of a {@link AmountField}. */ public AmountField asAmountField() { @@ -79,6 +83,7 @@ public AmountField asAmountField() { /** * Represent the feature as a standard {@link DateField}. * Only works for non-list features. + * * @return An instance of a {@link DateField}. */ public DateField asDateField() { @@ -91,6 +96,7 @@ public DateField asDateField() { /** * Represent the feature as a standard {@link ClassificationField}. * Only works for non-list features. + * * @return An instance of a {@link ClassificationField}. */ public ClassificationField asClassificationField() { diff --git a/src/main/java/com/mindee/parsing/generated/GeneratedObject.java b/src/main/java/com/mindee/parsing/generated/GeneratedObject.java index 17700ac02..130669a87 100644 --- a/src/main/java/com/mindee/parsing/generated/GeneratedObject.java +++ b/src/main/java/com/mindee/parsing/generated/GeneratedObject.java @@ -18,6 +18,7 @@ public class GeneratedObject extends HashMap { /** * Represent the object as a standard {@link StringField}. + * * @return A {@link StringField} containing a string value. */ public StringField asStringField() { @@ -32,6 +33,7 @@ public StringField asStringField() { /** * Represent the object as a standard {@link AmountField}. + * * @return An {@link AmountField} containing a double value. */ public AmountField asAmountField() { @@ -39,35 +41,35 @@ public AmountField asAmountField() { Object rawValue = this.get("value"); if (rawValue instanceof Integer) { value = ((Integer) rawValue).doubleValue(); - } - else if (rawValue instanceof Double) { + } else if (rawValue instanceof Double) { value = (Double) rawValue; - } - else { + } else { throw new ClassCastException("Cannot cast " + rawValue + " to Double"); } - return new AmountField( - value, - this.getConfidence(), - this.getPolygon(), - this.getPageId() - ); + return new AmountField(value, this.getConfidence(), this.getPolygon(), this.getPageId()); } /** * Represent the object as a standard {@link BooleanField}. + * * @return A {@link BooleanField} containing a boolean value. */ public BooleanField asBooleanField() { Object rawValue = this.get("value"); if (rawValue instanceof Boolean) { - return new BooleanField((Boolean) rawValue, this.getConfidence(), this.getPolygon(), this.getPageId()); + return new BooleanField( + (Boolean) rawValue, + this.getConfidence(), + this.getPolygon(), + this.getPageId() + ); } throw new ClassCastException("Cannot cast " + rawValue + " to Boolean"); } /** * Represent the object as a standard {@link DateField}. + * * @return A {@link DateField} containing a date value. */ public DateField asDateField() { @@ -82,16 +84,16 @@ public DateField asDateField() { /** * Represent the object as a standard {@link ClassificationField}. + * * @return A {@link ClassificationField} containing a string value. */ public ClassificationField asClassificationField() { - return new ClassificationField( - (String) this.get("value") - ); + return new ClassificationField((String) this.get("value")); } /** * Get the polygon, if present. + * * @return A {@link Polygon}. */ public Polygon getPolygon() { @@ -100,6 +102,7 @@ public Polygon getPolygon() { /** * Get the specified key as a {@link Polygon} object. + * * @param key Key to retrieve the polygon from. * @return A {@link Polygon}. */ @@ -128,6 +131,7 @@ public Polygon getAsPolygon(String key) { /** * Get the page ID, if present. + * * @return A page ID, as an integer. */ public Integer getPageId() { @@ -136,6 +140,7 @@ public Integer getPageId() { /** * Get the confidence score, if present. + * * @return The confidence score, as a double. */ public Double getConfidence() { @@ -144,9 +149,10 @@ public Double getConfidence() { /** * Get the information on whether the date field was extracted. + * * @return A boolean representation of the field. */ - public Boolean getIsComputed(){ + public Boolean getIsComputed() { return (Boolean) this.get("is_computed"); } } diff --git a/src/main/java/com/mindee/parsing/generated/GeneratedV1PredictionDeserializer.java b/src/main/java/com/mindee/parsing/generated/GeneratedV1PredictionDeserializer.java index 79fb7799c..626f0d480 100644 --- a/src/main/java/com/mindee/parsing/generated/GeneratedV1PredictionDeserializer.java +++ b/src/main/java/com/mindee/parsing/generated/GeneratedV1PredictionDeserializer.java @@ -36,7 +36,7 @@ public GeneratedV1Document deserialize( ObjectNode rootNode = jsonParser.getCodec().readTree(jsonParser); Map features = new HashMap<>(); - for (Iterator> subNode = rootNode.fields(); subNode.hasNext(); ) { + for (Iterator> subNode = rootNode.fields(); subNode.hasNext();) { Map.Entry featureNode = subNode.next(); String featureName = featureNode.getKey(); @@ -45,17 +45,15 @@ public GeneratedV1Document deserialize( if (featureNode.getValue().isArray()) { feature = new GeneratedFeature(true); for (JsonNode item : featureNode.getValue()) { - GeneratedObject value = mapper - .readerFor(new TypeReference() {}) - .readValue(item); + GeneratedObject value = mapper.readerFor(new TypeReference() { + }).readValue(item); feature.add(value); } features.put(featureName, feature); } else { feature = new GeneratedFeature(false); - GeneratedObject value = mapper - .readerFor(new TypeReference() {}) - .readValue(featureNode.getValue()); + GeneratedObject value = mapper.readerFor(new TypeReference() { + }).readValue(featureNode.getValue()); feature.add(value); } features.put(featureName, feature); diff --git a/src/main/java/com/mindee/parsing/standard/AddressField.java b/src/main/java/com/mindee/parsing/standard/AddressField.java index 33da5570d..faeea5303 100644 --- a/src/main/java/com/mindee/parsing/standard/AddressField.java +++ b/src/main/java/com/mindee/parsing/standard/AddressField.java @@ -41,33 +41,19 @@ public final class AddressField extends StringField { private final String country; public AddressField( - @JsonProperty("value") - String value, - @JsonProperty("raw_value") - String rawValue, - @JsonProperty("street_number") - String streetNumber, - @JsonProperty("street_name") - String streetName, - @JsonProperty("po_box") - String poBox, - @JsonProperty("address_complement") - String addressComplement, - @JsonProperty("city") - String city, - @JsonProperty("postal_code") - String postalCode, - @JsonProperty("state") - String state, - @JsonProperty("country") - String country, - @JsonProperty("confidence") - Double confidence, - @JsonProperty("polygon") - @JsonDeserialize(using = PolygonDeserializer.class) - Polygon polygon, - @JsonProperty("page_id") - Integer pageId + @JsonProperty("value") String value, + @JsonProperty("raw_value") String rawValue, + @JsonProperty("street_number") String streetNumber, + @JsonProperty("street_name") String streetName, + @JsonProperty("po_box") String poBox, + @JsonProperty("address_complement") String addressComplement, + @JsonProperty("city") String city, + @JsonProperty("postal_code") String postalCode, + @JsonProperty("state") String state, + @JsonProperty("country") String country, + @JsonProperty("confidence") Double confidence, + @JsonProperty("polygon") @JsonDeserialize(using = PolygonDeserializer.class) Polygon polygon, + @JsonProperty("page_id") Integer pageId ) { super(value, rawValue, confidence, polygon, pageId); this.rawValue = rawValue; @@ -84,13 +70,7 @@ public AddressField( /** * Address field constructor only containing the value. */ - public AddressField( - String value, - Double confidence, - Polygon polygon - ) { - this(value, null, null, null, null, - null, null, null, null, null, - confidence, polygon, null); + public AddressField(String value, Double confidence, Polygon polygon) { + this(value, null, null, null, null, null, null, null, null, null, confidence, polygon, null); } } diff --git a/src/main/java/com/mindee/parsing/standard/AmountField.java b/src/main/java/com/mindee/parsing/standard/AmountField.java index ea8114524..8ec6af2db 100644 --- a/src/main/java/com/mindee/parsing/standard/AmountField.java +++ b/src/main/java/com/mindee/parsing/standard/AmountField.java @@ -22,15 +22,10 @@ public class AmountField extends BaseField { private Double value; public AmountField( - @JsonProperty("value") - Double value, - @JsonProperty("confidence") - Double confidence, - @JsonProperty("polygon") - @JsonDeserialize(using = PolygonDeserializer.class) - Polygon polygon, - @JsonProperty("page_id") - Integer pageId + @JsonProperty("value") Double value, + @JsonProperty("confidence") Double confidence, + @JsonProperty("polygon") @JsonDeserialize(using = PolygonDeserializer.class) Polygon polygon, + @JsonProperty("page_id") Integer pageId ) { super(confidence, polygon, pageId); this.value = value; diff --git a/src/main/java/com/mindee/parsing/standard/BaseField.java b/src/main/java/com/mindee/parsing/standard/BaseField.java index 371600e62..d085e40d0 100644 --- a/src/main/java/com/mindee/parsing/standard/BaseField.java +++ b/src/main/java/com/mindee/parsing/standard/BaseField.java @@ -45,13 +45,9 @@ public abstract class BaseField implements PositionData { * JSON constructor. */ protected BaseField( - @JsonProperty("confidence") - Double confidence, - @JsonProperty("polygon") - @JsonDeserialize(using = PolygonDeserializer.class) - Polygon polygon, - @JsonProperty("page_id") - Integer pageId + @JsonProperty("confidence") Double confidence, + @JsonProperty("polygon") @JsonDeserialize(using = PolygonDeserializer.class) Polygon polygon, + @JsonProperty("page_id") Integer pageId ) { this.confidence = confidence; this.polygon = polygon; diff --git a/src/main/java/com/mindee/parsing/standard/BooleanField.java b/src/main/java/com/mindee/parsing/standard/BooleanField.java index ebf650258..88a02c796 100644 --- a/src/main/java/com/mindee/parsing/standard/BooleanField.java +++ b/src/main/java/com/mindee/parsing/standard/BooleanField.java @@ -8,7 +8,6 @@ import com.mindee.parsing.SummaryHelper; import lombok.Getter; - /** * Represent a date. */ @@ -23,15 +22,10 @@ public class BooleanField extends BaseField { private Boolean value; public BooleanField( - @JsonProperty("value") - Boolean value, - @JsonProperty("confidence") - Double confidence, - @JsonProperty("polygon") - @JsonDeserialize(using = PolygonDeserializer.class) - Polygon polygon, - @JsonProperty("page_id") - Integer pageId + @JsonProperty("value") Boolean value, + @JsonProperty("confidence") Double confidence, + @JsonProperty("polygon") @JsonDeserialize(using = PolygonDeserializer.class) Polygon polygon, + @JsonProperty("page_id") Integer pageId ) { super(confidence, polygon, pageId); this.value = value; diff --git a/src/main/java/com/mindee/parsing/standard/CompanyRegistrationField.java b/src/main/java/com/mindee/parsing/standard/CompanyRegistrationField.java index 309cafbff..5596b4e76 100644 --- a/src/main/java/com/mindee/parsing/standard/CompanyRegistrationField.java +++ b/src/main/java/com/mindee/parsing/standard/CompanyRegistrationField.java @@ -25,20 +25,15 @@ public final class CompanyRegistrationField extends BaseField implements LineIte private final String type; public CompanyRegistrationField( - @JsonProperty("type") - String type, - @JsonProperty("value") - String value + @JsonProperty("type") String type, + @JsonProperty("value") String value ) { this.type = type; this.value = value; } public boolean isEmpty() { - return ( - (value == null || value.isEmpty()) - && (type == null || type.isEmpty()) - ); + return ((value == null || value.isEmpty()) && (type == null || type.isEmpty())); } /** diff --git a/src/main/java/com/mindee/parsing/standard/DateField.java b/src/main/java/com/mindee/parsing/standard/DateField.java index e11fe90b0..0f2aa7b98 100644 --- a/src/main/java/com/mindee/parsing/standard/DateField.java +++ b/src/main/java/com/mindee/parsing/standard/DateField.java @@ -28,17 +28,11 @@ public class DateField extends BaseField { private Boolean isComputed; public DateField( - @JsonProperty("value") - LocalDate value, - @JsonProperty("confidence") - Double confidence, - @JsonProperty("polygon") - @JsonDeserialize(using = PolygonDeserializer.class) - Polygon polygon, - @JsonProperty("page_id") - Integer pageId, - @JsonProperty("is_computed") - Boolean isComputed + @JsonProperty("value") LocalDate value, + @JsonProperty("confidence") Double confidence, + @JsonProperty("polygon") @JsonDeserialize(using = PolygonDeserializer.class) Polygon polygon, + @JsonProperty("page_id") Integer pageId, + @JsonProperty("is_computed") Boolean isComputed ) { super(confidence, polygon, pageId); this.value = value; diff --git a/src/main/java/com/mindee/parsing/standard/LocaleField.java b/src/main/java/com/mindee/parsing/standard/LocaleField.java index 8a284b4ad..47fe88cfa 100644 --- a/src/main/java/com/mindee/parsing/standard/LocaleField.java +++ b/src/main/java/com/mindee/parsing/standard/LocaleField.java @@ -1,6 +1,5 @@ package com.mindee.parsing.standard; - import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; @@ -33,14 +32,10 @@ public class LocaleField extends BaseField { private final String currency; public LocaleField( - @JsonProperty("value") - String value, - @JsonProperty("language") - String language, - @JsonProperty("country") - String country, - @JsonProperty("currency") - String currency + @JsonProperty("value") String value, + @JsonProperty("language") String language, + @JsonProperty("country") String country, + @JsonProperty("currency") String currency ) { this.value = value; this.language = language; @@ -53,12 +48,10 @@ public LocaleField( } public boolean isEmpty() { - return ( - (this.value == null || this.value.isEmpty()) - && (this.country == null || this.country.isEmpty()) - && (this.language == null || this.language.isEmpty()) - && (this.currency == null || this.currency.isEmpty()) - ); + return ((this.value == null || this.value.isEmpty()) + && (this.country == null || this.country.isEmpty()) + && (this.language == null || this.language.isEmpty()) + && (this.currency == null || this.currency.isEmpty())); } @Override diff --git a/src/main/java/com/mindee/parsing/standard/PaymentDetailsField.java b/src/main/java/com/mindee/parsing/standard/PaymentDetailsField.java index 2b314c0b0..935a02d53 100644 --- a/src/main/java/com/mindee/parsing/standard/PaymentDetailsField.java +++ b/src/main/java/com/mindee/parsing/standard/PaymentDetailsField.java @@ -32,14 +32,10 @@ public class PaymentDetailsField extends BaseField { private final String swift; public PaymentDetailsField( - @JsonProperty("account_number") - String accountNumber, - @JsonProperty("iban") - String iban, - @JsonProperty("routing_number") - String routingNumber, - @JsonProperty("swift") - String swift + @JsonProperty("account_number") String accountNumber, + @JsonProperty("iban") String iban, + @JsonProperty("routing_number") String routingNumber, + @JsonProperty("swift") String swift ) { this.accountNumber = accountNumber; this.iban = iban; @@ -48,12 +44,10 @@ public PaymentDetailsField( } public boolean isEmpty() { - return ( - (accountNumber == null || accountNumber.isEmpty()) - && (iban == null || iban.isEmpty()) - && (routingNumber == null || routingNumber.isEmpty()) - && (swift == null || swift.isEmpty()) - ); + return ((accountNumber == null || accountNumber.isEmpty()) + && (iban == null || iban.isEmpty()) + && (routingNumber == null || routingNumber.isEmpty()) + && (swift == null || swift.isEmpty())); } @Override diff --git a/src/main/java/com/mindee/parsing/standard/PositionData.java b/src/main/java/com/mindee/parsing/standard/PositionData.java index 944f011cc..347b73090 100644 --- a/src/main/java/com/mindee/parsing/standard/PositionData.java +++ b/src/main/java/com/mindee/parsing/standard/PositionData.java @@ -7,5 +7,6 @@ */ public interface PositionData { Polygon getBoundingBox(); + Polygon getPolygon(); } diff --git a/src/main/java/com/mindee/parsing/standard/StringField.java b/src/main/java/com/mindee/parsing/standard/StringField.java index 3f3707a68..67c869125 100644 --- a/src/main/java/com/mindee/parsing/standard/StringField.java +++ b/src/main/java/com/mindee/parsing/standard/StringField.java @@ -25,26 +25,16 @@ public class StringField extends BaseField { */ private final String rawValue; - public StringField( - String value, - Double confidence, - Polygon polygon - ) { + public StringField(String value, Double confidence, Polygon polygon) { this(value, null, confidence, polygon, null); } public StringField( - @JsonProperty("value") - String value, - @JsonProperty("raw_value") - String rawValue, - @JsonProperty("confidence") - Double confidence, - @JsonProperty("polygon") - @JsonDeserialize(using = PolygonDeserializer.class) - Polygon polygon, - @JsonProperty("page_id") - Integer pageId + @JsonProperty("value") String value, + @JsonProperty("raw_value") String rawValue, + @JsonProperty("confidence") Double confidence, + @JsonProperty("polygon") @JsonDeserialize(using = PolygonDeserializer.class) Polygon polygon, + @JsonProperty("page_id") Integer pageId ) { super(confidence, polygon, pageId); this.value = value; diff --git a/src/main/java/com/mindee/parsing/standard/TaxField.java b/src/main/java/com/mindee/parsing/standard/TaxField.java index ee4ac8026..50a961fb9 100644 --- a/src/main/java/com/mindee/parsing/standard/TaxField.java +++ b/src/main/java/com/mindee/parsing/standard/TaxField.java @@ -7,7 +7,6 @@ import java.util.Map; import lombok.Getter; - /** * Represent a tax line. */ @@ -36,14 +35,10 @@ public class TaxField extends BaseField implements LineItemField { private final Double base; public TaxField( - @JsonProperty("value") - Double value, - @JsonProperty("code") - String code, - @JsonProperty("rate") - Double rate, - @JsonProperty("base") - Double base + @JsonProperty("value") Double value, + @JsonProperty("code") String code, + @JsonProperty("rate") Double rate, + @JsonProperty("base") Double base ) { this.value = value; this.code = code; @@ -52,12 +47,7 @@ public TaxField( } public boolean isEmpty() { - return ( - value == null - && (code == null || code.isEmpty()) - && rate == null - && base == null - ); + return (value == null && (code == null || code.isEmpty()) && rate == null && base == null); } /** diff --git a/src/main/java/com/mindee/parsing/standard/Taxes.java b/src/main/java/com/mindee/parsing/standard/Taxes.java index c9dcb8934..49cdce126 100644 --- a/src/main/java/com/mindee/parsing/standard/Taxes.java +++ b/src/main/java/com/mindee/parsing/standard/Taxes.java @@ -15,7 +15,7 @@ public String toString() { if (this.isEmpty()) { return ""; } - int[] columnSizes = new int[] {15, 8, 10, 15}; + int[] columnSizes = new int[] { 15, 8, 10, 15 }; return String.format("%n%s%n", SummaryHelper.lineSeparator(columnSizes, "-")) + " | Base | Code | Rate (%) | Amount |" + String.format("%n%s%n ", SummaryHelper.lineSeparator(columnSizes, "=")) diff --git a/src/main/java/com/mindee/parsing/standard/TaxesDeserializer.java b/src/main/java/com/mindee/parsing/standard/TaxesDeserializer.java index 8aafdc819..a98e6a720 100644 --- a/src/main/java/com/mindee/parsing/standard/TaxesDeserializer.java +++ b/src/main/java/com/mindee/parsing/standard/TaxesDeserializer.java @@ -29,9 +29,8 @@ public Taxes deserialize(JsonParser jsonParser, DeserializationContext ctx) thro Taxes taxes = new Taxes(); ArrayNode arrayNode = jsonParser.getCodec().readTree(jsonParser); for (JsonNode item : arrayNode) { - TaxField line = mapper - .readerFor(new TypeReference() {}) - .readValue(item); + TaxField line = mapper.readerFor(new TypeReference() { + }).readValue(item); taxes.add(line); } return taxes; diff --git a/src/main/java/com/mindee/parsing/v2/DataSchemaActiveOptions.java b/src/main/java/com/mindee/parsing/v2/DataSchemaActiveOptions.java index 66e5a6599..5d14c28f2 100644 --- a/src/main/java/com/mindee/parsing/v2/DataSchemaActiveOptions.java +++ b/src/main/java/com/mindee/parsing/v2/DataSchemaActiveOptions.java @@ -28,9 +28,9 @@ public boolean getReplace() { public String toString() { StringJoiner joiner = new StringJoiner("\n"); return joiner - .add("Data Schema") - .add("-----------") - .add(":Replace: " + formatForDisplay(replace, 5)) - .toString(); + .add("Data Schema") + .add("-----------") + .add(":Replace: " + formatForDisplay(replace, 5)) + .toString(); } } diff --git a/src/main/java/com/mindee/parsing/v2/Inference.java b/src/main/java/com/mindee/parsing/v2/Inference.java index e8d53f313..763515faf 100644 --- a/src/main/java/com/mindee/parsing/v2/Inference.java +++ b/src/main/java/com/mindee/parsing/v2/Inference.java @@ -51,15 +51,15 @@ public class Inference { public String toString() { StringJoiner joiner = new StringJoiner("\n"); joiner - .add("Inference") - .add("#########") - .add(model.toString()) - .add("") - .add(file.toString()) - .add("") - .add(activeOptions.toString()) - .add("") - .add(result != null ? result.toString() : ""); + .add("Inference") + .add("#########") + .add(model.toString()) + .add("") + .add(file.toString()) + .add("") + .add(activeOptions.toString()) + .add("") + .add(result != null ? result.toString() : ""); return joiner.toString().trim() + "\n"; } } diff --git a/src/main/java/com/mindee/parsing/v2/InferenceActiveOptions.java b/src/main/java/com/mindee/parsing/v2/InferenceActiveOptions.java index 0a4b1d6d9..96fbc27b4 100644 --- a/src/main/java/com/mindee/parsing/v2/InferenceActiveOptions.java +++ b/src/main/java/com/mindee/parsing/v2/InferenceActiveOptions.java @@ -31,7 +31,7 @@ public final class InferenceActiveOptions { private boolean textContext; /** - * Data schema options provided for the inference. + * Data schema options provided for the inference. */ @Getter @JsonProperty("data_schema") @@ -68,21 +68,23 @@ public boolean getConfidence() { /** * Whether the text context feature was activated. */ - public boolean getTextContext() { return textContext; } + public boolean getTextContext() { + return textContext; + } @Override public String toString() { StringJoiner joiner = new StringJoiner("\n"); return joiner - .add("Active Options") - .add("==============") - .add(":Raw Text: " + formatForDisplay(rawText, 5)) - .add(":Polygon: " + formatForDisplay(polygon, 5)) - .add(":Confidence: " + formatForDisplay(confidence, 5)) - .add(":RAG: " + formatForDisplay(rag, 5)) - .add(":Text Context: " + formatForDisplay(textContext, 5)) - .add("") - .add(dataSchema.toString()) - .toString(); + .add("Active Options") + .add("==============") + .add(":Raw Text: " + formatForDisplay(rawText, 5)) + .add(":Polygon: " + formatForDisplay(polygon, 5)) + .add(":Confidence: " + formatForDisplay(confidence, 5)) + .add(":RAG: " + formatForDisplay(rag, 5)) + .add(":Text Context: " + formatForDisplay(textContext, 5)) + .add("") + .add(dataSchema.toString()) + .toString(); } } diff --git a/src/main/java/com/mindee/parsing/v2/InferenceFile.java b/src/main/java/com/mindee/parsing/v2/InferenceFile.java index 67e0b3772..4276b969a 100644 --- a/src/main/java/com/mindee/parsing/v2/InferenceFile.java +++ b/src/main/java/com/mindee/parsing/v2/InferenceFile.java @@ -41,17 +41,16 @@ public class InferenceFile { @JsonProperty("mime_type") private String mimeType; - public String toString() { StringJoiner joiner = new StringJoiner("\n"); joiner - .add("File") - .add("====") - .add(":Name: " + name) - .add(":Alias:" + (alias != null ? " " + alias : "")) - .add(":Page Count: " + pageCount) - .add(":MIME Type: " + mimeType); + .add("File") + .add("====") + .add(":Name: " + name) + .add(":Alias:" + (alias != null ? " " + alias : "")) + .add(":Page Count: " + pageCount) + .add(":MIME Type: " + mimeType); return joiner.toString(); } } diff --git a/src/main/java/com/mindee/parsing/v2/InferenceModel.java b/src/main/java/com/mindee/parsing/v2/InferenceModel.java index 6440df5f2..bee0eb258 100644 --- a/src/main/java/com/mindee/parsing/v2/InferenceModel.java +++ b/src/main/java/com/mindee/parsing/v2/InferenceModel.java @@ -26,10 +26,6 @@ public class InferenceModel { public String toString() { StringJoiner joiner = new StringJoiner("\n"); - return joiner - .add("Model") - .add("=====") - .add(":ID: " + id) - .toString(); + return joiner.add("Model").add("=====").add(":ID: " + id).toString(); } } diff --git a/src/main/java/com/mindee/parsing/v2/InferenceResult.java b/src/main/java/com/mindee/parsing/v2/InferenceResult.java index 185cc4782..7a328bf43 100644 --- a/src/main/java/com/mindee/parsing/v2/InferenceResult.java +++ b/src/main/java/com/mindee/parsing/v2/InferenceResult.java @@ -40,8 +40,7 @@ public final class InferenceResult { @Override public String toString() { StringJoiner joiner = new StringJoiner("\n"); - joiner.add("Fields") - .add("======"); + joiner.add("Fields").add("======"); joiner.add(fields.toString()); return joiner.toString(); diff --git a/src/main/java/com/mindee/parsing/v2/JobResponse.java b/src/main/java/com/mindee/parsing/v2/JobResponse.java index dcad0c80a..0753d1cd3 100644 --- a/src/main/java/com/mindee/parsing/v2/JobResponse.java +++ b/src/main/java/com/mindee/parsing/v2/JobResponse.java @@ -1,6 +1,5 @@ package com.mindee.parsing.v2; - import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; diff --git a/src/main/java/com/mindee/parsing/v2/field/DynamicField.java b/src/main/java/com/mindee/parsing/v2/field/DynamicField.java index b7b5001a8..5ca96bc81 100644 --- a/src/main/java/com/mindee/parsing/v2/field/DynamicField.java +++ b/src/main/java/com/mindee/parsing/v2/field/DynamicField.java @@ -76,7 +76,8 @@ public ObjectField getObjectField() throws IllegalStateException { * * @param type the class representing the desired field type * @param the type of field to return - * @throws IllegalArgumentException if the requested type is not SimpleField, ListField, or ObjectField + * @throws IllegalArgumentException if the requested type is not: + * SimpleField, ListField, or ObjectField * @throws IllegalStateException if the field's internal type does not match the requested type */ public T getField(Class type) throws IllegalArgumentException { @@ -89,21 +90,26 @@ public T getField(Class type) throws IllegalArgumentExc if (type == ObjectField.class) { return (T) this.getObjectField(); } - throw new IllegalArgumentException( - "Cannot cast to " + type.getSimpleName() - ); + throw new IllegalArgumentException("Cannot cast to " + type.getSimpleName()); } @Override public String toString() { - if (simpleField != null) return simpleField.toString(); - if (listField != null) return listField.toString(); - if (objectField != null) return objectField.toString(); + if (simpleField != null) + return simpleField.toString(); + if (listField != null) + return listField.toString(); + if (objectField != null) + return objectField.toString(); return ""; } /** * Possible field kinds. */ - public enum FieldType { SIMPLE_FIELD, OBJECT_FIELD, LIST_FIELD } + public enum FieldType { + SIMPLE_FIELD, + OBJECT_FIELD, + LIST_FIELD, + } } diff --git a/src/main/java/com/mindee/parsing/v2/field/FieldConfidence.java b/src/main/java/com/mindee/parsing/v2/field/FieldConfidence.java index 01daa01fa..f0e6d7beb 100644 --- a/src/main/java/com/mindee/parsing/v2/field/FieldConfidence.java +++ b/src/main/java/com/mindee/parsing/v2/field/FieldConfidence.java @@ -42,7 +42,7 @@ public static FieldConfidence fromJson(String value) { * * @param other the other FieldConfidence level to compare against * @return true if the current FieldConfidence level is greater than the specified level, - * false otherwise + * false otherwise */ public boolean greaterThan(FieldConfidence other) { return this.compareTo(other) > 0; @@ -53,8 +53,8 @@ public boolean greaterThan(FieldConfidence other) { * to determine if the current level is greater than or equal to the specified level. * * @param other the other FieldConfidence level to compare against - * @return true if the current FieldConfidence level is greater than or equal to the specified level, - * false otherwise + * @return true if the current FieldConfidence level is greater than or equal to the specified + * level, false otherwise */ public boolean greaterThanOrEqual(FieldConfidence other) { return this.compareTo(other) >= 0; @@ -66,7 +66,7 @@ public boolean greaterThanOrEqual(FieldConfidence other) { * * @param other the other FieldConfidence level to compare against * @return true if the current FieldConfidence level is less than the specified level, - * false otherwise + * false otherwise */ public boolean lessThan(FieldConfidence other) { return this.compareTo(other) < 0; @@ -78,7 +78,7 @@ public boolean lessThan(FieldConfidence other) { * * @param other the other FieldConfidence level to compare against * @return true if the current FieldConfidence level is less than or equal to the specified level, - * false otherwise + * false otherwise */ public boolean lessThanOrEqual(FieldConfidence other) { return this.compareTo(other) <= 0; diff --git a/src/main/java/com/mindee/parsing/v2/field/InferenceFields.java b/src/main/java/com/mindee/parsing/v2/field/InferenceFields.java index cd9d871f2..30b294c85 100644 --- a/src/main/java/com/mindee/parsing/v2/field/InferenceFields.java +++ b/src/main/java/com/mindee/parsing/v2/field/InferenceFields.java @@ -62,11 +62,12 @@ public String toString(int indent) { } else if (fieldInstance.getType() == DynamicField.FieldType.OBJECT_FIELD) { strBuilder.append(fieldInstance.getObjectField()); } else if (fieldInstance.getType() == DynamicField.FieldType.SIMPLE_FIELD) { - strBuilder.append( + strBuilder + .append( fieldInstance.getSimpleField().getValue() != null ? fieldInstance.getSimpleField().toString() : "" - ); + ); } joiner.add(strBuilder); diff --git a/src/main/java/com/mindee/parsing/v2/field/ListField.java b/src/main/java/com/mindee/parsing/v2/field/ListField.java index 56e52dd57..c64d92f76 100644 --- a/src/main/java/com/mindee/parsing/v2/field/ListField.java +++ b/src/main/java/com/mindee/parsing/v2/field/ListField.java @@ -30,7 +30,8 @@ public final class ListField extends BaseField { * Retrieves the {@code items} as {@code SimpleField} objects. * * @return a list of {@code SimpleField} objects - * @throws IllegalStateException if any dynamic field in the list is not of type {@code SIMPLE_FIELD} + * @throws IllegalStateException if any dynamic field in the list is not of type + * {@code SIMPLE_FIELD} */ public List getSimpleItems() throws IllegalStateException { List simpleItems = new ArrayList<>(); @@ -46,7 +47,8 @@ public List getSimpleItems() throws IllegalStateException { * Retrieves the {@code items} as {@code ObjectField} objects. * * @return a list of {@code ObjectField} objects - * @throws IllegalStateException if any dynamic field in the list is not of type {@code OBJECT_FIELD} + * @throws IllegalStateException if any dynamic field in the list is not of type + * {@code OBJECT_FIELD} */ public List getObjectItems() throws IllegalStateException { List objectItems = new ArrayList<>(); diff --git a/src/main/java/com/mindee/parsing/v2/field/ObjectField.java b/src/main/java/com/mindee/parsing/v2/field/ObjectField.java index b059e452f..8798d6b28 100644 --- a/src/main/java/com/mindee/parsing/v2/field/ObjectField.java +++ b/src/main/java/com/mindee/parsing/v2/field/ObjectField.java @@ -29,7 +29,7 @@ public class ObjectField extends BaseField { * {@code SimpleField} objects, keyed by their field names. * * @return a {@link LinkedHashMap} containing the field names as keys and their corresponding - * {@code SimpleField} instances as values + * {@code SimpleField} instances as values * @throws IllegalStateException if any field is not of type {@code SIMPLE_FIELD} */ public LinkedHashMap getSimpleFields() throws IllegalStateException { diff --git a/src/main/java/com/mindee/parsing/v2/field/SimpleField.java b/src/main/java/com/mindee/parsing/v2/field/SimpleField.java index fec866a61..0273609ff 100644 --- a/src/main/java/com/mindee/parsing/v2/field/SimpleField.java +++ b/src/main/java/com/mindee/parsing/v2/field/SimpleField.java @@ -59,7 +59,8 @@ public Boolean getBooleanValue() throws ClassCastException { @Override public String toString() { - if (value == null) return ""; + if (value == null) + return ""; if (value.getClass().equals(Boolean.class)) { return ((Boolean) value) ? "True" : "False"; } diff --git a/src/main/java/com/mindee/parsing/v2/field/SimpleFieldDeserializer.java b/src/main/java/com/mindee/parsing/v2/field/SimpleFieldDeserializer.java index 8abe56a71..9d2ae2db2 100644 --- a/src/main/java/com/mindee/parsing/v2/field/SimpleFieldDeserializer.java +++ b/src/main/java/com/mindee/parsing/v2/field/SimpleFieldDeserializer.java @@ -38,9 +38,7 @@ public SimpleField deserialize(JsonParser jp, DeserializationContext ctxt) throw } } - FieldConfidence confidence = codec.treeToValue( - root.get("confidence"), FieldConfidence.class - ); + FieldConfidence confidence = codec.treeToValue(root.get("confidence"), FieldConfidence.class); List locations = null; JsonNode locationsNode = root.get("locations"); diff --git a/src/main/java/com/mindee/pdf/PDFUtils.java b/src/main/java/com/mindee/pdf/PDFUtils.java index ca3536aa6..a0a4cb1fe 100644 --- a/src/main/java/com/mindee/pdf/PDFUtils.java +++ b/src/main/java/com/mindee/pdf/PDFUtils.java @@ -65,14 +65,17 @@ private static PDPage clonePage(PDPage page) { } private static byte[] createPdfFromExistingPdf( - PDDocument document, List pageNumbers, + PDDocument document, + List pageNumbers, boolean closeOriginal ) throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PDDocument newDocument = new PDDocument(); int pageCount = document.getNumberOfPages(); - pageNumbers.stream().filter(i -> i < pageCount) - .forEach(i -> newDocument.addPage(clonePage(document.getPage(i)))); + pageNumbers + .stream() + .filter(i -> i < pageCount) + .forEach(i -> newDocument.addPage(clonePage(document.getPage(i)))); newDocument.save(outputStream); newDocument.close(); @@ -88,7 +91,7 @@ private static byte[] createPdfFromExistingPdf( /** * Merge specified PDF pages together. * - * @param file The PDF file. + * @param file The PDF file. * @param pageNumbers Lit of page numbers to merge together. */ public static byte[] mergePdfPages(File file, List pageNumbers) throws IOException { @@ -96,20 +99,21 @@ public static byte[] mergePdfPages(File file, List pageNumbers) throws return createPdfFromExistingPdf(document, pageNumbers, true); } - public static byte[] mergePdfPages(PDDocument document, List pageNumbers) - throws IOException { + public static byte[] mergePdfPages( + PDDocument document, + List pageNumbers + ) throws IOException { return mergePdfPages(document, pageNumbers, true); } - public static byte[] mergePdfPages( - PDDocument document, List pageNumbers, + PDDocument document, + List pageNumbers, boolean closeOriginal ) throws IOException { return createPdfFromExistingPdf(document, pageNumbers, closeOriginal); } - public static boolean isPdfEmpty(File file) throws IOException { return checkIfPdfIsEmpty(Loader.loadPDF(file)); } @@ -124,8 +128,10 @@ private static boolean checkIfPdfIsEmpty(PDDocument document) throws IOException Iterable xObjects = resources.getXObjectNames(); Iterable fonts = resources.getFontNames(); - if (xObjects.spliterator().getExactSizeIfKnown() != 0 - || fonts.spliterator().getExactSizeIfKnown() != 0) { + if ( + xObjects.spliterator().getExactSizeIfKnown() != 0 + || fonts.spliterator().getExactSizeIfKnown() != 0 + ) { isEmpty = false; break; } @@ -168,9 +174,10 @@ public static List pdfToImages(LocalInputSource source) throws IOE /** * Render a single page of a PDF as an image. * Main use case is for processing PDFs with hundreds of pages. - * If you need to only render some pages from the PDF, use mergePdfPages and then pdfToImages. + * If you need to only render some pages from the PDF, use mergePdfPages and then + * pdfToImages. * - * @param filePath The path to the PDF file. + * @param filePath The path to the PDF file. * @param pageNumber The page number to render, first page is 1. * @return The page as an image. */ @@ -184,7 +191,7 @@ public static PdfPageImage pdfPageToImage(String filePath, int pageNumber) throw * If you need to only render some pages from the PDF, use mergePdfPages and * then pdfToImages. * - * @param source The PDF file. + * @param source The PDF file. * @param pageNumber The page number to render, first page is 1. * @return The page as an image. */ @@ -201,7 +208,8 @@ public static PdfPageImage pdfPageToImage( } private static BufferedImage pdfPageToImageBuffer( - int index, PDDocument document, + int index, + PDDocument document, PDFRenderer pdfRenderer ) throws IOException { PDRectangle bbox = document.getPage(index).getBBox(); @@ -223,10 +231,11 @@ public static byte[] documentToBytes(PDDocument document) throws IOException { return outputStream.toByteArray(); } - public static void extractAndAddText( - PDDocument inputDoc, PDPageContentStream contentStream, - int pageIndex, boolean disableSourceText + PDDocument inputDoc, + PDPageContentStream contentStream, + int pageIndex, + boolean disableSourceText ) throws IOException { if (disableSourceText) { return; @@ -288,7 +297,8 @@ private static Color convertToAwtColor(PDColor pdColor) { } public static void addImageToPage( - PDPageContentStream contentStream, PDImageXObject pdImage, + PDPageContentStream contentStream, + PDImageXObject pdImage, PDRectangle pageSize ) throws IOException { contentStream.drawImage(pdImage, 0, 0, pageSize.getWidth(), pageSize.getHeight()); diff --git a/src/main/java/com/mindee/pdf/PdfBoxApi.java b/src/main/java/com/mindee/pdf/PdfBoxApi.java index 8e9749bc5..aa6fb3798 100644 --- a/src/main/java/com/mindee/pdf/PdfBoxApi.java +++ b/src/main/java/com/mindee/pdf/PdfBoxApi.java @@ -37,9 +37,10 @@ public SplitPdf split(SplitQuery splitQuery) throws IOException { List pageRange = getPageRanges(splitQuery.getPageOptions(), totalOriginalPages); - pageRange.stream() - .filter(i -> i < totalOriginalPages) - .forEach(i -> splitDocument.addPage(originalDocument.getPage(i))); + pageRange + .stream() + .filter(i -> i < totalOriginalPages) + .forEach(i -> splitDocument.addPage(originalDocument.getPage(i))); try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { splitDocument.save(outputStream); @@ -52,12 +53,13 @@ public SplitPdf split(SplitQuery splitQuery) throws IOException { private List getPageRanges(PageOptions pageOptions, Integer numberOfPages) { - Set pages = Optional.ofNullable(pageOptions.getPageIndexes()) - .map(Collection::stream) - .orElseGet(Stream::empty) - .filter(x -> x > (numberOfPages) * (-1) && x <= (numberOfPages - 1)) - .map(x -> (numberOfPages + x) % numberOfPages) - .collect(Collectors.toSet()); + Set pages = Optional + .ofNullable(pageOptions.getPageIndexes()) + .map(Collection::stream) + .orElseGet(Stream::empty) + .filter(x -> x > (numberOfPages) * (-1) && x <= (numberOfPages - 1)) + .map(x -> (numberOfPages + x) % numberOfPages) + .collect(Collectors.toSet()); List allPages = IntStream.range(0, numberOfPages).boxed().collect(Collectors.toList()); switch (pageOptions.getOperation()) { diff --git a/src/main/java/com/mindee/pdf/PdfCompressor.java b/src/main/java/com/mindee/pdf/PdfCompressor.java index a73244eb0..dee8ea642 100644 --- a/src/main/java/com/mindee/pdf/PdfCompressor.java +++ b/src/main/java/com/mindee/pdf/PdfCompressor.java @@ -20,10 +20,11 @@ */ public class PdfCompressor { public static byte[] compressPdf( - byte[] pdfData, Integer imageQuality, - Boolean forceSourceTextCompression, Boolean disableSourceText - ) - throws IOException { + byte[] pdfData, + Integer imageQuality, + Boolean forceSourceTextCompression, + Boolean disableSourceText + ) throws IOException { if (!isPdf(pdfData)) { return pdfData; } @@ -35,12 +36,13 @@ public static byte[] compressPdf( disableSourceText = true; } if (!forceSourceTextCompression && hasSourceText(pdfData)) { - System.out.println( - "MINDEE WARNING: Found text inside of the provided PDF file. Compression operation aborted."); + System.out + .println( + "MINDEE WARNING: Found text inside of the provided PDF file. Compression operation aborted." + ); return pdfData; } - try (PDDocument inputDoc = Loader.loadPDF(pdfData); - PDDocument outputDoc = new PDDocument()) { + try (PDDocument inputDoc = Loader.loadPDF(pdfData); PDDocument outputDoc = new PDDocument()) { PDFRenderer pdfRenderer = new PDFRenderer(inputDoc); @@ -48,9 +50,14 @@ public static byte[] compressPdf( PDPage originalPage = inputDoc.getPage(pageIndex); PDRectangle originalPageSize = originalPage.getMediaBox(); - processPage(inputDoc, pageIndex, outputDoc, - pdfRenderer.renderImageWithDPI(pageIndex, 72 * (imageQuality / 100f), ImageType.ARGB), - (imageQuality / 100f), originalPageSize, disableSourceText + processPage( + inputDoc, + pageIndex, + outputDoc, + pdfRenderer.renderImageWithDPI(pageIndex, 72 * (imageQuality / 100f), ImageType.ARGB), + (imageQuality / 100f), + originalPageSize, + disableSourceText ); } @@ -61,7 +68,8 @@ public static byte[] compressPdf( } public static byte[] compressPdf( - byte[] pdfData, Integer imageQuality, + byte[] pdfData, + Integer imageQuality, Boolean forceSourceTextCompression ) throws IOException { return compressPdf(pdfData, imageQuality, forceSourceTextCompression, true); @@ -76,12 +84,14 @@ public static byte[] compressPdf(byte[] pdfData) throws IOException { } private static void processPage( - PDDocument originalDocument, Integer pageIndex, - PDDocument outputDoc, BufferedImage image, + PDDocument originalDocument, + Integer pageIndex, + PDDocument outputDoc, + BufferedImage image, Float imageQuality, - PDRectangle originalPageSize, Boolean disableSourceText - ) - throws IOException { + PDRectangle originalPageSize, + Boolean disableSourceText + ) throws IOException { PDPage newPage = new PDPage(originalPageSize); outputDoc.addPage(newPage); diff --git a/src/main/java/com/mindee/pdf/PdfPageImage.java b/src/main/java/com/mindee/pdf/PdfPageImage.java index aba11cf10..5ef51de5b 100644 --- a/src/main/java/com/mindee/pdf/PdfPageImage.java +++ b/src/main/java/com/mindee/pdf/PdfPageImage.java @@ -22,7 +22,12 @@ public class PdfPageImage { private final String saveFormat; private final String originalFilename; - public PdfPageImage(BufferedImage image, int originalIndex, String originalFilename, String saveFormat) { + public PdfPageImage( + BufferedImage image, + int originalIndex, + String originalFilename, + String saveFormat + ) { this.image = image; this.originalIndex = originalIndex; this.saveFormat = saveFormat; @@ -31,6 +36,7 @@ public PdfPageImage(BufferedImage image, int originalIndex, String originalFilen /** * Return the image in a format suitable for sending to MindeeClient for parsing. + * * @return an instance of {@link LocalInputSource} */ public LocalInputSource asInputSource() throws IOException { @@ -42,6 +48,7 @@ public LocalInputSource asInputSource() throws IOException { /** * Write the image to a file. * Uses the default image format and filename. + * * @param outputPath the output directory (must exist). */ public void writeToFile(String outputPath) throws IOException, MindeeException { @@ -52,6 +59,7 @@ public void writeToFile(String outputPath) throws IOException, MindeeException { /** * Generate a filename for the image. + * * @return An auto-generated filename String. */ public String getFilename() { diff --git a/src/main/java/com/mindee/product/barcodereader/BarcodeReaderV1.java b/src/main/java/com/mindee/product/barcodereader/BarcodeReaderV1.java index c164f57b4..8e8dad7aa 100644 --- a/src/main/java/com/mindee/product/barcodereader/BarcodeReaderV1.java +++ b/src/main/java/com/mindee/product/barcodereader/BarcodeReaderV1.java @@ -11,6 +11,5 @@ @Getter @JsonIgnoreProperties(ignoreUnknown = true) @EndpointInfo(endpointName = "barcode_reader", version = "1") -public class BarcodeReaderV1 - extends Inference { +public class BarcodeReaderV1 extends Inference { } diff --git a/src/main/java/com/mindee/product/barcodereader/BarcodeReaderV1Document.java b/src/main/java/com/mindee/product/barcodereader/BarcodeReaderV1Document.java index dbc8a430c..fe6c44267 100644 --- a/src/main/java/com/mindee/product/barcodereader/BarcodeReaderV1Document.java +++ b/src/main/java/com/mindee/product/barcodereader/BarcodeReaderV1Document.java @@ -31,29 +31,17 @@ public class BarcodeReaderV1Document extends Prediction { @Override public boolean isEmpty() { - return ( - (this.codes1D == null || this.codes1D.isEmpty()) - && (this.codes2D == null || this.codes2D.isEmpty()) - ); + return ((this.codes1D == null || this.codes1D.isEmpty()) + && (this.codes2D == null || this.codes2D.isEmpty())); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - String codes1D = SummaryHelper.arrayToString( - this.getCodes1D(), - "%n " - ); - outStr.append( - String.format(":Barcodes 1D: %s%n", codes1D) - ); - String codes2D = SummaryHelper.arrayToString( - this.getCodes2D(), - "%n " - ); - outStr.append( - String.format(":Barcodes 2D: %s%n", codes2D) - ); + String codes1D = SummaryHelper.arrayToString(this.getCodes1D(), "%n "); + outStr.append(String.format(":Barcodes 1D: %s%n", codes1D)); + String codes2D = SummaryHelper.arrayToString(this.getCodes2D(), "%n "); + outStr.append(String.format(":Barcodes 2D: %s%n", codes2D)); return SummaryHelper.cleanSummary(outStr.toString()); } } diff --git a/src/main/java/com/mindee/product/billoflading/BillOfLadingV1.java b/src/main/java/com/mindee/product/billoflading/BillOfLadingV1.java index c0b0ed20b..d893ad8b3 100644 --- a/src/main/java/com/mindee/product/billoflading/BillOfLadingV1.java +++ b/src/main/java/com/mindee/product/billoflading/BillOfLadingV1.java @@ -11,6 +11,5 @@ @Getter @JsonIgnoreProperties(ignoreUnknown = true) @EndpointInfo(endpointName = "bill_of_lading", version = "1") -public class BillOfLadingV1 - extends Inference { +public class BillOfLadingV1 extends Inference { } diff --git a/src/main/java/com/mindee/product/billoflading/BillOfLadingV1Carrier.java b/src/main/java/com/mindee/product/billoflading/BillOfLadingV1Carrier.java index 04e600dbd..02d16df85 100644 --- a/src/main/java/com/mindee/product/billoflading/BillOfLadingV1Carrier.java +++ b/src/main/java/com/mindee/product/billoflading/BillOfLadingV1Carrier.java @@ -32,11 +32,9 @@ public class BillOfLadingV1Carrier extends BaseField { String scac; public boolean isEmpty() { - return ( - (name == null || name.isEmpty()) - && (professionalNumber == null || professionalNumber.isEmpty()) - && (scac == null || scac.isEmpty()) - ); + return ((name == null || name.isEmpty()) + && (professionalNumber == null || professionalNumber.isEmpty()) + && (scac == null || scac.isEmpty())); } /** @@ -45,8 +43,8 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Name: %s%n", printable.get("name")) - + String.format(" :Professional Number: %s%n", printable.get("professionalNumber")) - + String.format(" :SCAC: %s%n", printable.get("scac")); + + String.format(" :Professional Number: %s%n", printable.get("professionalNumber")) + + String.format(" :SCAC: %s%n", printable.get("scac")); } @Override @@ -61,7 +59,8 @@ private Map printableValues() { Map printable = new HashMap<>(); printable.put("name", SummaryHelper.formatForDisplay(this.name, null)); - printable.put("professionalNumber", SummaryHelper.formatForDisplay(this.professionalNumber, null)); + printable + .put("professionalNumber", SummaryHelper.formatForDisplay(this.professionalNumber, null)); printable.put("scac", SummaryHelper.formatForDisplay(this.scac, null)); return printable; } diff --git a/src/main/java/com/mindee/product/billoflading/BillOfLadingV1CarrierItem.java b/src/main/java/com/mindee/product/billoflading/BillOfLadingV1CarrierItem.java index ebb4f281d..5cdd5d5f3 100644 --- a/src/main/java/com/mindee/product/billoflading/BillOfLadingV1CarrierItem.java +++ b/src/main/java/com/mindee/product/billoflading/BillOfLadingV1CarrierItem.java @@ -48,33 +48,22 @@ public class BillOfLadingV1CarrierItem extends BaseField implements LineItemFiel String weightUnit; public boolean isEmpty() { - return ( - (description == null || description.isEmpty()) - && grossWeight == null - && measurement == null - && (measurementUnit == null || measurementUnit.isEmpty()) - && quantity == null - && (weightUnit == null || weightUnit.isEmpty()) - ); + return ((description == null || description.isEmpty()) + && grossWeight == null + && measurement == null + && (measurementUnit == null || measurementUnit.isEmpty()) + && quantity == null + && (weightUnit == null || weightUnit.isEmpty())); } private Map tablePrintableValues() { Map printable = new HashMap<>(); printable.put("description", SummaryHelper.formatForDisplay(this.description, 36)); - printable.put( - "grossWeight", - SummaryHelper.formatAmount(this.grossWeight) - ); - printable.put( - "measurement", - SummaryHelper.formatAmount(this.measurement) - ); + printable.put("grossWeight", SummaryHelper.formatAmount(this.grossWeight)); + printable.put("measurement", SummaryHelper.formatAmount(this.measurement)); printable.put("measurementUnit", SummaryHelper.formatForDisplay(this.measurementUnit, null)); - printable.put( - "quantity", - SummaryHelper.formatAmount(this.quantity) - ); + printable.put("quantity", SummaryHelper.formatAmount(this.quantity)); printable.put("weightUnit", SummaryHelper.formatForDisplay(this.weightUnit, null)); return printable; } @@ -107,19 +96,10 @@ private Map printableValues() { Map printable = new HashMap<>(); printable.put("description", SummaryHelper.formatForDisplay(this.description, null)); - printable.put( - "grossWeight", - SummaryHelper.formatAmount(this.grossWeight) - ); - printable.put( - "measurement", - SummaryHelper.formatAmount(this.measurement) - ); + printable.put("grossWeight", SummaryHelper.formatAmount(this.grossWeight)); + printable.put("measurement", SummaryHelper.formatAmount(this.measurement)); printable.put("measurementUnit", SummaryHelper.formatForDisplay(this.measurementUnit, null)); - printable.put( - "quantity", - SummaryHelper.formatAmount(this.quantity) - ); + printable.put("quantity", SummaryHelper.formatAmount(this.quantity)); printable.put("weightUnit", SummaryHelper.formatForDisplay(this.weightUnit, null)); return printable; } diff --git a/src/main/java/com/mindee/product/billoflading/BillOfLadingV1Consignee.java b/src/main/java/com/mindee/product/billoflading/BillOfLadingV1Consignee.java index 2a93ed54b..38a566329 100644 --- a/src/main/java/com/mindee/product/billoflading/BillOfLadingV1Consignee.java +++ b/src/main/java/com/mindee/product/billoflading/BillOfLadingV1Consignee.java @@ -21,7 +21,7 @@ public class BillOfLadingV1Consignee extends BaseField { @JsonProperty("address") String address; /** - * The email of the shipper. + * The email of the shipper. */ @JsonProperty("email") String email; @@ -37,12 +37,10 @@ public class BillOfLadingV1Consignee extends BaseField { String phone; public boolean isEmpty() { - return ( - (address == null || address.isEmpty()) - && (email == null || email.isEmpty()) - && (name == null || name.isEmpty()) - && (phone == null || phone.isEmpty()) - ); + return ((address == null || address.isEmpty()) + && (email == null || email.isEmpty()) + && (name == null || name.isEmpty()) + && (phone == null || phone.isEmpty())); } /** @@ -51,9 +49,9 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Address: %s%n", printable.get("address")) - + String.format(" :Email: %s%n", printable.get("email")) - + String.format(" :Name: %s%n", printable.get("name")) - + String.format(" :Phone: %s%n", printable.get("phone")); + + String.format(" :Email: %s%n", printable.get("email")) + + String.format(" :Name: %s%n", printable.get("name")) + + String.format(" :Phone: %s%n", printable.get("phone")); } @Override diff --git a/src/main/java/com/mindee/product/billoflading/BillOfLadingV1Document.java b/src/main/java/com/mindee/product/billoflading/BillOfLadingV1Document.java index 6f946347f..053106c32 100644 --- a/src/main/java/com/mindee/product/billoflading/BillOfLadingV1Document.java +++ b/src/main/java/com/mindee/product/billoflading/BillOfLadingV1Document.java @@ -77,8 +77,7 @@ public class BillOfLadingV1Document extends Prediction { @Override public boolean isEmpty() { - return ( - this.billOfLadingNumber == null + return (this.billOfLadingNumber == null && this.shipper == null && this.consignee == null && this.notifyParty == null @@ -88,61 +87,40 @@ public boolean isEmpty() { && this.portOfDischarge == null && this.placeOfDelivery == null && this.dateOfIssue == null - && this.departureDate == null - ); + && this.departureDate == null); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - outStr.append( - String.format(":Bill of Lading Number: %s%n", this.getBillOfLadingNumber()) - ); - outStr.append( - String.format(":Shipper:%n%s", this.getShipper().toFieldList()) - ); - outStr.append( - String.format(":Consignee:%n%s", this.getConsignee().toFieldList()) - ); - outStr.append( - String.format(":Notify Party:%n%s", this.getNotifyParty().toFieldList()) - ); - outStr.append( - String.format(":Carrier:%n%s", this.getCarrier().toFieldList()) - ); + outStr.append(String.format(":Bill of Lading Number: %s%n", this.getBillOfLadingNumber())); + outStr.append(String.format(":Shipper:%n%s", this.getShipper().toFieldList())); + outStr.append(String.format(":Consignee:%n%s", this.getConsignee().toFieldList())); + outStr.append(String.format(":Notify Party:%n%s", this.getNotifyParty().toFieldList())); + outStr.append(String.format(":Carrier:%n%s", this.getCarrier().toFieldList())); String carrierItemsSummary = ""; if (!this.getCarrierItems().isEmpty()) { - int[] carrierItemsColSizes = new int[]{38, 14, 13, 18, 10, 13}; - carrierItemsSummary = - String.format("%n%s%n ", SummaryHelper.lineSeparator(carrierItemsColSizes, "-")) - + "| Description " - + "| Gross Weight " - + "| Measurement " - + "| Measurement Unit " - + "| Quantity " - + "| Weight Unit " - + String.format("|%n%s%n ", SummaryHelper.lineSeparator(carrierItemsColSizes, "=")); - carrierItemsSummary += SummaryHelper.arrayToString(this.getCarrierItems(), carrierItemsColSizes); - carrierItemsSummary += String.format("%n%s", SummaryHelper.lineSeparator(carrierItemsColSizes, "-")); + int[] carrierItemsColSizes = new int[] { 38, 14, 13, 18, 10, 13 }; + carrierItemsSummary = String + .format("%n%s%n ", SummaryHelper.lineSeparator(carrierItemsColSizes, "-")) + + "| Description " + + "| Gross Weight " + + "| Measurement " + + "| Measurement Unit " + + "| Quantity " + + "| Weight Unit " + + String.format("|%n%s%n ", SummaryHelper.lineSeparator(carrierItemsColSizes, "=")); + carrierItemsSummary += SummaryHelper + .arrayToString(this.getCarrierItems(), carrierItemsColSizes); + carrierItemsSummary += String + .format("%n%s", SummaryHelper.lineSeparator(carrierItemsColSizes, "-")); } - outStr.append( - String.format(":Items: %s%n", carrierItemsSummary) - ); - outStr.append( - String.format(":Port of Loading: %s%n", this.getPortOfLoading()) - ); - outStr.append( - String.format(":Port of Discharge: %s%n", this.getPortOfDischarge()) - ); - outStr.append( - String.format(":Place of Delivery: %s%n", this.getPlaceOfDelivery()) - ); - outStr.append( - String.format(":Date of issue: %s%n", this.getDateOfIssue()) - ); - outStr.append( - String.format(":Departure Date: %s%n", this.getDepartureDate()) - ); + outStr.append(String.format(":Items: %s%n", carrierItemsSummary)); + outStr.append(String.format(":Port of Loading: %s%n", this.getPortOfLoading())); + outStr.append(String.format(":Port of Discharge: %s%n", this.getPortOfDischarge())); + outStr.append(String.format(":Place of Delivery: %s%n", this.getPlaceOfDelivery())); + outStr.append(String.format(":Date of issue: %s%n", this.getDateOfIssue())); + outStr.append(String.format(":Departure Date: %s%n", this.getDepartureDate())); return SummaryHelper.cleanSummary(outStr.toString()); } } diff --git a/src/main/java/com/mindee/product/billoflading/BillOfLadingV1NotifyParty.java b/src/main/java/com/mindee/product/billoflading/BillOfLadingV1NotifyParty.java index ece433791..70f5de432 100644 --- a/src/main/java/com/mindee/product/billoflading/BillOfLadingV1NotifyParty.java +++ b/src/main/java/com/mindee/product/billoflading/BillOfLadingV1NotifyParty.java @@ -21,7 +21,7 @@ public class BillOfLadingV1NotifyParty extends BaseField { @JsonProperty("address") String address; /** - * The email of the shipper. + * The email of the shipper. */ @JsonProperty("email") String email; @@ -37,12 +37,10 @@ public class BillOfLadingV1NotifyParty extends BaseField { String phone; public boolean isEmpty() { - return ( - (address == null || address.isEmpty()) - && (email == null || email.isEmpty()) - && (name == null || name.isEmpty()) - && (phone == null || phone.isEmpty()) - ); + return ((address == null || address.isEmpty()) + && (email == null || email.isEmpty()) + && (name == null || name.isEmpty()) + && (phone == null || phone.isEmpty())); } /** @@ -51,9 +49,9 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Address: %s%n", printable.get("address")) - + String.format(" :Email: %s%n", printable.get("email")) - + String.format(" :Name: %s%n", printable.get("name")) - + String.format(" :Phone: %s%n", printable.get("phone")); + + String.format(" :Email: %s%n", printable.get("email")) + + String.format(" :Name: %s%n", printable.get("name")) + + String.format(" :Phone: %s%n", printable.get("phone")); } @Override diff --git a/src/main/java/com/mindee/product/billoflading/BillOfLadingV1Shipper.java b/src/main/java/com/mindee/product/billoflading/BillOfLadingV1Shipper.java index 6d611dbc0..d478dde0b 100644 --- a/src/main/java/com/mindee/product/billoflading/BillOfLadingV1Shipper.java +++ b/src/main/java/com/mindee/product/billoflading/BillOfLadingV1Shipper.java @@ -21,7 +21,7 @@ public class BillOfLadingV1Shipper extends BaseField { @JsonProperty("address") String address; /** - * The email of the shipper. + * The email of the shipper. */ @JsonProperty("email") String email; @@ -37,12 +37,10 @@ public class BillOfLadingV1Shipper extends BaseField { String phone; public boolean isEmpty() { - return ( - (address == null || address.isEmpty()) - && (email == null || email.isEmpty()) - && (name == null || name.isEmpty()) - && (phone == null || phone.isEmpty()) - ); + return ((address == null || address.isEmpty()) + && (email == null || email.isEmpty()) + && (name == null || name.isEmpty()) + && (phone == null || phone.isEmpty())); } /** @@ -51,9 +49,9 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Address: %s%n", printable.get("address")) - + String.format(" :Email: %s%n", printable.get("email")) - + String.format(" :Name: %s%n", printable.get("name")) - + String.format(" :Phone: %s%n", printable.get("phone")); + + String.format(" :Email: %s%n", printable.get("email")) + + String.format(" :Name: %s%n", printable.get("name")) + + String.format(" :Phone: %s%n", printable.get("phone")); } @Override diff --git a/src/main/java/com/mindee/product/businesscard/BusinessCardV1.java b/src/main/java/com/mindee/product/businesscard/BusinessCardV1.java index 9cfd76b27..97f6066e3 100644 --- a/src/main/java/com/mindee/product/businesscard/BusinessCardV1.java +++ b/src/main/java/com/mindee/product/businesscard/BusinessCardV1.java @@ -11,6 +11,5 @@ @Getter @JsonIgnoreProperties(ignoreUnknown = true) @EndpointInfo(endpointName = "business_card", version = "1") -public class BusinessCardV1 - extends Inference { +public class BusinessCardV1 extends Inference { } diff --git a/src/main/java/com/mindee/product/businesscard/BusinessCardV1Document.java b/src/main/java/com/mindee/product/businesscard/BusinessCardV1Document.java index 99c72783b..000e74270 100644 --- a/src/main/java/com/mindee/product/businesscard/BusinessCardV1Document.java +++ b/src/main/java/com/mindee/product/businesscard/BusinessCardV1Document.java @@ -76,8 +76,7 @@ public class BusinessCardV1Document extends Prediction { @Override public boolean isEmpty() { - return ( - this.firstname == null + return (this.firstname == null && this.lastname == null && this.jobTitle == null && this.company == null @@ -87,50 +86,24 @@ public boolean isEmpty() { && this.faxNumber == null && this.address == null && this.website == null - && (this.socialMedia == null || this.socialMedia.isEmpty()) - ); + && (this.socialMedia == null || this.socialMedia.isEmpty())); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - outStr.append( - String.format(":Firstname: %s%n", this.getFirstname()) - ); - outStr.append( - String.format(":Lastname: %s%n", this.getLastname()) - ); - outStr.append( - String.format(":Job Title: %s%n", this.getJobTitle()) - ); - outStr.append( - String.format(":Company: %s%n", this.getCompany()) - ); - outStr.append( - String.format(":Email: %s%n", this.getEmail()) - ); - outStr.append( - String.format(":Phone Number: %s%n", this.getPhoneNumber()) - ); - outStr.append( - String.format(":Mobile Number: %s%n", this.getMobileNumber()) - ); - outStr.append( - String.format(":Fax Number: %s%n", this.getFaxNumber()) - ); - outStr.append( - String.format(":Address: %s%n", this.getAddress()) - ); - outStr.append( - String.format(":Website: %s%n", this.getWebsite()) - ); - String socialMedia = SummaryHelper.arrayToString( - this.getSocialMedia(), - "%n " - ); - outStr.append( - String.format(":Social Media: %s%n", socialMedia) - ); + outStr.append(String.format(":Firstname: %s%n", this.getFirstname())); + outStr.append(String.format(":Lastname: %s%n", this.getLastname())); + outStr.append(String.format(":Job Title: %s%n", this.getJobTitle())); + outStr.append(String.format(":Company: %s%n", this.getCompany())); + outStr.append(String.format(":Email: %s%n", this.getEmail())); + outStr.append(String.format(":Phone Number: %s%n", this.getPhoneNumber())); + outStr.append(String.format(":Mobile Number: %s%n", this.getMobileNumber())); + outStr.append(String.format(":Fax Number: %s%n", this.getFaxNumber())); + outStr.append(String.format(":Address: %s%n", this.getAddress())); + outStr.append(String.format(":Website: %s%n", this.getWebsite())); + String socialMedia = SummaryHelper.arrayToString(this.getSocialMedia(), "%n "); + outStr.append(String.format(":Social Media: %s%n", socialMedia)); return SummaryHelper.cleanSummary(outStr.toString()); } } diff --git a/src/main/java/com/mindee/product/cropper/CropperV1.java b/src/main/java/com/mindee/product/cropper/CropperV1.java index ec2e5061b..031f76627 100644 --- a/src/main/java/com/mindee/product/cropper/CropperV1.java +++ b/src/main/java/com/mindee/product/cropper/CropperV1.java @@ -11,6 +11,5 @@ @Getter @JsonIgnoreProperties(ignoreUnknown = true) @EndpointInfo(endpointName = "cropper", version = "1") -public class CropperV1 - extends Inference { +public class CropperV1 extends Inference { } diff --git a/src/main/java/com/mindee/product/cropper/CropperV1Document.java b/src/main/java/com/mindee/product/cropper/CropperV1Document.java index bedf56bac..e2fa77603 100644 --- a/src/main/java/com/mindee/product/cropper/CropperV1Document.java +++ b/src/main/java/com/mindee/product/cropper/CropperV1Document.java @@ -13,7 +13,6 @@ @JsonIgnoreProperties(ignoreUnknown = true) public class CropperV1Document extends Prediction { - @Override public boolean isEmpty() { return false; diff --git a/src/main/java/com/mindee/product/cropper/CropperV1Page.java b/src/main/java/com/mindee/product/cropper/CropperV1Page.java index eac838695..31a29cec0 100644 --- a/src/main/java/com/mindee/product/cropper/CropperV1Page.java +++ b/src/main/java/com/mindee/product/cropper/CropperV1Page.java @@ -25,21 +25,14 @@ public class CropperV1Page extends CropperV1Document { @Override public boolean isEmpty() { - return ( - (this.cropping == null || this.cropping.isEmpty()) - ); + return ((this.cropping == null || this.cropping.isEmpty())); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - String cropping = SummaryHelper.arrayToString( - this.getCropping(), - "%n " - ); - outStr.append( - String.format(":Document Cropper: %s%n", cropping) - ); + String cropping = SummaryHelper.arrayToString(this.getCropping(), "%n "); + outStr.append(String.format(":Document Cropper: %s%n", cropping)); outStr.append(super.toString()); return SummaryHelper.cleanSummary(outStr.toString()); } diff --git a/src/main/java/com/mindee/product/custom/CustomV1Document.java b/src/main/java/com/mindee/product/custom/CustomV1Document.java index e1665673c..27faa41b6 100644 --- a/src/main/java/com/mindee/product/custom/CustomV1Document.java +++ b/src/main/java/com/mindee/product/custom/CustomV1Document.java @@ -13,7 +13,6 @@ import lombok.EqualsAndHashCode; import lombok.Getter; - /** * Document data for custom documents, API version 1.x. */ diff --git a/src/main/java/com/mindee/product/custom/CustomV1Page.java b/src/main/java/com/mindee/product/custom/CustomV1Page.java index c0f357532..4f8d3e8dc 100644 --- a/src/main/java/com/mindee/product/custom/CustomV1Page.java +++ b/src/main/java/com/mindee/product/custom/CustomV1Page.java @@ -8,7 +8,6 @@ import lombok.EqualsAndHashCode; import lombok.Getter; - /** * Page data for custom documents, API version 1.x. */ diff --git a/src/main/java/com/mindee/product/deliverynote/DeliveryNoteV1.java b/src/main/java/com/mindee/product/deliverynote/DeliveryNoteV1.java index d953e0e92..3889d1b87 100644 --- a/src/main/java/com/mindee/product/deliverynote/DeliveryNoteV1.java +++ b/src/main/java/com/mindee/product/deliverynote/DeliveryNoteV1.java @@ -11,6 +11,5 @@ @Getter @JsonIgnoreProperties(ignoreUnknown = true) @EndpointInfo(endpointName = "delivery_notes", version = "1") -public class DeliveryNoteV1 - extends Inference { +public class DeliveryNoteV1 extends Inference { } diff --git a/src/main/java/com/mindee/product/deliverynote/DeliveryNoteV1Document.java b/src/main/java/com/mindee/product/deliverynote/DeliveryNoteV1Document.java index 2aacb310e..3e8d06151 100644 --- a/src/main/java/com/mindee/product/deliverynote/DeliveryNoteV1Document.java +++ b/src/main/java/com/mindee/product/deliverynote/DeliveryNoteV1Document.java @@ -56,41 +56,25 @@ public class DeliveryNoteV1Document extends Prediction { @Override public boolean isEmpty() { - return ( - this.deliveryDate == null + return (this.deliveryDate == null && this.deliveryNumber == null && this.supplierName == null && this.supplierAddress == null && this.customerName == null && this.customerAddress == null - && this.totalAmount == null - ); + && this.totalAmount == null); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - outStr.append( - String.format(":Delivery Date: %s%n", this.getDeliveryDate()) - ); - outStr.append( - String.format(":Delivery Number: %s%n", this.getDeliveryNumber()) - ); - outStr.append( - String.format(":Supplier Name: %s%n", this.getSupplierName()) - ); - outStr.append( - String.format(":Supplier Address: %s%n", this.getSupplierAddress()) - ); - outStr.append( - String.format(":Customer Name: %s%n", this.getCustomerName()) - ); - outStr.append( - String.format(":Customer Address: %s%n", this.getCustomerAddress()) - ); - outStr.append( - String.format(":Total Amount: %s%n", this.getTotalAmount()) - ); + outStr.append(String.format(":Delivery Date: %s%n", this.getDeliveryDate())); + outStr.append(String.format(":Delivery Number: %s%n", this.getDeliveryNumber())); + outStr.append(String.format(":Supplier Name: %s%n", this.getSupplierName())); + outStr.append(String.format(":Supplier Address: %s%n", this.getSupplierAddress())); + outStr.append(String.format(":Customer Name: %s%n", this.getCustomerName())); + outStr.append(String.format(":Customer Address: %s%n", this.getCustomerAddress())); + outStr.append(String.format(":Total Amount: %s%n", this.getTotalAmount())); return SummaryHelper.cleanSummary(outStr.toString()); } } diff --git a/src/main/java/com/mindee/product/driverlicense/DriverLicenseV1.java b/src/main/java/com/mindee/product/driverlicense/DriverLicenseV1.java index aedbe68ab..5035f64b0 100644 --- a/src/main/java/com/mindee/product/driverlicense/DriverLicenseV1.java +++ b/src/main/java/com/mindee/product/driverlicense/DriverLicenseV1.java @@ -11,6 +11,5 @@ @Getter @JsonIgnoreProperties(ignoreUnknown = true) @EndpointInfo(endpointName = "driver_license", version = "1") -public class DriverLicenseV1 - extends Inference { +public class DriverLicenseV1 extends Inference { } diff --git a/src/main/java/com/mindee/product/driverlicense/DriverLicenseV1Document.java b/src/main/java/com/mindee/product/driverlicense/DriverLicenseV1Document.java index 85d71d1da..3808b5250 100644 --- a/src/main/java/com/mindee/product/driverlicense/DriverLicenseV1Document.java +++ b/src/main/java/com/mindee/product/driverlicense/DriverLicenseV1Document.java @@ -85,8 +85,7 @@ public class DriverLicenseV1Document extends Prediction { @Override public boolean isEmpty() { - return ( - this.countryCode == null + return (this.countryCode == null && this.state == null && this.id == null && this.category == null @@ -98,52 +97,25 @@ public boolean isEmpty() { && this.issuedDate == null && this.issuingAuthority == null && this.mrz == null - && this.ddNumber == null - ); + && this.ddNumber == null); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - outStr.append( - String.format(":Country Code: %s%n", this.getCountryCode()) - ); - outStr.append( - String.format(":State: %s%n", this.getState()) - ); - outStr.append( - String.format(":ID: %s%n", this.getId()) - ); - outStr.append( - String.format(":Category: %s%n", this.getCategory()) - ); - outStr.append( - String.format(":Last Name: %s%n", this.getLastName()) - ); - outStr.append( - String.format(":First Name: %s%n", this.getFirstName()) - ); - outStr.append( - String.format(":Date of Birth: %s%n", this.getDateOfBirth()) - ); - outStr.append( - String.format(":Place of Birth: %s%n", this.getPlaceOfBirth()) - ); - outStr.append( - String.format(":Expiry Date: %s%n", this.getExpiryDate()) - ); - outStr.append( - String.format(":Issued Date: %s%n", this.getIssuedDate()) - ); - outStr.append( - String.format(":Issuing Authority: %s%n", this.getIssuingAuthority()) - ); - outStr.append( - String.format(":MRZ: %s%n", this.getMrz()) - ); - outStr.append( - String.format(":DD Number: %s%n", this.getDdNumber()) - ); + outStr.append(String.format(":Country Code: %s%n", this.getCountryCode())); + outStr.append(String.format(":State: %s%n", this.getState())); + outStr.append(String.format(":ID: %s%n", this.getId())); + outStr.append(String.format(":Category: %s%n", this.getCategory())); + outStr.append(String.format(":Last Name: %s%n", this.getLastName())); + outStr.append(String.format(":First Name: %s%n", this.getFirstName())); + outStr.append(String.format(":Date of Birth: %s%n", this.getDateOfBirth())); + outStr.append(String.format(":Place of Birth: %s%n", this.getPlaceOfBirth())); + outStr.append(String.format(":Expiry Date: %s%n", this.getExpiryDate())); + outStr.append(String.format(":Issued Date: %s%n", this.getIssuedDate())); + outStr.append(String.format(":Issuing Authority: %s%n", this.getIssuingAuthority())); + outStr.append(String.format(":MRZ: %s%n", this.getMrz())); + outStr.append(String.format(":DD Number: %s%n", this.getDdNumber())); return SummaryHelper.cleanSummary(outStr.toString()); } } diff --git a/src/main/java/com/mindee/product/financialdocument/FinancialDocumentV1Document.java b/src/main/java/com/mindee/product/financialdocument/FinancialDocumentV1Document.java index 83d527c66..2f879df7d 100644 --- a/src/main/java/com/mindee/product/financialdocument/FinancialDocumentV1Document.java +++ b/src/main/java/com/mindee/product/financialdocument/FinancialDocumentV1Document.java @@ -69,7 +69,8 @@ public class FinancialDocumentV1Document extends Prediction { @JsonProperty("document_number") protected StringField documentNumber; /** - * The type of the document: INVOICE or CREDIT NOTE if it is an invoice, CREDIT CARD RECEIPT or EXPENSE RECEIPT if it is a receipt. + * The type of the document: INVOICE or CREDIT NOTE if it is an invoice, CREDIT CARD RECEIPT or + * EXPENSE RECEIPT if it is a receipt. */ @JsonProperty("document_type") protected ClassificationField documentType; @@ -197,8 +198,7 @@ public class FinancialDocumentV1Document extends Prediction { @Override public boolean isEmpty() { - return ( - this.locale == null + return (this.locale == null && this.invoiceNumber == null && this.poNumber == null && this.receiptNumber == null @@ -230,145 +230,73 @@ public boolean isEmpty() { && this.totalTax == null && this.tip == null && this.time == null - && (this.lineItems == null || this.lineItems.isEmpty()) - ); + && (this.lineItems == null || this.lineItems.isEmpty())); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - outStr.append( - String.format(":Locale: %s%n", this.getLocale()) - ); - outStr.append( - String.format(":Invoice Number: %s%n", this.getInvoiceNumber()) - ); - outStr.append( - String.format(":Purchase Order Number: %s%n", this.getPoNumber()) - ); - outStr.append( - String.format(":Receipt Number: %s%n", this.getReceiptNumber()) - ); - outStr.append( - String.format(":Document Number: %s%n", this.getDocumentNumber()) - ); - String referenceNumbers = SummaryHelper.arrayToString( - this.getReferenceNumbers(), - "%n " - ); - outStr.append( - String.format(":Reference Numbers: %s%n", referenceNumbers) - ); - outStr.append( - String.format(":Purchase Date: %s%n", this.getDate()) - ); - outStr.append( - String.format(":Due Date: %s%n", this.getDueDate()) - ); - outStr.append( - String.format(":Payment Date: %s%n", this.getPaymentDate()) - ); - outStr.append( - String.format(":Total Net: %s%n", this.getTotalNet()) - ); - outStr.append( - String.format(":Total Amount: %s%n", this.getTotalAmount()) - ); - outStr.append( - String.format(":Taxes: %s%n", this.getTaxes()) - ); - String supplierPaymentDetails = SummaryHelper.arrayToString( - this.getSupplierPaymentDetails(), - "%n " - ); - outStr.append( - String.format(":Supplier Payment Details: %s%n", supplierPaymentDetails) - ); - outStr.append( - String.format(":Supplier Name: %s%n", this.getSupplierName()) - ); - String supplierCompanyRegistrations = SummaryHelper.arrayToString( - this.getSupplierCompanyRegistrations(), - "%n " - ); - outStr.append( - String.format(":Supplier Company Registrations: %s%n", supplierCompanyRegistrations) - ); - outStr.append( - String.format(":Supplier Address: %s%n", this.getSupplierAddress()) - ); - outStr.append( - String.format(":Supplier Phone Number: %s%n", this.getSupplierPhoneNumber()) - ); - outStr.append( - String.format(":Customer Name: %s%n", this.getCustomerName()) - ); - outStr.append( - String.format(":Supplier Website: %s%n", this.getSupplierWebsite()) - ); - outStr.append( - String.format(":Supplier Email: %s%n", this.getSupplierEmail()) - ); - String customerCompanyRegistrations = SummaryHelper.arrayToString( - this.getCustomerCompanyRegistrations(), - "%n " - ); - outStr.append( - String.format(":Customer Company Registrations: %s%n", customerCompanyRegistrations) - ); - outStr.append( - String.format(":Customer Address: %s%n", this.getCustomerAddress()) - ); - outStr.append( - String.format(":Customer ID: %s%n", this.getCustomerId()) - ); - outStr.append( - String.format(":Shipping Address: %s%n", this.getShippingAddress()) - ); - outStr.append( - String.format(":Billing Address: %s%n", this.getBillingAddress()) - ); - outStr.append( - String.format(":Document Type: %s%n", this.getDocumentType()) - ); - outStr.append( - String.format(":Document Type Extended: %s%n", this.getDocumentTypeExtended()) - ); - outStr.append( - String.format(":Purchase Subcategory: %s%n", this.getSubcategory()) - ); - outStr.append( - String.format(":Purchase Category: %s%n", this.getCategory()) - ); - outStr.append( - String.format(":Total Tax: %s%n", this.getTotalTax()) - ); - outStr.append( - String.format(":Tip and Gratuity: %s%n", this.getTip()) - ); - outStr.append( - String.format(":Purchase Time: %s%n", this.getTime()) - ); + outStr.append(String.format(":Locale: %s%n", this.getLocale())); + outStr.append(String.format(":Invoice Number: %s%n", this.getInvoiceNumber())); + outStr.append(String.format(":Purchase Order Number: %s%n", this.getPoNumber())); + outStr.append(String.format(":Receipt Number: %s%n", this.getReceiptNumber())); + outStr.append(String.format(":Document Number: %s%n", this.getDocumentNumber())); + String referenceNumbers = SummaryHelper + .arrayToString(this.getReferenceNumbers(), "%n "); + outStr.append(String.format(":Reference Numbers: %s%n", referenceNumbers)); + outStr.append(String.format(":Purchase Date: %s%n", this.getDate())); + outStr.append(String.format(":Due Date: %s%n", this.getDueDate())); + outStr.append(String.format(":Payment Date: %s%n", this.getPaymentDate())); + outStr.append(String.format(":Total Net: %s%n", this.getTotalNet())); + outStr.append(String.format(":Total Amount: %s%n", this.getTotalAmount())); + outStr.append(String.format(":Taxes: %s%n", this.getTaxes())); + String supplierPaymentDetails = SummaryHelper + .arrayToString(this.getSupplierPaymentDetails(), "%n "); + outStr.append(String.format(":Supplier Payment Details: %s%n", supplierPaymentDetails)); + outStr.append(String.format(":Supplier Name: %s%n", this.getSupplierName())); + String supplierCompanyRegistrations = SummaryHelper + .arrayToString(this.getSupplierCompanyRegistrations(), "%n "); + outStr + .append(String.format(":Supplier Company Registrations: %s%n", supplierCompanyRegistrations)); + outStr.append(String.format(":Supplier Address: %s%n", this.getSupplierAddress())); + outStr.append(String.format(":Supplier Phone Number: %s%n", this.getSupplierPhoneNumber())); + outStr.append(String.format(":Customer Name: %s%n", this.getCustomerName())); + outStr.append(String.format(":Supplier Website: %s%n", this.getSupplierWebsite())); + outStr.append(String.format(":Supplier Email: %s%n", this.getSupplierEmail())); + String customerCompanyRegistrations = SummaryHelper + .arrayToString(this.getCustomerCompanyRegistrations(), "%n "); + outStr + .append(String.format(":Customer Company Registrations: %s%n", customerCompanyRegistrations)); + outStr.append(String.format(":Customer Address: %s%n", this.getCustomerAddress())); + outStr.append(String.format(":Customer ID: %s%n", this.getCustomerId())); + outStr.append(String.format(":Shipping Address: %s%n", this.getShippingAddress())); + outStr.append(String.format(":Billing Address: %s%n", this.getBillingAddress())); + outStr.append(String.format(":Document Type: %s%n", this.getDocumentType())); + outStr.append(String.format(":Document Type Extended: %s%n", this.getDocumentTypeExtended())); + outStr.append(String.format(":Purchase Subcategory: %s%n", this.getSubcategory())); + outStr.append(String.format(":Purchase Category: %s%n", this.getCategory())); + outStr.append(String.format(":Total Tax: %s%n", this.getTotalTax())); + outStr.append(String.format(":Tip and Gratuity: %s%n", this.getTip())); + outStr.append(String.format(":Purchase Time: %s%n", this.getTime())); String lineItemsSummary = ""; if (!this.getLineItems().isEmpty()) { - int[] lineItemsColSizes = new int[]{38, 14, 10, 12, 14, 14, 17, 12}; - lineItemsSummary = - String.format("%n%s%n ", SummaryHelper.lineSeparator(lineItemsColSizes, "-")) - + "| Description " - + "| Product code " - + "| Quantity " - + "| Tax Amount " - + "| Tax Rate (%) " - + "| Total Amount " - + "| Unit of measure " - + "| Unit Price " - + String.format("|%n%s%n ", SummaryHelper.lineSeparator(lineItemsColSizes, "=")); + int[] lineItemsColSizes = new int[] { 38, 14, 10, 12, 14, 14, 17, 12 }; + lineItemsSummary = String + .format("%n%s%n ", SummaryHelper.lineSeparator(lineItemsColSizes, "-")) + + "| Description " + + "| Product code " + + "| Quantity " + + "| Tax Amount " + + "| Tax Rate (%) " + + "| Total Amount " + + "| Unit of measure " + + "| Unit Price " + + String.format("|%n%s%n ", SummaryHelper.lineSeparator(lineItemsColSizes, "=")); lineItemsSummary += SummaryHelper.arrayToString(this.getLineItems(), lineItemsColSizes); - lineItemsSummary += String.format("%n%s", SummaryHelper.lineSeparator(lineItemsColSizes, "-")); + lineItemsSummary += String + .format("%n%s", SummaryHelper.lineSeparator(lineItemsColSizes, "-")); } - outStr.append( - String.format(":Line Items: %s%n", lineItemsSummary) - ); + outStr.append(String.format(":Line Items: %s%n", lineItemsSummary)); return SummaryHelper.cleanSummary(outStr.toString()); } } diff --git a/src/main/java/com/mindee/product/financialdocument/FinancialDocumentV1LineItem.java b/src/main/java/com/mindee/product/financialdocument/FinancialDocumentV1LineItem.java index 3cc48cbdc..47ec3a696 100644 --- a/src/main/java/com/mindee/product/financialdocument/FinancialDocumentV1LineItem.java +++ b/src/main/java/com/mindee/product/financialdocument/FinancialDocumentV1LineItem.java @@ -58,16 +58,14 @@ public class FinancialDocumentV1LineItem extends BaseField implements LineItemFi Double unitPrice; public boolean isEmpty() { - return ( - (description == null || description.isEmpty()) - && (productCode == null || productCode.isEmpty()) - && quantity == null - && taxAmount == null - && taxRate == null - && totalAmount == null - && (unitMeasure == null || unitMeasure.isEmpty()) - && unitPrice == null - ); + return ((description == null || description.isEmpty()) + && (productCode == null || productCode.isEmpty()) + && quantity == null + && taxAmount == null + && taxRate == null + && totalAmount == null + && (unitMeasure == null || unitMeasure.isEmpty()) + && unitPrice == null); } private Map tablePrintableValues() { @@ -75,27 +73,12 @@ private Map tablePrintableValues() { printable.put("description", SummaryHelper.formatForDisplay(this.description, 36)); printable.put("productCode", SummaryHelper.formatForDisplay(this.productCode, null)); - printable.put( - "quantity", - SummaryHelper.formatAmount(this.quantity) - ); - printable.put( - "taxAmount", - SummaryHelper.formatAmount(this.taxAmount) - ); - printable.put( - "taxRate", - SummaryHelper.formatAmount(this.taxRate) - ); - printable.put( - "totalAmount", - SummaryHelper.formatAmount(this.totalAmount) - ); + printable.put("quantity", SummaryHelper.formatAmount(this.quantity)); + printable.put("taxAmount", SummaryHelper.formatAmount(this.taxAmount)); + printable.put("taxRate", SummaryHelper.formatAmount(this.taxRate)); + printable.put("totalAmount", SummaryHelper.formatAmount(this.totalAmount)); printable.put("unitMeasure", SummaryHelper.formatForDisplay(this.unitMeasure, null)); - printable.put( - "unitPrice", - SummaryHelper.formatAmount(this.unitPrice) - ); + printable.put("unitPrice", SummaryHelper.formatAmount(this.unitPrice)); return printable; } @@ -132,27 +115,12 @@ private Map printableValues() { printable.put("description", SummaryHelper.formatForDisplay(this.description, null)); printable.put("productCode", SummaryHelper.formatForDisplay(this.productCode, null)); - printable.put( - "quantity", - SummaryHelper.formatAmount(this.quantity) - ); - printable.put( - "taxAmount", - SummaryHelper.formatAmount(this.taxAmount) - ); - printable.put( - "taxRate", - SummaryHelper.formatAmount(this.taxRate) - ); - printable.put( - "totalAmount", - SummaryHelper.formatAmount(this.totalAmount) - ); + printable.put("quantity", SummaryHelper.formatAmount(this.quantity)); + printable.put("taxAmount", SummaryHelper.formatAmount(this.taxAmount)); + printable.put("taxRate", SummaryHelper.formatAmount(this.taxRate)); + printable.put("totalAmount", SummaryHelper.formatAmount(this.totalAmount)); printable.put("unitMeasure", SummaryHelper.formatForDisplay(this.unitMeasure, null)); - printable.put( - "unitPrice", - SummaryHelper.formatAmount(this.unitPrice) - ); + printable.put("unitPrice", SummaryHelper.formatAmount(this.unitPrice)); return printable; } } diff --git a/src/main/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV1Document.java b/src/main/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV1Document.java index 48aa9f797..9be2de22a 100644 --- a/src/main/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV1Document.java +++ b/src/main/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV1Document.java @@ -34,25 +34,15 @@ public class BankAccountDetailsV1Document extends Prediction { @Override public boolean isEmpty() { - return ( - this.iban == null - && this.accountHolderName == null - && this.swift == null - ); + return (this.iban == null && this.accountHolderName == null && this.swift == null); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - outStr.append( - String.format(":IBAN: %s%n", this.getIban()) - ); - outStr.append( - String.format(":Account Holder's Name: %s%n", this.getAccountHolderName()) - ); - outStr.append( - String.format(":SWIFT Code: %s%n", this.getSwift()) - ); + outStr.append(String.format(":IBAN: %s%n", this.getIban())); + outStr.append(String.format(":Account Holder's Name: %s%n", this.getAccountHolderName())); + outStr.append(String.format(":SWIFT Code: %s%n", this.getSwift())); return SummaryHelper.cleanSummary(outStr.toString()); } } diff --git a/src/main/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV2Bban.java b/src/main/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV2Bban.java index 1027f56bd..ea4829175 100644 --- a/src/main/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV2Bban.java +++ b/src/main/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV2Bban.java @@ -37,12 +37,10 @@ public class BankAccountDetailsV2Bban extends BaseField { String bbanNumber; public boolean isEmpty() { - return ( - (bbanBankCode == null || bbanBankCode.isEmpty()) - && (bbanBranchCode == null || bbanBranchCode.isEmpty()) - && (bbanKey == null || bbanKey.isEmpty()) - && (bbanNumber == null || bbanNumber.isEmpty()) - ); + return ((bbanBankCode == null || bbanBankCode.isEmpty()) + && (bbanBranchCode == null || bbanBranchCode.isEmpty()) + && (bbanKey == null || bbanKey.isEmpty()) + && (bbanNumber == null || bbanNumber.isEmpty())); } /** @@ -51,9 +49,9 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Bank Code: %s%n", printable.get("bbanBankCode")) - + String.format(" :Branch Code: %s%n", printable.get("bbanBranchCode")) - + String.format(" :Key: %s%n", printable.get("bbanKey")) - + String.format(" :Account Number: %s%n", printable.get("bbanNumber")); + + String.format(" :Branch Code: %s%n", printable.get("bbanBranchCode")) + + String.format(" :Key: %s%n", printable.get("bbanKey")) + + String.format(" :Account Number: %s%n", printable.get("bbanNumber")); } @Override diff --git a/src/main/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV2Document.java b/src/main/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV2Document.java index 71dba60c2..78d914c05 100644 --- a/src/main/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV2Document.java +++ b/src/main/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV2Document.java @@ -39,29 +39,19 @@ public class BankAccountDetailsV2Document extends Prediction { @Override public boolean isEmpty() { - return ( - this.accountHoldersNames == null + return (this.accountHoldersNames == null && this.bban == null && this.iban == null - && this.swiftCode == null - ); + && this.swiftCode == null); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - outStr.append( - String.format(":Account Holder's Names: %s%n", this.getAccountHoldersNames()) - ); - outStr.append( - String.format(":Basic Bank Account Number:%n%s", this.getBban().toFieldList()) - ); - outStr.append( - String.format(":IBAN: %s%n", this.getIban()) - ); - outStr.append( - String.format(":SWIFT Code: %s%n", this.getSwiftCode()) - ); + outStr.append(String.format(":Account Holder's Names: %s%n", this.getAccountHoldersNames())); + outStr.append(String.format(":Basic Bank Account Number:%n%s", this.getBban().toFieldList())); + outStr.append(String.format(":IBAN: %s%n", this.getIban())); + outStr.append(String.format(":SWIFT Code: %s%n", this.getSwiftCode())); return SummaryHelper.cleanSummary(outStr.toString()); } } diff --git a/src/main/java/com/mindee/product/fr/cartegrise/CarteGriseV1.java b/src/main/java/com/mindee/product/fr/cartegrise/CarteGriseV1.java index cfa41e761..686c557e7 100644 --- a/src/main/java/com/mindee/product/fr/cartegrise/CarteGriseV1.java +++ b/src/main/java/com/mindee/product/fr/cartegrise/CarteGriseV1.java @@ -11,6 +11,5 @@ @Getter @JsonIgnoreProperties(ignoreUnknown = true) @EndpointInfo(endpointName = "carte_grise", version = "1") -public class CarteGriseV1 - extends Inference { +public class CarteGriseV1 extends Inference { } diff --git a/src/main/java/com/mindee/product/fr/cartegrise/CarteGriseV1Document.java b/src/main/java/com/mindee/product/fr/cartegrise/CarteGriseV1Document.java index a93b05ad6..16f505af7 100644 --- a/src/main/java/com/mindee/product/fr/cartegrise/CarteGriseV1Document.java +++ b/src/main/java/com/mindee/product/fr/cartegrise/CarteGriseV1Document.java @@ -225,8 +225,7 @@ public class CarteGriseV1Document extends Prediction { @Override public boolean isEmpty() { - return ( - this.a == null + return (this.a == null && this.b == null && this.c1 == null && this.c3 == null @@ -266,136 +265,53 @@ public boolean isEmpty() { && this.ownerFirstName == null && this.ownerSurname == null && this.mrz1 == null - && this.mrz2 == null - ); + && this.mrz2 == null); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - outStr.append( - String.format(":a: %s%n", this.getA()) - ); - outStr.append( - String.format(":b: %s%n", this.getB()) - ); - outStr.append( - String.format(":c1: %s%n", this.getC1()) - ); - outStr.append( - String.format(":c3: %s%n", this.getC3()) - ); - outStr.append( - String.format(":c41: %s%n", this.getC41()) - ); - outStr.append( - String.format(":c4a: %s%n", this.getC4A()) - ); - outStr.append( - String.format(":d1: %s%n", this.getD1()) - ); - outStr.append( - String.format(":d3: %s%n", this.getD3()) - ); - outStr.append( - String.format(":e: %s%n", this.getE()) - ); - outStr.append( - String.format(":f1: %s%n", this.getF1()) - ); - outStr.append( - String.format(":f2: %s%n", this.getF2()) - ); - outStr.append( - String.format(":f3: %s%n", this.getF3()) - ); - outStr.append( - String.format(":g: %s%n", this.getG()) - ); - outStr.append( - String.format(":g1: %s%n", this.getG1()) - ); - outStr.append( - String.format(":i: %s%n", this.getI()) - ); - outStr.append( - String.format(":j: %s%n", this.getJ()) - ); - outStr.append( - String.format(":j1: %s%n", this.getJ1()) - ); - outStr.append( - String.format(":j2: %s%n", this.getJ2()) - ); - outStr.append( - String.format(":j3: %s%n", this.getJ3()) - ); - outStr.append( - String.format(":p1: %s%n", this.getP1()) - ); - outStr.append( - String.format(":p2: %s%n", this.getP2()) - ); - outStr.append( - String.format(":p3: %s%n", this.getP3()) - ); - outStr.append( - String.format(":p6: %s%n", this.getP6()) - ); - outStr.append( - String.format(":q: %s%n", this.getQ()) - ); - outStr.append( - String.format(":s1: %s%n", this.getS1()) - ); - outStr.append( - String.format(":s2: %s%n", this.getS2()) - ); - outStr.append( - String.format(":u1: %s%n", this.getU1()) - ); - outStr.append( - String.format(":u2: %s%n", this.getU2()) - ); - outStr.append( - String.format(":v7: %s%n", this.getV7()) - ); - outStr.append( - String.format(":x1: %s%n", this.getX1()) - ); - outStr.append( - String.format(":y1: %s%n", this.getY1()) - ); - outStr.append( - String.format(":y2: %s%n", this.getY2()) - ); - outStr.append( - String.format(":y3: %s%n", this.getY3()) - ); - outStr.append( - String.format(":y4: %s%n", this.getY4()) - ); - outStr.append( - String.format(":y5: %s%n", this.getY5()) - ); - outStr.append( - String.format(":y6: %s%n", this.getY6()) - ); - outStr.append( - String.format(":Formula Number: %s%n", this.getFormulaNumber()) - ); - outStr.append( - String.format(":Owner's First Name: %s%n", this.getOwnerFirstName()) - ); - outStr.append( - String.format(":Owner's Surname: %s%n", this.getOwnerSurname()) - ); - outStr.append( - String.format(":MRZ Line 1: %s%n", this.getMrz1()) - ); - outStr.append( - String.format(":MRZ Line 2: %s%n", this.getMrz2()) - ); + outStr.append(String.format(":a: %s%n", this.getA())); + outStr.append(String.format(":b: %s%n", this.getB())); + outStr.append(String.format(":c1: %s%n", this.getC1())); + outStr.append(String.format(":c3: %s%n", this.getC3())); + outStr.append(String.format(":c41: %s%n", this.getC41())); + outStr.append(String.format(":c4a: %s%n", this.getC4A())); + outStr.append(String.format(":d1: %s%n", this.getD1())); + outStr.append(String.format(":d3: %s%n", this.getD3())); + outStr.append(String.format(":e: %s%n", this.getE())); + outStr.append(String.format(":f1: %s%n", this.getF1())); + outStr.append(String.format(":f2: %s%n", this.getF2())); + outStr.append(String.format(":f3: %s%n", this.getF3())); + outStr.append(String.format(":g: %s%n", this.getG())); + outStr.append(String.format(":g1: %s%n", this.getG1())); + outStr.append(String.format(":i: %s%n", this.getI())); + outStr.append(String.format(":j: %s%n", this.getJ())); + outStr.append(String.format(":j1: %s%n", this.getJ1())); + outStr.append(String.format(":j2: %s%n", this.getJ2())); + outStr.append(String.format(":j3: %s%n", this.getJ3())); + outStr.append(String.format(":p1: %s%n", this.getP1())); + outStr.append(String.format(":p2: %s%n", this.getP2())); + outStr.append(String.format(":p3: %s%n", this.getP3())); + outStr.append(String.format(":p6: %s%n", this.getP6())); + outStr.append(String.format(":q: %s%n", this.getQ())); + outStr.append(String.format(":s1: %s%n", this.getS1())); + outStr.append(String.format(":s2: %s%n", this.getS2())); + outStr.append(String.format(":u1: %s%n", this.getU1())); + outStr.append(String.format(":u2: %s%n", this.getU2())); + outStr.append(String.format(":v7: %s%n", this.getV7())); + outStr.append(String.format(":x1: %s%n", this.getX1())); + outStr.append(String.format(":y1: %s%n", this.getY1())); + outStr.append(String.format(":y2: %s%n", this.getY2())); + outStr.append(String.format(":y3: %s%n", this.getY3())); + outStr.append(String.format(":y4: %s%n", this.getY4())); + outStr.append(String.format(":y5: %s%n", this.getY5())); + outStr.append(String.format(":y6: %s%n", this.getY6())); + outStr.append(String.format(":Formula Number: %s%n", this.getFormulaNumber())); + outStr.append(String.format(":Owner's First Name: %s%n", this.getOwnerFirstName())); + outStr.append(String.format(":Owner's Surname: %s%n", this.getOwnerSurname())); + outStr.append(String.format(":MRZ Line 1: %s%n", this.getMrz1())); + outStr.append(String.format(":MRZ Line 2: %s%n", this.getMrz2())); return SummaryHelper.cleanSummary(outStr.toString()); } } diff --git a/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1.java b/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1.java index 09d939298..3d267e740 100644 --- a/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1.java +++ b/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1.java @@ -11,6 +11,5 @@ @Getter @JsonIgnoreProperties(ignoreUnknown = true) @EndpointInfo(endpointName = "energy_bill_fra", version = "1") -public class EnergyBillV1 - extends Inference { +public class EnergyBillV1 extends Inference { } diff --git a/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1Document.java b/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1Document.java index 160e6763a..e6d023215 100644 --- a/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1Document.java +++ b/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1Document.java @@ -26,7 +26,8 @@ public class EnergyBillV1Document extends Prediction { @JsonProperty("contract_id") protected StringField contractId; /** - * The unique identifier assigned to each electricity or gas consumption point. It specifies the exact location where the energy is delivered. + * The unique identifier assigned to each electricity or gas consumption point. It specifies the + * exact location where the energy is delivered. */ @JsonProperty("delivery_point") protected StringField deliveryPoint; @@ -93,8 +94,7 @@ public class EnergyBillV1Document extends Prediction { @Override public boolean isEmpty() { - return ( - this.invoiceNumber == null + return (this.invoiceNumber == null && this.contractId == null && this.deliveryPoint == null && this.invoiceDate == null @@ -107,102 +107,79 @@ public boolean isEmpty() { && (this.subscription == null || this.subscription.isEmpty()) && (this.energyUsage == null || this.energyUsage.isEmpty()) && (this.taxesAndContributions == null || this.taxesAndContributions.isEmpty()) - && this.meterDetails == null - ); + && this.meterDetails == null); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - outStr.append( - String.format(":Invoice Number: %s%n", this.getInvoiceNumber()) - ); - outStr.append( - String.format(":Contract ID: %s%n", this.getContractId()) - ); - outStr.append( - String.format(":Delivery Point: %s%n", this.getDeliveryPoint()) - ); - outStr.append( - String.format(":Invoice Date: %s%n", this.getInvoiceDate()) - ); - outStr.append( - String.format(":Due Date: %s%n", this.getDueDate()) - ); - outStr.append( - String.format(":Total Before Taxes: %s%n", this.getTotalBeforeTaxes()) - ); - outStr.append( - String.format(":Total Taxes: %s%n", this.getTotalTaxes()) - ); - outStr.append( - String.format(":Total Amount: %s%n", this.getTotalAmount()) - ); - outStr.append( - String.format(":Energy Supplier:%n%s", this.getEnergySupplier().toFieldList()) - ); - outStr.append( - String.format(":Energy Consumer:%n%s", this.getEnergyConsumer().toFieldList()) - ); + outStr.append(String.format(":Invoice Number: %s%n", this.getInvoiceNumber())); + outStr.append(String.format(":Contract ID: %s%n", this.getContractId())); + outStr.append(String.format(":Delivery Point: %s%n", this.getDeliveryPoint())); + outStr.append(String.format(":Invoice Date: %s%n", this.getInvoiceDate())); + outStr.append(String.format(":Due Date: %s%n", this.getDueDate())); + outStr.append(String.format(":Total Before Taxes: %s%n", this.getTotalBeforeTaxes())); + outStr.append(String.format(":Total Taxes: %s%n", this.getTotalTaxes())); + outStr.append(String.format(":Total Amount: %s%n", this.getTotalAmount())); + outStr.append(String.format(":Energy Supplier:%n%s", this.getEnergySupplier().toFieldList())); + outStr.append(String.format(":Energy Consumer:%n%s", this.getEnergyConsumer().toFieldList())); String subscriptionSummary = ""; if (!this.getSubscription().isEmpty()) { - int[] subscriptionColSizes = new int[]{38, 12, 12, 10, 11, 12}; - subscriptionSummary = - String.format("%n%s%n ", SummaryHelper.lineSeparator(subscriptionColSizes, "-")) - + "| Description " - + "| End Date " - + "| Start Date " - + "| Tax Rate " - + "| Total " - + "| Unit Price " - + String.format("|%n%s%n ", SummaryHelper.lineSeparator(subscriptionColSizes, "=")); - subscriptionSummary += SummaryHelper.arrayToString(this.getSubscription(), subscriptionColSizes); - subscriptionSummary += String.format("%n%s", SummaryHelper.lineSeparator(subscriptionColSizes, "-")); + int[] subscriptionColSizes = new int[] { 38, 12, 12, 10, 11, 12 }; + subscriptionSummary = String + .format("%n%s%n ", SummaryHelper.lineSeparator(subscriptionColSizes, "-")) + + "| Description " + + "| End Date " + + "| Start Date " + + "| Tax Rate " + + "| Total " + + "| Unit Price " + + String.format("|%n%s%n ", SummaryHelper.lineSeparator(subscriptionColSizes, "=")); + subscriptionSummary += SummaryHelper + .arrayToString(this.getSubscription(), subscriptionColSizes); + subscriptionSummary += String + .format("%n%s", SummaryHelper.lineSeparator(subscriptionColSizes, "-")); } - outStr.append( - String.format(":Subscription: %s%n", subscriptionSummary) - ); + outStr.append(String.format(":Subscription: %s%n", subscriptionSummary)); String energyUsageSummary = ""; if (!this.getEnergyUsage().isEmpty()) { - int[] energyUsageColSizes = new int[]{13, 38, 12, 12, 10, 11, 17, 12}; - energyUsageSummary = - String.format("%n%s%n ", SummaryHelper.lineSeparator(energyUsageColSizes, "-")) - + "| Consumption " - + "| Description " - + "| End Date " - + "| Start Date " - + "| Tax Rate " - + "| Total " - + "| Unit of Measure " - + "| Unit Price " - + String.format("|%n%s%n ", SummaryHelper.lineSeparator(energyUsageColSizes, "=")); + int[] energyUsageColSizes = new int[] { 13, 38, 12, 12, 10, 11, 17, 12 }; + energyUsageSummary = String + .format("%n%s%n ", SummaryHelper.lineSeparator(energyUsageColSizes, "-")) + + "| Consumption " + + "| Description " + + "| End Date " + + "| Start Date " + + "| Tax Rate " + + "| Total " + + "| Unit of Measure " + + "| Unit Price " + + String.format("|%n%s%n ", SummaryHelper.lineSeparator(energyUsageColSizes, "=")); energyUsageSummary += SummaryHelper.arrayToString(this.getEnergyUsage(), energyUsageColSizes); - energyUsageSummary += String.format("%n%s", SummaryHelper.lineSeparator(energyUsageColSizes, "-")); + energyUsageSummary += String + .format("%n%s", SummaryHelper.lineSeparator(energyUsageColSizes, "-")); } - outStr.append( - String.format(":Energy Usage: %s%n", energyUsageSummary) - ); + outStr.append(String.format(":Energy Usage: %s%n", energyUsageSummary)); String taxesAndContributionsSummary = ""; if (!this.getTaxesAndContributions().isEmpty()) { - int[] taxesAndContributionsColSizes = new int[]{38, 12, 12, 10, 11, 12}; - taxesAndContributionsSummary = - String.format("%n%s%n ", SummaryHelper.lineSeparator(taxesAndContributionsColSizes, "-")) - + "| Description " - + "| End Date " - + "| Start Date " - + "| Tax Rate " - + "| Total " - + "| Unit Price " - + String.format("|%n%s%n ", SummaryHelper.lineSeparator(taxesAndContributionsColSizes, "=")); - taxesAndContributionsSummary += SummaryHelper.arrayToString(this.getTaxesAndContributions(), taxesAndContributionsColSizes); - taxesAndContributionsSummary += String.format("%n%s", SummaryHelper.lineSeparator(taxesAndContributionsColSizes, "-")); + int[] taxesAndContributionsColSizes = new int[] { 38, 12, 12, 10, 11, 12 }; + taxesAndContributionsSummary = String + .format("%n%s%n ", SummaryHelper.lineSeparator(taxesAndContributionsColSizes, "-")) + + "| Description " + + "| End Date " + + "| Start Date " + + "| Tax Rate " + + "| Total " + + "| Unit Price " + + String + .format("|%n%s%n ", SummaryHelper.lineSeparator(taxesAndContributionsColSizes, "=")); + taxesAndContributionsSummary += SummaryHelper + .arrayToString(this.getTaxesAndContributions(), taxesAndContributionsColSizes); + taxesAndContributionsSummary += String + .format("%n%s", SummaryHelper.lineSeparator(taxesAndContributionsColSizes, "-")); } - outStr.append( - String.format(":Taxes and Contributions: %s%n", taxesAndContributionsSummary) - ); - outStr.append( - String.format(":Meter Details:%n%s", this.getMeterDetails().toFieldList()) - ); + outStr.append(String.format(":Taxes and Contributions: %s%n", taxesAndContributionsSummary)); + outStr.append(String.format(":Meter Details:%n%s", this.getMeterDetails().toFieldList())); return SummaryHelper.cleanSummary(outStr.toString()); } } diff --git a/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1EnergyConsumer.java b/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1EnergyConsumer.java index 1992107f1..f2df3287f 100644 --- a/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1EnergyConsumer.java +++ b/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1EnergyConsumer.java @@ -27,10 +27,7 @@ public class EnergyBillV1EnergyConsumer extends BaseField { String name; public boolean isEmpty() { - return ( - (address == null || address.isEmpty()) - && (name == null || name.isEmpty()) - ); + return ((address == null || address.isEmpty()) && (name == null || name.isEmpty())); } /** @@ -39,7 +36,7 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Address: %s%n", printable.get("address")) - + String.format(" :Name: %s%n", printable.get("name")); + + String.format(" :Name: %s%n", printable.get("name")); } @Override diff --git a/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1EnergySupplier.java b/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1EnergySupplier.java index 08be27989..23b5044b8 100644 --- a/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1EnergySupplier.java +++ b/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1EnergySupplier.java @@ -27,10 +27,7 @@ public class EnergyBillV1EnergySupplier extends BaseField { String name; public boolean isEmpty() { - return ( - (address == null || address.isEmpty()) - && (name == null || name.isEmpty()) - ); + return ((address == null || address.isEmpty()) && (name == null || name.isEmpty())); } /** @@ -39,7 +36,7 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Address: %s%n", printable.get("address")) - + String.format(" :Name: %s%n", printable.get("name")); + + String.format(" :Name: %s%n", printable.get("name")); } @Override diff --git a/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1EnergyUsage.java b/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1EnergyUsage.java index 4bd929a56..1cbbc7169 100644 --- a/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1EnergyUsage.java +++ b/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1EnergyUsage.java @@ -58,41 +58,27 @@ public class EnergyBillV1EnergyUsage extends BaseField implements LineItemField Double unitPrice; public boolean isEmpty() { - return ( - consumption == null - && (description == null || description.isEmpty()) - && (endDate == null || endDate.isEmpty()) - && (startDate == null || startDate.isEmpty()) - && taxRate == null - && total == null - && (unit == null || unit.isEmpty()) - && unitPrice == null - ); + return (consumption == null + && (description == null || description.isEmpty()) + && (endDate == null || endDate.isEmpty()) + && (startDate == null || startDate.isEmpty()) + && taxRate == null + && total == null + && (unit == null || unit.isEmpty()) + && unitPrice == null); } private Map tablePrintableValues() { Map printable = new HashMap<>(); - printable.put( - "consumption", - SummaryHelper.formatAmount(this.consumption) - ); + printable.put("consumption", SummaryHelper.formatAmount(this.consumption)); printable.put("description", SummaryHelper.formatForDisplay(this.description, 36)); printable.put("endDate", SummaryHelper.formatForDisplay(this.endDate, 10)); printable.put("startDate", SummaryHelper.formatForDisplay(this.startDate, null)); - printable.put( - "taxRate", - SummaryHelper.formatAmount(this.taxRate) - ); - printable.put( - "total", - SummaryHelper.formatAmount(this.total) - ); + printable.put("taxRate", SummaryHelper.formatAmount(this.taxRate)); + printable.put("total", SummaryHelper.formatAmount(this.total)); printable.put("unit", SummaryHelper.formatForDisplay(this.unit, null)); - printable.put( - "unitPrice", - SummaryHelper.formatAmount(this.unitPrice) - ); + printable.put("unitPrice", SummaryHelper.formatAmount(this.unitPrice)); return printable; } @@ -127,26 +113,14 @@ public String toString() { private Map printableValues() { Map printable = new HashMap<>(); - printable.put( - "consumption", - SummaryHelper.formatAmount(this.consumption) - ); + printable.put("consumption", SummaryHelper.formatAmount(this.consumption)); printable.put("description", SummaryHelper.formatForDisplay(this.description, null)); printable.put("endDate", SummaryHelper.formatForDisplay(this.endDate, null)); printable.put("startDate", SummaryHelper.formatForDisplay(this.startDate, null)); - printable.put( - "taxRate", - SummaryHelper.formatAmount(this.taxRate) - ); - printable.put( - "total", - SummaryHelper.formatAmount(this.total) - ); + printable.put("taxRate", SummaryHelper.formatAmount(this.taxRate)); + printable.put("total", SummaryHelper.formatAmount(this.total)); printable.put("unit", SummaryHelper.formatForDisplay(this.unit, null)); - printable.put( - "unitPrice", - SummaryHelper.formatAmount(this.unitPrice) - ); + printable.put("unitPrice", SummaryHelper.formatAmount(this.unitPrice)); return printable; } } diff --git a/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1MeterDetail.java b/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1MeterDetail.java index 7e60cd5e9..8cbb0ad3e 100644 --- a/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1MeterDetail.java +++ b/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1MeterDetail.java @@ -32,11 +32,9 @@ public class EnergyBillV1MeterDetail extends BaseField { String unit; public boolean isEmpty() { - return ( - (meterNumber == null || meterNumber.isEmpty()) - && (meterType == null || meterType.isEmpty()) - && (unit == null || unit.isEmpty()) - ); + return ((meterNumber == null || meterNumber.isEmpty()) + && (meterType == null || meterType.isEmpty()) + && (unit == null || unit.isEmpty())); } /** @@ -45,8 +43,8 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Meter Number: %s%n", printable.get("meterNumber")) - + String.format(" :Meter Type: %s%n", printable.get("meterType")) - + String.format(" :Unit of Power: %s%n", printable.get("unit")); + + String.format(" :Meter Type: %s%n", printable.get("meterType")) + + String.format(" :Unit of Power: %s%n", printable.get("unit")); } @Override diff --git a/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1Subscription.java b/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1Subscription.java index 0e5a22843..8759b7974 100644 --- a/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1Subscription.java +++ b/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1Subscription.java @@ -48,14 +48,12 @@ public class EnergyBillV1Subscription extends BaseField implements LineItemField Double unitPrice; public boolean isEmpty() { - return ( - (description == null || description.isEmpty()) - && (endDate == null || endDate.isEmpty()) - && (startDate == null || startDate.isEmpty()) - && taxRate == null - && total == null - && unitPrice == null - ); + return ((description == null || description.isEmpty()) + && (endDate == null || endDate.isEmpty()) + && (startDate == null || startDate.isEmpty()) + && taxRate == null + && total == null + && unitPrice == null); } private Map tablePrintableValues() { @@ -64,18 +62,9 @@ private Map tablePrintableValues() { printable.put("description", SummaryHelper.formatForDisplay(this.description, 36)); printable.put("endDate", SummaryHelper.formatForDisplay(this.endDate, 10)); printable.put("startDate", SummaryHelper.formatForDisplay(this.startDate, null)); - printable.put( - "taxRate", - SummaryHelper.formatAmount(this.taxRate) - ); - printable.put( - "total", - SummaryHelper.formatAmount(this.total) - ); - printable.put( - "unitPrice", - SummaryHelper.formatAmount(this.unitPrice) - ); + printable.put("taxRate", SummaryHelper.formatAmount(this.taxRate)); + printable.put("total", SummaryHelper.formatAmount(this.total)); + printable.put("unitPrice", SummaryHelper.formatAmount(this.unitPrice)); return printable; } @@ -109,18 +98,9 @@ private Map printableValues() { printable.put("description", SummaryHelper.formatForDisplay(this.description, null)); printable.put("endDate", SummaryHelper.formatForDisplay(this.endDate, null)); printable.put("startDate", SummaryHelper.formatForDisplay(this.startDate, null)); - printable.put( - "taxRate", - SummaryHelper.formatAmount(this.taxRate) - ); - printable.put( - "total", - SummaryHelper.formatAmount(this.total) - ); - printable.put( - "unitPrice", - SummaryHelper.formatAmount(this.unitPrice) - ); + printable.put("taxRate", SummaryHelper.formatAmount(this.taxRate)); + printable.put("total", SummaryHelper.formatAmount(this.total)); + printable.put("unitPrice", SummaryHelper.formatAmount(this.unitPrice)); return printable; } } diff --git a/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1TaxesAndContribution.java b/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1TaxesAndContribution.java index 04cd23a78..37f96bc04 100644 --- a/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1TaxesAndContribution.java +++ b/src/main/java/com/mindee/product/fr/energybill/EnergyBillV1TaxesAndContribution.java @@ -48,14 +48,12 @@ public class EnergyBillV1TaxesAndContribution extends BaseField implements LineI Double unitPrice; public boolean isEmpty() { - return ( - (description == null || description.isEmpty()) - && (endDate == null || endDate.isEmpty()) - && (startDate == null || startDate.isEmpty()) - && taxRate == null - && total == null - && unitPrice == null - ); + return ((description == null || description.isEmpty()) + && (endDate == null || endDate.isEmpty()) + && (startDate == null || startDate.isEmpty()) + && taxRate == null + && total == null + && unitPrice == null); } private Map tablePrintableValues() { @@ -64,18 +62,9 @@ private Map tablePrintableValues() { printable.put("description", SummaryHelper.formatForDisplay(this.description, 36)); printable.put("endDate", SummaryHelper.formatForDisplay(this.endDate, 10)); printable.put("startDate", SummaryHelper.formatForDisplay(this.startDate, null)); - printable.put( - "taxRate", - SummaryHelper.formatAmount(this.taxRate) - ); - printable.put( - "total", - SummaryHelper.formatAmount(this.total) - ); - printable.put( - "unitPrice", - SummaryHelper.formatAmount(this.unitPrice) - ); + printable.put("taxRate", SummaryHelper.formatAmount(this.taxRate)); + printable.put("total", SummaryHelper.formatAmount(this.total)); + printable.put("unitPrice", SummaryHelper.formatAmount(this.unitPrice)); return printable; } @@ -109,18 +98,9 @@ private Map printableValues() { printable.put("description", SummaryHelper.formatForDisplay(this.description, null)); printable.put("endDate", SummaryHelper.formatForDisplay(this.endDate, null)); printable.put("startDate", SummaryHelper.formatForDisplay(this.startDate, null)); - printable.put( - "taxRate", - SummaryHelper.formatAmount(this.taxRate) - ); - printable.put( - "total", - SummaryHelper.formatAmount(this.total) - ); - printable.put( - "unitPrice", - SummaryHelper.formatAmount(this.unitPrice) - ); + printable.put("taxRate", SummaryHelper.formatAmount(this.taxRate)); + printable.put("total", SummaryHelper.formatAmount(this.total)); + printable.put("unitPrice", SummaryHelper.formatAmount(this.unitPrice)); return printable; } } diff --git a/src/main/java/com/mindee/product/fr/healthcard/HealthCardV1.java b/src/main/java/com/mindee/product/fr/healthcard/HealthCardV1.java index 7ba93c3a0..dee9fd4b5 100644 --- a/src/main/java/com/mindee/product/fr/healthcard/HealthCardV1.java +++ b/src/main/java/com/mindee/product/fr/healthcard/HealthCardV1.java @@ -11,6 +11,5 @@ @Getter @JsonIgnoreProperties(ignoreUnknown = true) @EndpointInfo(endpointName = "french_healthcard", version = "1") -public class HealthCardV1 - extends Inference { +public class HealthCardV1 extends Inference { } diff --git a/src/main/java/com/mindee/product/fr/healthcard/HealthCardV1Document.java b/src/main/java/com/mindee/product/fr/healthcard/HealthCardV1Document.java index f2395ba97..cf58fe59d 100644 --- a/src/main/java/com/mindee/product/fr/healthcard/HealthCardV1Document.java +++ b/src/main/java/com/mindee/product/fr/healthcard/HealthCardV1Document.java @@ -42,33 +42,20 @@ public class HealthCardV1Document extends Prediction { @Override public boolean isEmpty() { - return ( - (this.givenNames == null || this.givenNames.isEmpty()) + return ((this.givenNames == null || this.givenNames.isEmpty()) && this.surname == null && this.socialSecurity == null - && this.issuanceDate == null - ); + && this.issuanceDate == null); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - String givenNames = SummaryHelper.arrayToString( - this.getGivenNames(), - "%n " - ); - outStr.append( - String.format(":Given Name(s): %s%n", givenNames) - ); - outStr.append( - String.format(":Surname: %s%n", this.getSurname()) - ); - outStr.append( - String.format(":Social Security Number: %s%n", this.getSocialSecurity()) - ); - outStr.append( - String.format(":Issuance Date: %s%n", this.getIssuanceDate()) - ); + String givenNames = SummaryHelper.arrayToString(this.getGivenNames(), "%n "); + outStr.append(String.format(":Given Name(s): %s%n", givenNames)); + outStr.append(String.format(":Surname: %s%n", this.getSurname())); + outStr.append(String.format(":Social Security Number: %s%n", this.getSocialSecurity())); + outStr.append(String.format(":Issuance Date: %s%n", this.getIssuanceDate())); return SummaryHelper.cleanSummary(outStr.toString()); } } diff --git a/src/main/java/com/mindee/product/fr/idcard/IdCardV1.java b/src/main/java/com/mindee/product/fr/idcard/IdCardV1.java index a5ed46aad..af8cda05c 100644 --- a/src/main/java/com/mindee/product/fr/idcard/IdCardV1.java +++ b/src/main/java/com/mindee/product/fr/idcard/IdCardV1.java @@ -11,6 +11,5 @@ @Getter @JsonIgnoreProperties(ignoreUnknown = true) @EndpointInfo(endpointName = "idcard_fr", version = "1") -public class IdCardV1 - extends Inference { +public class IdCardV1 extends Inference { } diff --git a/src/main/java/com/mindee/product/fr/idcard/IdCardV1Document.java b/src/main/java/com/mindee/product/fr/idcard/IdCardV1Document.java index df19ddd79..7af2b21e7 100644 --- a/src/main/java/com/mindee/product/fr/idcard/IdCardV1Document.java +++ b/src/main/java/com/mindee/product/fr/idcard/IdCardV1Document.java @@ -72,8 +72,7 @@ public class IdCardV1Document extends Prediction { @Override public boolean isEmpty() { - return ( - this.idNumber == null + return (this.idNumber == null && (this.givenNames == null || this.givenNames.isEmpty()) && this.surname == null && this.birthDate == null @@ -82,47 +81,23 @@ public boolean isEmpty() { && this.authority == null && this.gender == null && this.mrz1 == null - && this.mrz2 == null - ); + && this.mrz2 == null); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - outStr.append( - String.format(":Identity Number: %s%n", this.getIdNumber()) - ); - String givenNames = SummaryHelper.arrayToString( - this.getGivenNames(), - "%n " - ); - outStr.append( - String.format(":Given Name(s): %s%n", givenNames) - ); - outStr.append( - String.format(":Surname: %s%n", this.getSurname()) - ); - outStr.append( - String.format(":Date of Birth: %s%n", this.getBirthDate()) - ); - outStr.append( - String.format(":Place of Birth: %s%n", this.getBirthPlace()) - ); - outStr.append( - String.format(":Expiry Date: %s%n", this.getExpiryDate()) - ); - outStr.append( - String.format(":Issuing Authority: %s%n", this.getAuthority()) - ); - outStr.append( - String.format(":Gender: %s%n", this.getGender()) - ); - outStr.append( - String.format(":MRZ Line 1: %s%n", this.getMrz1()) - ); - outStr.append( - String.format(":MRZ Line 2: %s%n", this.getMrz2()) - ); + outStr.append(String.format(":Identity Number: %s%n", this.getIdNumber())); + String givenNames = SummaryHelper.arrayToString(this.getGivenNames(), "%n "); + outStr.append(String.format(":Given Name(s): %s%n", givenNames)); + outStr.append(String.format(":Surname: %s%n", this.getSurname())); + outStr.append(String.format(":Date of Birth: %s%n", this.getBirthDate())); + outStr.append(String.format(":Place of Birth: %s%n", this.getBirthPlace())); + outStr.append(String.format(":Expiry Date: %s%n", this.getExpiryDate())); + outStr.append(String.format(":Issuing Authority: %s%n", this.getAuthority())); + outStr.append(String.format(":Gender: %s%n", this.getGender())); + outStr.append(String.format(":MRZ Line 1: %s%n", this.getMrz1())); + outStr.append(String.format(":MRZ Line 2: %s%n", this.getMrz2())); return SummaryHelper.cleanSummary(outStr.toString()); } } diff --git a/src/main/java/com/mindee/product/fr/idcard/IdCardV1Page.java b/src/main/java/com/mindee/product/fr/idcard/IdCardV1Page.java index 1607339e0..3d2b2c58e 100644 --- a/src/main/java/com/mindee/product/fr/idcard/IdCardV1Page.java +++ b/src/main/java/com/mindee/product/fr/idcard/IdCardV1Page.java @@ -23,17 +23,13 @@ public class IdCardV1Page extends IdCardV1Document { @Override public boolean isEmpty() { - return ( - this.documentSide == null - ); + return (this.documentSide == null); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - outStr.append( - String.format(":Document Side: %s%n", this.getDocumentSide()) - ); + outStr.append(String.format(":Document Side: %s%n", this.getDocumentSide())); outStr.append(super.toString()); return SummaryHelper.cleanSummary(outStr.toString()); } diff --git a/src/main/java/com/mindee/product/fr/idcard/IdCardV2.java b/src/main/java/com/mindee/product/fr/idcard/IdCardV2.java index 2d1fca951..feb577e14 100644 --- a/src/main/java/com/mindee/product/fr/idcard/IdCardV2.java +++ b/src/main/java/com/mindee/product/fr/idcard/IdCardV2.java @@ -11,6 +11,5 @@ @Getter @JsonIgnoreProperties(ignoreUnknown = true) @EndpointInfo(endpointName = "idcard_fr", version = "2") -public class IdCardV2 - extends Inference { +public class IdCardV2 extends Inference { } diff --git a/src/main/java/com/mindee/product/fr/idcard/IdCardV2Document.java b/src/main/java/com/mindee/product/fr/idcard/IdCardV2Document.java index 5ce46b75c..54754f6b9 100644 --- a/src/main/java/com/mindee/product/fr/idcard/IdCardV2Document.java +++ b/src/main/java/com/mindee/product/fr/idcard/IdCardV2Document.java @@ -97,8 +97,7 @@ public class IdCardV2Document extends Prediction { @Override public boolean isEmpty() { - return ( - this.nationality == null + return (this.nationality == null && this.cardAccessNumber == null && this.documentNumber == null && (this.givenNames == null || this.givenNames.isEmpty()) @@ -112,62 +111,28 @@ public boolean isEmpty() { && this.mrz2 == null && this.mrz3 == null && this.issueDate == null - && this.authority == null - ); + && this.authority == null); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - outStr.append( - String.format(":Nationality: %s%n", this.getNationality()) - ); - outStr.append( - String.format(":Card Access Number: %s%n", this.getCardAccessNumber()) - ); - outStr.append( - String.format(":Document Number: %s%n", this.getDocumentNumber()) - ); - String givenNames = SummaryHelper.arrayToString( - this.getGivenNames(), - "%n " - ); - outStr.append( - String.format(":Given Name(s): %s%n", givenNames) - ); - outStr.append( - String.format(":Surname: %s%n", this.getSurname()) - ); - outStr.append( - String.format(":Alternate Name: %s%n", this.getAlternateName()) - ); - outStr.append( - String.format(":Date of Birth: %s%n", this.getBirthDate()) - ); - outStr.append( - String.format(":Place of Birth: %s%n", this.getBirthPlace()) - ); - outStr.append( - String.format(":Gender: %s%n", this.getGender()) - ); - outStr.append( - String.format(":Expiry Date: %s%n", this.getExpiryDate()) - ); - outStr.append( - String.format(":Mrz Line 1: %s%n", this.getMrz1()) - ); - outStr.append( - String.format(":Mrz Line 2: %s%n", this.getMrz2()) - ); - outStr.append( - String.format(":Mrz Line 3: %s%n", this.getMrz3()) - ); - outStr.append( - String.format(":Date of Issue: %s%n", this.getIssueDate()) - ); - outStr.append( - String.format(":Issuing Authority: %s%n", this.getAuthority()) - ); + outStr.append(String.format(":Nationality: %s%n", this.getNationality())); + outStr.append(String.format(":Card Access Number: %s%n", this.getCardAccessNumber())); + outStr.append(String.format(":Document Number: %s%n", this.getDocumentNumber())); + String givenNames = SummaryHelper.arrayToString(this.getGivenNames(), "%n "); + outStr.append(String.format(":Given Name(s): %s%n", givenNames)); + outStr.append(String.format(":Surname: %s%n", this.getSurname())); + outStr.append(String.format(":Alternate Name: %s%n", this.getAlternateName())); + outStr.append(String.format(":Date of Birth: %s%n", this.getBirthDate())); + outStr.append(String.format(":Place of Birth: %s%n", this.getBirthPlace())); + outStr.append(String.format(":Gender: %s%n", this.getGender())); + outStr.append(String.format(":Expiry Date: %s%n", this.getExpiryDate())); + outStr.append(String.format(":Mrz Line 1: %s%n", this.getMrz1())); + outStr.append(String.format(":Mrz Line 2: %s%n", this.getMrz2())); + outStr.append(String.format(":Mrz Line 3: %s%n", this.getMrz3())); + outStr.append(String.format(":Date of Issue: %s%n", this.getIssueDate())); + outStr.append(String.format(":Issuing Authority: %s%n", this.getAuthority())); return SummaryHelper.cleanSummary(outStr.toString()); } } diff --git a/src/main/java/com/mindee/product/fr/idcard/IdCardV2Page.java b/src/main/java/com/mindee/product/fr/idcard/IdCardV2Page.java index e26242fbb..e24661128 100644 --- a/src/main/java/com/mindee/product/fr/idcard/IdCardV2Page.java +++ b/src/main/java/com/mindee/product/fr/idcard/IdCardV2Page.java @@ -28,21 +28,14 @@ public class IdCardV2Page extends IdCardV2Document { @Override public boolean isEmpty() { - return ( - this.documentType == null - && this.documentSide == null - ); + return (this.documentType == null && this.documentSide == null); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - outStr.append( - String.format(":Document Type: %s%n", this.getDocumentType()) - ); - outStr.append( - String.format(":Document Sides: %s%n", this.getDocumentSide()) - ); + outStr.append(String.format(":Document Type: %s%n", this.getDocumentType())); + outStr.append(String.format(":Document Sides: %s%n", this.getDocumentSide())); outStr.append(super.toString()); return SummaryHelper.cleanSummary(outStr.toString()); } diff --git a/src/main/java/com/mindee/product/fr/payslip/PayslipV2.java b/src/main/java/com/mindee/product/fr/payslip/PayslipV2.java index c14b743dc..19a9145aa 100644 --- a/src/main/java/com/mindee/product/fr/payslip/PayslipV2.java +++ b/src/main/java/com/mindee/product/fr/payslip/PayslipV2.java @@ -11,6 +11,5 @@ @Getter @JsonIgnoreProperties(ignoreUnknown = true) @EndpointInfo(endpointName = "payslip_fra", version = "2") -public class PayslipV2 - extends Inference { +public class PayslipV2 extends Inference { } diff --git a/src/main/java/com/mindee/product/fr/payslip/PayslipV2BankAccountDetail.java b/src/main/java/com/mindee/product/fr/payslip/PayslipV2BankAccountDetail.java index a5efbfa1b..7469c16df 100644 --- a/src/main/java/com/mindee/product/fr/payslip/PayslipV2BankAccountDetail.java +++ b/src/main/java/com/mindee/product/fr/payslip/PayslipV2BankAccountDetail.java @@ -32,11 +32,9 @@ public class PayslipV2BankAccountDetail extends BaseField { String swift; public boolean isEmpty() { - return ( - (bankName == null || bankName.isEmpty()) - && (iban == null || iban.isEmpty()) - && (swift == null || swift.isEmpty()) - ); + return ((bankName == null || bankName.isEmpty()) + && (iban == null || iban.isEmpty()) + && (swift == null || swift.isEmpty())); } /** @@ -45,8 +43,8 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Bank Name: %s%n", printable.get("bankName")) - + String.format(" :IBAN: %s%n", printable.get("iban")) - + String.format(" :SWIFT: %s%n", printable.get("swift")); + + String.format(" :IBAN: %s%n", printable.get("iban")) + + String.format(" :SWIFT: %s%n", printable.get("swift")); } @Override diff --git a/src/main/java/com/mindee/product/fr/payslip/PayslipV2Document.java b/src/main/java/com/mindee/product/fr/payslip/PayslipV2Document.java index 34800c6fb..debfd219a 100644 --- a/src/main/java/com/mindee/product/fr/payslip/PayslipV2Document.java +++ b/src/main/java/com/mindee/product/fr/payslip/PayslipV2Document.java @@ -60,58 +60,45 @@ public class PayslipV2Document extends Prediction { @Override public boolean isEmpty() { - return ( - this.employee == null + return (this.employee == null && this.employer == null && this.bankAccountDetails == null && this.employment == null && (this.salaryDetails == null || this.salaryDetails.isEmpty()) && this.payDetail == null && this.pto == null - && this.payPeriod == null - ); + && this.payPeriod == null); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - outStr.append( - String.format(":Employee:%n%s", this.getEmployee().toFieldList()) - ); - outStr.append( - String.format(":Employer:%n%s", this.getEmployer().toFieldList()) - ); - outStr.append( + outStr.append(String.format(":Employee:%n%s", this.getEmployee().toFieldList())); + outStr.append(String.format(":Employer:%n%s", this.getEmployer().toFieldList())); + outStr + .append( String.format(":Bank Account Details:%n%s", this.getBankAccountDetails().toFieldList()) - ); - outStr.append( - String.format(":Employment:%n%s", this.getEmployment().toFieldList()) - ); + ); + outStr.append(String.format(":Employment:%n%s", this.getEmployment().toFieldList())); String salaryDetailsSummary = ""; if (!this.getSalaryDetails().isEmpty()) { - int[] salaryDetailsColSizes = new int[]{14, 11, 38, 11}; - salaryDetailsSummary = - String.format("%n%s%n ", SummaryHelper.lineSeparator(salaryDetailsColSizes, "-")) - + "| Amount " - + "| Base " - + "| Description " - + "| Rate " - + String.format("|%n%s%n ", SummaryHelper.lineSeparator(salaryDetailsColSizes, "=")); - salaryDetailsSummary += SummaryHelper.arrayToString(this.getSalaryDetails(), salaryDetailsColSizes); - salaryDetailsSummary += String.format("%n%s", SummaryHelper.lineSeparator(salaryDetailsColSizes, "-")); + int[] salaryDetailsColSizes = new int[] { 14, 11, 38, 11 }; + salaryDetailsSummary = String + .format("%n%s%n ", SummaryHelper.lineSeparator(salaryDetailsColSizes, "-")) + + "| Amount " + + "| Base " + + "| Description " + + "| Rate " + + String.format("|%n%s%n ", SummaryHelper.lineSeparator(salaryDetailsColSizes, "=")); + salaryDetailsSummary += SummaryHelper + .arrayToString(this.getSalaryDetails(), salaryDetailsColSizes); + salaryDetailsSummary += String + .format("%n%s", SummaryHelper.lineSeparator(salaryDetailsColSizes, "-")); } - outStr.append( - String.format(":Salary Details: %s%n", salaryDetailsSummary) - ); - outStr.append( - String.format(":Pay Detail:%n%s", this.getPayDetail().toFieldList()) - ); - outStr.append( - String.format(":PTO:%n%s", this.getPto().toFieldList()) - ); - outStr.append( - String.format(":Pay Period:%n%s", this.getPayPeriod().toFieldList()) - ); + outStr.append(String.format(":Salary Details: %s%n", salaryDetailsSummary)); + outStr.append(String.format(":Pay Detail:%n%s", this.getPayDetail().toFieldList())); + outStr.append(String.format(":PTO:%n%s", this.getPto().toFieldList())); + outStr.append(String.format(":Pay Period:%n%s", this.getPayPeriod().toFieldList())); return SummaryHelper.cleanSummary(outStr.toString()); } } diff --git a/src/main/java/com/mindee/product/fr/payslip/PayslipV2Employee.java b/src/main/java/com/mindee/product/fr/payslip/PayslipV2Employee.java index 950d42cf8..4743ef638 100644 --- a/src/main/java/com/mindee/product/fr/payslip/PayslipV2Employee.java +++ b/src/main/java/com/mindee/product/fr/payslip/PayslipV2Employee.java @@ -52,15 +52,13 @@ public class PayslipV2Employee extends BaseField { String socialSecurityNumber; public boolean isEmpty() { - return ( - (address == null || address.isEmpty()) - && (dateOfBirth == null || dateOfBirth.isEmpty()) - && (firstName == null || firstName.isEmpty()) - && (lastName == null || lastName.isEmpty()) - && (phoneNumber == null || phoneNumber.isEmpty()) - && (registrationNumber == null || registrationNumber.isEmpty()) - && (socialSecurityNumber == null || socialSecurityNumber.isEmpty()) - ); + return ((address == null || address.isEmpty()) + && (dateOfBirth == null || dateOfBirth.isEmpty()) + && (firstName == null || firstName.isEmpty()) + && (lastName == null || lastName.isEmpty()) + && (phoneNumber == null || phoneNumber.isEmpty()) + && (registrationNumber == null || registrationNumber.isEmpty()) + && (socialSecurityNumber == null || socialSecurityNumber.isEmpty())); } /** @@ -69,12 +67,12 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Address: %s%n", printable.get("address")) - + String.format(" :Date of Birth: %s%n", printable.get("dateOfBirth")) - + String.format(" :First Name: %s%n", printable.get("firstName")) - + String.format(" :Last Name: %s%n", printable.get("lastName")) - + String.format(" :Phone Number: %s%n", printable.get("phoneNumber")) - + String.format(" :Registration Number: %s%n", printable.get("registrationNumber")) - + String.format(" :Social Security Number: %s%n", printable.get("socialSecurityNumber")); + + String.format(" :Date of Birth: %s%n", printable.get("dateOfBirth")) + + String.format(" :First Name: %s%n", printable.get("firstName")) + + String.format(" :Last Name: %s%n", printable.get("lastName")) + + String.format(" :Phone Number: %s%n", printable.get("phoneNumber")) + + String.format(" :Registration Number: %s%n", printable.get("registrationNumber")) + + String.format(" :Social Security Number: %s%n", printable.get("socialSecurityNumber")); } @Override @@ -97,8 +95,10 @@ private Map printableValues() { printable.put("firstName", SummaryHelper.formatForDisplay(this.firstName, null)); printable.put("lastName", SummaryHelper.formatForDisplay(this.lastName, null)); printable.put("phoneNumber", SummaryHelper.formatForDisplay(this.phoneNumber, null)); - printable.put("registrationNumber", SummaryHelper.formatForDisplay(this.registrationNumber, null)); - printable.put("socialSecurityNumber", SummaryHelper.formatForDisplay(this.socialSecurityNumber, null)); + printable + .put("registrationNumber", SummaryHelper.formatForDisplay(this.registrationNumber, null)); + printable + .put("socialSecurityNumber", SummaryHelper.formatForDisplay(this.socialSecurityNumber, null)); return printable; } } diff --git a/src/main/java/com/mindee/product/fr/payslip/PayslipV2Employer.java b/src/main/java/com/mindee/product/fr/payslip/PayslipV2Employer.java index d0f3856a2..2ddbbb317 100644 --- a/src/main/java/com/mindee/product/fr/payslip/PayslipV2Employer.java +++ b/src/main/java/com/mindee/product/fr/payslip/PayslipV2Employer.java @@ -52,15 +52,13 @@ public class PayslipV2Employer extends BaseField { String urssafNumber; public boolean isEmpty() { - return ( - (address == null || address.isEmpty()) - && (companyId == null || companyId.isEmpty()) - && (companySite == null || companySite.isEmpty()) - && (nafCode == null || nafCode.isEmpty()) - && (name == null || name.isEmpty()) - && (phoneNumber == null || phoneNumber.isEmpty()) - && (urssafNumber == null || urssafNumber.isEmpty()) - ); + return ((address == null || address.isEmpty()) + && (companyId == null || companyId.isEmpty()) + && (companySite == null || companySite.isEmpty()) + && (nafCode == null || nafCode.isEmpty()) + && (name == null || name.isEmpty()) + && (phoneNumber == null || phoneNumber.isEmpty()) + && (urssafNumber == null || urssafNumber.isEmpty())); } /** @@ -69,12 +67,12 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Address: %s%n", printable.get("address")) - + String.format(" :Company ID: %s%n", printable.get("companyId")) - + String.format(" :Company Site: %s%n", printable.get("companySite")) - + String.format(" :NAF Code: %s%n", printable.get("nafCode")) - + String.format(" :Name: %s%n", printable.get("name")) - + String.format(" :Phone Number: %s%n", printable.get("phoneNumber")) - + String.format(" :URSSAF Number: %s%n", printable.get("urssafNumber")); + + String.format(" :Company ID: %s%n", printable.get("companyId")) + + String.format(" :Company Site: %s%n", printable.get("companySite")) + + String.format(" :NAF Code: %s%n", printable.get("nafCode")) + + String.format(" :Name: %s%n", printable.get("name")) + + String.format(" :Phone Number: %s%n", printable.get("phoneNumber")) + + String.format(" :URSSAF Number: %s%n", printable.get("urssafNumber")); } @Override diff --git a/src/main/java/com/mindee/product/fr/payslip/PayslipV2Employment.java b/src/main/java/com/mindee/product/fr/payslip/PayslipV2Employment.java index 72c4e5ab4..ec49bfcc1 100644 --- a/src/main/java/com/mindee/product/fr/payslip/PayslipV2Employment.java +++ b/src/main/java/com/mindee/product/fr/payslip/PayslipV2Employment.java @@ -47,14 +47,12 @@ public class PayslipV2Employment extends BaseField { String startDate; public boolean isEmpty() { - return ( - (category == null || category.isEmpty()) - && coefficient == null - && (collectiveAgreement == null || collectiveAgreement.isEmpty()) - && (jobTitle == null || jobTitle.isEmpty()) - && (positionLevel == null || positionLevel.isEmpty()) - && (startDate == null || startDate.isEmpty()) - ); + return ((category == null || category.isEmpty()) + && coefficient == null + && (collectiveAgreement == null || collectiveAgreement.isEmpty()) + && (jobTitle == null || jobTitle.isEmpty()) + && (positionLevel == null || positionLevel.isEmpty()) + && (startDate == null || startDate.isEmpty())); } /** @@ -63,11 +61,11 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Category: %s%n", printable.get("category")) - + String.format(" :Coefficient: %s%n", printable.get("coefficient")) - + String.format(" :Collective Agreement: %s%n", printable.get("collectiveAgreement")) - + String.format(" :Job Title: %s%n", printable.get("jobTitle")) - + String.format(" :Position Level: %s%n", printable.get("positionLevel")) - + String.format(" :Start Date: %s%n", printable.get("startDate")); + + String.format(" :Coefficient: %s%n", printable.get("coefficient")) + + String.format(" :Collective Agreement: %s%n", printable.get("collectiveAgreement")) + + String.format(" :Job Title: %s%n", printable.get("jobTitle")) + + String.format(" :Position Level: %s%n", printable.get("positionLevel")) + + String.format(" :Start Date: %s%n", printable.get("startDate")); } @Override @@ -85,11 +83,9 @@ private Map printableValues() { Map printable = new HashMap<>(); printable.put("category", SummaryHelper.formatForDisplay(this.category, null)); - printable.put( - "coefficient", - SummaryHelper.formatAmount(this.coefficient) - ); - printable.put("collectiveAgreement", SummaryHelper.formatForDisplay(this.collectiveAgreement, null)); + printable.put("coefficient", SummaryHelper.formatAmount(this.coefficient)); + printable + .put("collectiveAgreement", SummaryHelper.formatForDisplay(this.collectiveAgreement, null)); printable.put("jobTitle", SummaryHelper.formatForDisplay(this.jobTitle, null)); printable.put("positionLevel", SummaryHelper.formatForDisplay(this.positionLevel, null)); printable.put("startDate", SummaryHelper.formatForDisplay(this.startDate, null)); diff --git a/src/main/java/com/mindee/product/fr/payslip/PayslipV2PayDetail.java b/src/main/java/com/mindee/product/fr/payslip/PayslipV2PayDetail.java index 8117460e4..d309622e5 100644 --- a/src/main/java/com/mindee/product/fr/payslip/PayslipV2PayDetail.java +++ b/src/main/java/com/mindee/product/fr/payslip/PayslipV2PayDetail.java @@ -67,18 +67,16 @@ public class PayslipV2PayDetail extends BaseField { Double totalTaxesAndDeductions; public boolean isEmpty() { - return ( - grossSalary == null - && grossSalaryYtd == null - && incomeTaxRate == null - && incomeTaxWithheld == null - && netPaid == null - && netPaidBeforeTax == null - && netTaxable == null - && netTaxableYtd == null - && totalCostEmployer == null - && totalTaxesAndDeductions == null - ); + return (grossSalary == null + && grossSalaryYtd == null + && incomeTaxRate == null + && incomeTaxWithheld == null + && netPaid == null + && netPaidBeforeTax == null + && netTaxable == null + && netTaxableYtd == null + && totalCostEmployer == null + && totalTaxesAndDeductions == null); } /** @@ -87,15 +85,16 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Gross Salary: %s%n", printable.get("grossSalary")) - + String.format(" :Gross Salary YTD: %s%n", printable.get("grossSalaryYtd")) - + String.format(" :Income Tax Rate: %s%n", printable.get("incomeTaxRate")) - + String.format(" :Income Tax Withheld: %s%n", printable.get("incomeTaxWithheld")) - + String.format(" :Net Paid: %s%n", printable.get("netPaid")) - + String.format(" :Net Paid Before Tax: %s%n", printable.get("netPaidBeforeTax")) - + String.format(" :Net Taxable: %s%n", printable.get("netTaxable")) - + String.format(" :Net Taxable YTD: %s%n", printable.get("netTaxableYtd")) - + String.format(" :Total Cost Employer: %s%n", printable.get("totalCostEmployer")) - + String.format(" :Total Taxes and Deductions: %s%n", printable.get("totalTaxesAndDeductions")); + + String.format(" :Gross Salary YTD: %s%n", printable.get("grossSalaryYtd")) + + String.format(" :Income Tax Rate: %s%n", printable.get("incomeTaxRate")) + + String.format(" :Income Tax Withheld: %s%n", printable.get("incomeTaxWithheld")) + + String.format(" :Net Paid: %s%n", printable.get("netPaid")) + + String.format(" :Net Paid Before Tax: %s%n", printable.get("netPaidBeforeTax")) + + String.format(" :Net Taxable: %s%n", printable.get("netTaxable")) + + String.format(" :Net Taxable YTD: %s%n", printable.get("netTaxableYtd")) + + String.format(" :Total Cost Employer: %s%n", printable.get("totalCostEmployer")) + + String + .format(" :Total Taxes and Deductions: %s%n", printable.get("totalTaxesAndDeductions")); } @Override @@ -116,46 +115,17 @@ public String toString() { private Map printableValues() { Map printable = new HashMap<>(); - printable.put( - "grossSalary", - SummaryHelper.formatAmount(this.grossSalary) - ); - printable.put( - "grossSalaryYtd", - SummaryHelper.formatAmount(this.grossSalaryYtd) - ); - printable.put( - "incomeTaxRate", - SummaryHelper.formatAmount(this.incomeTaxRate) - ); - printable.put( - "incomeTaxWithheld", - SummaryHelper.formatAmount(this.incomeTaxWithheld) - ); - printable.put( - "netPaid", - SummaryHelper.formatAmount(this.netPaid) - ); - printable.put( - "netPaidBeforeTax", - SummaryHelper.formatAmount(this.netPaidBeforeTax) - ); - printable.put( - "netTaxable", - SummaryHelper.formatAmount(this.netTaxable) - ); - printable.put( - "netTaxableYtd", - SummaryHelper.formatAmount(this.netTaxableYtd) - ); - printable.put( - "totalCostEmployer", - SummaryHelper.formatAmount(this.totalCostEmployer) - ); - printable.put( - "totalTaxesAndDeductions", - SummaryHelper.formatAmount(this.totalTaxesAndDeductions) - ); + printable.put("grossSalary", SummaryHelper.formatAmount(this.grossSalary)); + printable.put("grossSalaryYtd", SummaryHelper.formatAmount(this.grossSalaryYtd)); + printable.put("incomeTaxRate", SummaryHelper.formatAmount(this.incomeTaxRate)); + printable.put("incomeTaxWithheld", SummaryHelper.formatAmount(this.incomeTaxWithheld)); + printable.put("netPaid", SummaryHelper.formatAmount(this.netPaid)); + printable.put("netPaidBeforeTax", SummaryHelper.formatAmount(this.netPaidBeforeTax)); + printable.put("netTaxable", SummaryHelper.formatAmount(this.netTaxable)); + printable.put("netTaxableYtd", SummaryHelper.formatAmount(this.netTaxableYtd)); + printable.put("totalCostEmployer", SummaryHelper.formatAmount(this.totalCostEmployer)); + printable + .put("totalTaxesAndDeductions", SummaryHelper.formatAmount(this.totalTaxesAndDeductions)); return printable; } } diff --git a/src/main/java/com/mindee/product/fr/payslip/PayslipV2PayPeriod.java b/src/main/java/com/mindee/product/fr/payslip/PayslipV2PayPeriod.java index 55aeb3998..89a3c28d7 100644 --- a/src/main/java/com/mindee/product/fr/payslip/PayslipV2PayPeriod.java +++ b/src/main/java/com/mindee/product/fr/payslip/PayslipV2PayPeriod.java @@ -42,13 +42,11 @@ public class PayslipV2PayPeriod extends BaseField { String year; public boolean isEmpty() { - return ( - (endDate == null || endDate.isEmpty()) - && (month == null || month.isEmpty()) - && (paymentDate == null || paymentDate.isEmpty()) - && (startDate == null || startDate.isEmpty()) - && (year == null || year.isEmpty()) - ); + return ((endDate == null || endDate.isEmpty()) + && (month == null || month.isEmpty()) + && (paymentDate == null || paymentDate.isEmpty()) + && (startDate == null || startDate.isEmpty()) + && (year == null || year.isEmpty())); } /** @@ -57,10 +55,10 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :End Date: %s%n", printable.get("endDate")) - + String.format(" :Month: %s%n", printable.get("month")) - + String.format(" :Payment Date: %s%n", printable.get("paymentDate")) - + String.format(" :Start Date: %s%n", printable.get("startDate")) - + String.format(" :Year: %s%n", printable.get("year")); + + String.format(" :Month: %s%n", printable.get("month")) + + String.format(" :Payment Date: %s%n", printable.get("paymentDate")) + + String.format(" :Start Date: %s%n", printable.get("startDate")) + + String.format(" :Year: %s%n", printable.get("year")); } @Override diff --git a/src/main/java/com/mindee/product/fr/payslip/PayslipV2Pto.java b/src/main/java/com/mindee/product/fr/payslip/PayslipV2Pto.java index c88e3bbc3..7189ea27f 100644 --- a/src/main/java/com/mindee/product/fr/payslip/PayslipV2Pto.java +++ b/src/main/java/com/mindee/product/fr/payslip/PayslipV2Pto.java @@ -32,11 +32,7 @@ public class PayslipV2Pto extends BaseField { Double usedThisPeriod; public boolean isEmpty() { - return ( - accruedThisPeriod == null - && balanceEndOfPeriod == null - && usedThisPeriod == null - ); + return (accruedThisPeriod == null && balanceEndOfPeriod == null && usedThisPeriod == null); } /** @@ -45,8 +41,8 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Accrued This Period: %s%n", printable.get("accruedThisPeriod")) - + String.format(" :Balance End of Period: %s%n", printable.get("balanceEndOfPeriod")) - + String.format(" :Used This Period: %s%n", printable.get("usedThisPeriod")); + + String.format(" :Balance End of Period: %s%n", printable.get("balanceEndOfPeriod")) + + String.format(" :Used This Period: %s%n", printable.get("usedThisPeriod")); } @Override @@ -60,18 +56,9 @@ public String toString() { private Map printableValues() { Map printable = new HashMap<>(); - printable.put( - "accruedThisPeriod", - SummaryHelper.formatAmount(this.accruedThisPeriod) - ); - printable.put( - "balanceEndOfPeriod", - SummaryHelper.formatAmount(this.balanceEndOfPeriod) - ); - printable.put( - "usedThisPeriod", - SummaryHelper.formatAmount(this.usedThisPeriod) - ); + printable.put("accruedThisPeriod", SummaryHelper.formatAmount(this.accruedThisPeriod)); + printable.put("balanceEndOfPeriod", SummaryHelper.formatAmount(this.balanceEndOfPeriod)); + printable.put("usedThisPeriod", SummaryHelper.formatAmount(this.usedThisPeriod)); return printable; } } diff --git a/src/main/java/com/mindee/product/fr/payslip/PayslipV2SalaryDetail.java b/src/main/java/com/mindee/product/fr/payslip/PayslipV2SalaryDetail.java index 0448182a5..b6729b837 100644 --- a/src/main/java/com/mindee/product/fr/payslip/PayslipV2SalaryDetail.java +++ b/src/main/java/com/mindee/product/fr/payslip/PayslipV2SalaryDetail.java @@ -38,30 +38,19 @@ public class PayslipV2SalaryDetail extends BaseField implements LineItemField { Double rate; public boolean isEmpty() { - return ( - amount == null - && base == null - && (description == null || description.isEmpty()) - && rate == null - ); + return (amount == null + && base == null + && (description == null || description.isEmpty()) + && rate == null); } private Map tablePrintableValues() { Map printable = new HashMap<>(); - printable.put( - "amount", - SummaryHelper.formatAmount(this.amount) - ); - printable.put( - "base", - SummaryHelper.formatAmount(this.base) - ); + printable.put("amount", SummaryHelper.formatAmount(this.amount)); + printable.put("base", SummaryHelper.formatAmount(this.base)); printable.put("description", SummaryHelper.formatForDisplay(this.description, 36)); - printable.put( - "rate", - SummaryHelper.formatAmount(this.rate) - ); + printable.put("rate", SummaryHelper.formatAmount(this.rate)); return printable; } @@ -88,19 +77,10 @@ public String toString() { private Map printableValues() { Map printable = new HashMap<>(); - printable.put( - "amount", - SummaryHelper.formatAmount(this.amount) - ); - printable.put( - "base", - SummaryHelper.formatAmount(this.base) - ); + printable.put("amount", SummaryHelper.formatAmount(this.amount)); + printable.put("base", SummaryHelper.formatAmount(this.base)); printable.put("description", SummaryHelper.formatForDisplay(this.description, null)); - printable.put( - "rate", - SummaryHelper.formatAmount(this.rate) - ); + printable.put("rate", SummaryHelper.formatAmount(this.rate)); return printable; } } diff --git a/src/main/java/com/mindee/product/fr/payslip/PayslipV3.java b/src/main/java/com/mindee/product/fr/payslip/PayslipV3.java index b9f60aa87..f0b989d5d 100644 --- a/src/main/java/com/mindee/product/fr/payslip/PayslipV3.java +++ b/src/main/java/com/mindee/product/fr/payslip/PayslipV3.java @@ -11,6 +11,5 @@ @Getter @JsonIgnoreProperties(ignoreUnknown = true) @EndpointInfo(endpointName = "payslip_fra", version = "3") -public class PayslipV3 - extends Inference { +public class PayslipV3 extends Inference { } diff --git a/src/main/java/com/mindee/product/fr/payslip/PayslipV3BankAccountDetail.java b/src/main/java/com/mindee/product/fr/payslip/PayslipV3BankAccountDetail.java index 7240026f6..81e1de6c4 100644 --- a/src/main/java/com/mindee/product/fr/payslip/PayslipV3BankAccountDetail.java +++ b/src/main/java/com/mindee/product/fr/payslip/PayslipV3BankAccountDetail.java @@ -32,11 +32,9 @@ public class PayslipV3BankAccountDetail extends BaseField { String swift; public boolean isEmpty() { - return ( - (bankName == null || bankName.isEmpty()) - && (iban == null || iban.isEmpty()) - && (swift == null || swift.isEmpty()) - ); + return ((bankName == null || bankName.isEmpty()) + && (iban == null || iban.isEmpty()) + && (swift == null || swift.isEmpty())); } /** @@ -45,8 +43,8 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Bank Name: %s%n", printable.get("bankName")) - + String.format(" :IBAN: %s%n", printable.get("iban")) - + String.format(" :SWIFT: %s%n", printable.get("swift")); + + String.format(" :IBAN: %s%n", printable.get("iban")) + + String.format(" :SWIFT: %s%n", printable.get("swift")); } @Override diff --git a/src/main/java/com/mindee/product/fr/payslip/PayslipV3Document.java b/src/main/java/com/mindee/product/fr/payslip/PayslipV3Document.java index 7ad3480f0..c8317d599 100644 --- a/src/main/java/com/mindee/product/fr/payslip/PayslipV3Document.java +++ b/src/main/java/com/mindee/product/fr/payslip/PayslipV3Document.java @@ -60,73 +60,61 @@ public class PayslipV3Document extends Prediction { @Override public boolean isEmpty() { - return ( - this.payPeriod == null + return (this.payPeriod == null && this.employee == null && this.employer == null && this.bankAccountDetails == null && this.employment == null && (this.salaryDetails == null || this.salaryDetails.isEmpty()) && this.payDetail == null - && (this.paidTimeOff == null || this.paidTimeOff.isEmpty()) - ); + && (this.paidTimeOff == null || this.paidTimeOff.isEmpty())); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - outStr.append( - String.format(":Pay Period:%n%s", this.getPayPeriod().toFieldList()) - ); - outStr.append( - String.format(":Employee:%n%s", this.getEmployee().toFieldList()) - ); - outStr.append( - String.format(":Employer:%n%s", this.getEmployer().toFieldList()) - ); - outStr.append( + outStr.append(String.format(":Pay Period:%n%s", this.getPayPeriod().toFieldList())); + outStr.append(String.format(":Employee:%n%s", this.getEmployee().toFieldList())); + outStr.append(String.format(":Employer:%n%s", this.getEmployer().toFieldList())); + outStr + .append( String.format(":Bank Account Details:%n%s", this.getBankAccountDetails().toFieldList()) - ); - outStr.append( - String.format(":Employment:%n%s", this.getEmployment().toFieldList()) - ); + ); + outStr.append(String.format(":Employment:%n%s", this.getEmployment().toFieldList())); String salaryDetailsSummary = ""; if (!this.getSalaryDetails().isEmpty()) { - int[] salaryDetailsColSizes = new int[]{14, 11, 38, 8, 11}; - salaryDetailsSummary = - String.format("%n%s%n ", SummaryHelper.lineSeparator(salaryDetailsColSizes, "-")) - + "| Amount " - + "| Base " - + "| Description " - + "| Number " - + "| Rate " - + String.format("|%n%s%n ", SummaryHelper.lineSeparator(salaryDetailsColSizes, "=")); - salaryDetailsSummary += SummaryHelper.arrayToString(this.getSalaryDetails(), salaryDetailsColSizes); - salaryDetailsSummary += String.format("%n%s", SummaryHelper.lineSeparator(salaryDetailsColSizes, "-")); + int[] salaryDetailsColSizes = new int[] { 14, 11, 38, 8, 11 }; + salaryDetailsSummary = String + .format("%n%s%n ", SummaryHelper.lineSeparator(salaryDetailsColSizes, "-")) + + "| Amount " + + "| Base " + + "| Description " + + "| Number " + + "| Rate " + + String.format("|%n%s%n ", SummaryHelper.lineSeparator(salaryDetailsColSizes, "=")); + salaryDetailsSummary += SummaryHelper + .arrayToString(this.getSalaryDetails(), salaryDetailsColSizes); + salaryDetailsSummary += String + .format("%n%s", SummaryHelper.lineSeparator(salaryDetailsColSizes, "-")); } - outStr.append( - String.format(":Salary Details: %s%n", salaryDetailsSummary) - ); - outStr.append( - String.format(":Pay Detail:%n%s", this.getPayDetail().toFieldList()) - ); + outStr.append(String.format(":Salary Details: %s%n", salaryDetailsSummary)); + outStr.append(String.format(":Pay Detail:%n%s", this.getPayDetail().toFieldList())); String paidTimeOffSummary = ""; if (!this.getPaidTimeOff().isEmpty()) { - int[] paidTimeOffColSizes = new int[]{11, 8, 13, 11, 11}; - paidTimeOffSummary = - String.format("%n%s%n ", SummaryHelper.lineSeparator(paidTimeOffColSizes, "-")) - + "| Accrued " - + "| Period " - + "| Type " - + "| Remaining " - + "| Used " - + String.format("|%n%s%n ", SummaryHelper.lineSeparator(paidTimeOffColSizes, "=")); + int[] paidTimeOffColSizes = new int[] { 11, 8, 13, 11, 11 }; + paidTimeOffSummary = String + .format("%n%s%n ", SummaryHelper.lineSeparator(paidTimeOffColSizes, "-")) + + "| Accrued " + + "| Period " + + "| Type " + + "| Remaining " + + "| Used " + + String.format("|%n%s%n ", SummaryHelper.lineSeparator(paidTimeOffColSizes, "=")); paidTimeOffSummary += SummaryHelper.arrayToString(this.getPaidTimeOff(), paidTimeOffColSizes); - paidTimeOffSummary += String.format("%n%s", SummaryHelper.lineSeparator(paidTimeOffColSizes, "-")); + paidTimeOffSummary += String + .format("%n%s", SummaryHelper.lineSeparator(paidTimeOffColSizes, "-")); } - outStr.append( - String.format(":Paid Time Off: %s%n", paidTimeOffSummary) - ); + outStr.append(String.format(":Paid Time Off: %s%n", paidTimeOffSummary)); return SummaryHelper.cleanSummary(outStr.toString()); } } diff --git a/src/main/java/com/mindee/product/fr/payslip/PayslipV3Employee.java b/src/main/java/com/mindee/product/fr/payslip/PayslipV3Employee.java index 444d32a0f..4d97365b6 100644 --- a/src/main/java/com/mindee/product/fr/payslip/PayslipV3Employee.java +++ b/src/main/java/com/mindee/product/fr/payslip/PayslipV3Employee.java @@ -52,15 +52,13 @@ public class PayslipV3Employee extends BaseField { String socialSecurityNumber; public boolean isEmpty() { - return ( - (address == null || address.isEmpty()) - && (dateOfBirth == null || dateOfBirth.isEmpty()) - && (firstName == null || firstName.isEmpty()) - && (lastName == null || lastName.isEmpty()) - && (phoneNumber == null || phoneNumber.isEmpty()) - && (registrationNumber == null || registrationNumber.isEmpty()) - && (socialSecurityNumber == null || socialSecurityNumber.isEmpty()) - ); + return ((address == null || address.isEmpty()) + && (dateOfBirth == null || dateOfBirth.isEmpty()) + && (firstName == null || firstName.isEmpty()) + && (lastName == null || lastName.isEmpty()) + && (phoneNumber == null || phoneNumber.isEmpty()) + && (registrationNumber == null || registrationNumber.isEmpty()) + && (socialSecurityNumber == null || socialSecurityNumber.isEmpty())); } /** @@ -69,12 +67,12 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Address: %s%n", printable.get("address")) - + String.format(" :Date of Birth: %s%n", printable.get("dateOfBirth")) - + String.format(" :First Name: %s%n", printable.get("firstName")) - + String.format(" :Last Name: %s%n", printable.get("lastName")) - + String.format(" :Phone Number: %s%n", printable.get("phoneNumber")) - + String.format(" :Registration Number: %s%n", printable.get("registrationNumber")) - + String.format(" :Social Security Number: %s%n", printable.get("socialSecurityNumber")); + + String.format(" :Date of Birth: %s%n", printable.get("dateOfBirth")) + + String.format(" :First Name: %s%n", printable.get("firstName")) + + String.format(" :Last Name: %s%n", printable.get("lastName")) + + String.format(" :Phone Number: %s%n", printable.get("phoneNumber")) + + String.format(" :Registration Number: %s%n", printable.get("registrationNumber")) + + String.format(" :Social Security Number: %s%n", printable.get("socialSecurityNumber")); } @Override @@ -97,8 +95,10 @@ private Map printableValues() { printable.put("firstName", SummaryHelper.formatForDisplay(this.firstName, null)); printable.put("lastName", SummaryHelper.formatForDisplay(this.lastName, null)); printable.put("phoneNumber", SummaryHelper.formatForDisplay(this.phoneNumber, null)); - printable.put("registrationNumber", SummaryHelper.formatForDisplay(this.registrationNumber, null)); - printable.put("socialSecurityNumber", SummaryHelper.formatForDisplay(this.socialSecurityNumber, null)); + printable + .put("registrationNumber", SummaryHelper.formatForDisplay(this.registrationNumber, null)); + printable + .put("socialSecurityNumber", SummaryHelper.formatForDisplay(this.socialSecurityNumber, null)); return printable; } } diff --git a/src/main/java/com/mindee/product/fr/payslip/PayslipV3Employer.java b/src/main/java/com/mindee/product/fr/payslip/PayslipV3Employer.java index 99e9f70e7..2a1999bb2 100644 --- a/src/main/java/com/mindee/product/fr/payslip/PayslipV3Employer.java +++ b/src/main/java/com/mindee/product/fr/payslip/PayslipV3Employer.java @@ -52,15 +52,13 @@ public class PayslipV3Employer extends BaseField { String urssafNumber; public boolean isEmpty() { - return ( - (address == null || address.isEmpty()) - && (companyId == null || companyId.isEmpty()) - && (companySite == null || companySite.isEmpty()) - && (nafCode == null || nafCode.isEmpty()) - && (name == null || name.isEmpty()) - && (phoneNumber == null || phoneNumber.isEmpty()) - && (urssafNumber == null || urssafNumber.isEmpty()) - ); + return ((address == null || address.isEmpty()) + && (companyId == null || companyId.isEmpty()) + && (companySite == null || companySite.isEmpty()) + && (nafCode == null || nafCode.isEmpty()) + && (name == null || name.isEmpty()) + && (phoneNumber == null || phoneNumber.isEmpty()) + && (urssafNumber == null || urssafNumber.isEmpty())); } /** @@ -69,12 +67,12 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Address: %s%n", printable.get("address")) - + String.format(" :Company ID: %s%n", printable.get("companyId")) - + String.format(" :Company Site: %s%n", printable.get("companySite")) - + String.format(" :NAF Code: %s%n", printable.get("nafCode")) - + String.format(" :Name: %s%n", printable.get("name")) - + String.format(" :Phone Number: %s%n", printable.get("phoneNumber")) - + String.format(" :URSSAF Number: %s%n", printable.get("urssafNumber")); + + String.format(" :Company ID: %s%n", printable.get("companyId")) + + String.format(" :Company Site: %s%n", printable.get("companySite")) + + String.format(" :NAF Code: %s%n", printable.get("nafCode")) + + String.format(" :Name: %s%n", printable.get("name")) + + String.format(" :Phone Number: %s%n", printable.get("phoneNumber")) + + String.format(" :URSSAF Number: %s%n", printable.get("urssafNumber")); } @Override diff --git a/src/main/java/com/mindee/product/fr/payslip/PayslipV3Employment.java b/src/main/java/com/mindee/product/fr/payslip/PayslipV3Employment.java index 311d69aba..3ff48d488 100644 --- a/src/main/java/com/mindee/product/fr/payslip/PayslipV3Employment.java +++ b/src/main/java/com/mindee/product/fr/payslip/PayslipV3Employment.java @@ -52,15 +52,13 @@ public class PayslipV3Employment extends BaseField { String startDate; public boolean isEmpty() { - return ( - (category == null || category.isEmpty()) - && (coefficient == null || coefficient.isEmpty()) - && (collectiveAgreement == null || collectiveAgreement.isEmpty()) - && (jobTitle == null || jobTitle.isEmpty()) - && (positionLevel == null || positionLevel.isEmpty()) - && (seniorityDate == null || seniorityDate.isEmpty()) - && (startDate == null || startDate.isEmpty()) - ); + return ((category == null || category.isEmpty()) + && (coefficient == null || coefficient.isEmpty()) + && (collectiveAgreement == null || collectiveAgreement.isEmpty()) + && (jobTitle == null || jobTitle.isEmpty()) + && (positionLevel == null || positionLevel.isEmpty()) + && (seniorityDate == null || seniorityDate.isEmpty()) + && (startDate == null || startDate.isEmpty())); } /** @@ -69,12 +67,12 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Category: %s%n", printable.get("category")) - + String.format(" :Coefficient: %s%n", printable.get("coefficient")) - + String.format(" :Collective Agreement: %s%n", printable.get("collectiveAgreement")) - + String.format(" :Job Title: %s%n", printable.get("jobTitle")) - + String.format(" :Position Level: %s%n", printable.get("positionLevel")) - + String.format(" :Seniority Date: %s%n", printable.get("seniorityDate")) - + String.format(" :Start Date: %s%n", printable.get("startDate")); + + String.format(" :Coefficient: %s%n", printable.get("coefficient")) + + String.format(" :Collective Agreement: %s%n", printable.get("collectiveAgreement")) + + String.format(" :Job Title: %s%n", printable.get("jobTitle")) + + String.format(" :Position Level: %s%n", printable.get("positionLevel")) + + String.format(" :Seniority Date: %s%n", printable.get("seniorityDate")) + + String.format(" :Start Date: %s%n", printable.get("startDate")); } @Override @@ -94,7 +92,8 @@ private Map printableValues() { printable.put("category", SummaryHelper.formatForDisplay(this.category, null)); printable.put("coefficient", SummaryHelper.formatForDisplay(this.coefficient, null)); - printable.put("collectiveAgreement", SummaryHelper.formatForDisplay(this.collectiveAgreement, null)); + printable + .put("collectiveAgreement", SummaryHelper.formatForDisplay(this.collectiveAgreement, null)); printable.put("jobTitle", SummaryHelper.formatForDisplay(this.jobTitle, null)); printable.put("positionLevel", SummaryHelper.formatForDisplay(this.positionLevel, null)); printable.put("seniorityDate", SummaryHelper.formatForDisplay(this.seniorityDate, null)); diff --git a/src/main/java/com/mindee/product/fr/payslip/PayslipV3PaidTimeOff.java b/src/main/java/com/mindee/product/fr/payslip/PayslipV3PaidTimeOff.java index 46eb2b0a2..f010d9eae 100644 --- a/src/main/java/com/mindee/product/fr/payslip/PayslipV3PaidTimeOff.java +++ b/src/main/java/com/mindee/product/fr/payslip/PayslipV3PaidTimeOff.java @@ -43,32 +43,21 @@ public class PayslipV3PaidTimeOff extends BaseField implements LineItemField { Double used; public boolean isEmpty() { - return ( - accrued == null - && (period == null || period.isEmpty()) - && (ptoType == null || ptoType.isEmpty()) - && remaining == null - && used == null - ); + return (accrued == null + && (period == null || period.isEmpty()) + && (ptoType == null || ptoType.isEmpty()) + && remaining == null + && used == null); } private Map tablePrintableValues() { Map printable = new HashMap<>(); - printable.put( - "accrued", - SummaryHelper.formatAmount(this.accrued) - ); + printable.put("accrued", SummaryHelper.formatAmount(this.accrued)); printable.put("period", SummaryHelper.formatForDisplay(this.period, 6)); printable.put("ptoType", SummaryHelper.formatForDisplay(this.ptoType, 11)); - printable.put( - "remaining", - SummaryHelper.formatAmount(this.remaining) - ); - printable.put( - "used", - SummaryHelper.formatAmount(this.used) - ); + printable.put("remaining", SummaryHelper.formatAmount(this.remaining)); + printable.put("used", SummaryHelper.formatAmount(this.used)); return printable; } @@ -97,20 +86,11 @@ public String toString() { private Map printableValues() { Map printable = new HashMap<>(); - printable.put( - "accrued", - SummaryHelper.formatAmount(this.accrued) - ); + printable.put("accrued", SummaryHelper.formatAmount(this.accrued)); printable.put("period", SummaryHelper.formatForDisplay(this.period, null)); printable.put("ptoType", SummaryHelper.formatForDisplay(this.ptoType, null)); - printable.put( - "remaining", - SummaryHelper.formatAmount(this.remaining) - ); - printable.put( - "used", - SummaryHelper.formatAmount(this.used) - ); + printable.put("remaining", SummaryHelper.formatAmount(this.remaining)); + printable.put("used", SummaryHelper.formatAmount(this.used)); return printable; } } diff --git a/src/main/java/com/mindee/product/fr/payslip/PayslipV3PayDetail.java b/src/main/java/com/mindee/product/fr/payslip/PayslipV3PayDetail.java index a1fc06f1e..fc3257089 100644 --- a/src/main/java/com/mindee/product/fr/payslip/PayslipV3PayDetail.java +++ b/src/main/java/com/mindee/product/fr/payslip/PayslipV3PayDetail.java @@ -67,18 +67,16 @@ public class PayslipV3PayDetail extends BaseField { Double totalTaxesAndDeductions; public boolean isEmpty() { - return ( - grossSalary == null - && grossSalaryYtd == null - && incomeTaxRate == null - && incomeTaxWithheld == null - && netPaid == null - && netPaidBeforeTax == null - && netTaxable == null - && netTaxableYtd == null - && totalCostEmployer == null - && totalTaxesAndDeductions == null - ); + return (grossSalary == null + && grossSalaryYtd == null + && incomeTaxRate == null + && incomeTaxWithheld == null + && netPaid == null + && netPaidBeforeTax == null + && netTaxable == null + && netTaxableYtd == null + && totalCostEmployer == null + && totalTaxesAndDeductions == null); } /** @@ -87,15 +85,16 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Gross Salary: %s%n", printable.get("grossSalary")) - + String.format(" :Gross Salary YTD: %s%n", printable.get("grossSalaryYtd")) - + String.format(" :Income Tax Rate: %s%n", printable.get("incomeTaxRate")) - + String.format(" :Income Tax Withheld: %s%n", printable.get("incomeTaxWithheld")) - + String.format(" :Net Paid: %s%n", printable.get("netPaid")) - + String.format(" :Net Paid Before Tax: %s%n", printable.get("netPaidBeforeTax")) - + String.format(" :Net Taxable: %s%n", printable.get("netTaxable")) - + String.format(" :Net Taxable YTD: %s%n", printable.get("netTaxableYtd")) - + String.format(" :Total Cost Employer: %s%n", printable.get("totalCostEmployer")) - + String.format(" :Total Taxes and Deductions: %s%n", printable.get("totalTaxesAndDeductions")); + + String.format(" :Gross Salary YTD: %s%n", printable.get("grossSalaryYtd")) + + String.format(" :Income Tax Rate: %s%n", printable.get("incomeTaxRate")) + + String.format(" :Income Tax Withheld: %s%n", printable.get("incomeTaxWithheld")) + + String.format(" :Net Paid: %s%n", printable.get("netPaid")) + + String.format(" :Net Paid Before Tax: %s%n", printable.get("netPaidBeforeTax")) + + String.format(" :Net Taxable: %s%n", printable.get("netTaxable")) + + String.format(" :Net Taxable YTD: %s%n", printable.get("netTaxableYtd")) + + String.format(" :Total Cost Employer: %s%n", printable.get("totalCostEmployer")) + + String + .format(" :Total Taxes and Deductions: %s%n", printable.get("totalTaxesAndDeductions")); } @Override @@ -116,46 +115,17 @@ public String toString() { private Map printableValues() { Map printable = new HashMap<>(); - printable.put( - "grossSalary", - SummaryHelper.formatAmount(this.grossSalary) - ); - printable.put( - "grossSalaryYtd", - SummaryHelper.formatAmount(this.grossSalaryYtd) - ); - printable.put( - "incomeTaxRate", - SummaryHelper.formatAmount(this.incomeTaxRate) - ); - printable.put( - "incomeTaxWithheld", - SummaryHelper.formatAmount(this.incomeTaxWithheld) - ); - printable.put( - "netPaid", - SummaryHelper.formatAmount(this.netPaid) - ); - printable.put( - "netPaidBeforeTax", - SummaryHelper.formatAmount(this.netPaidBeforeTax) - ); - printable.put( - "netTaxable", - SummaryHelper.formatAmount(this.netTaxable) - ); - printable.put( - "netTaxableYtd", - SummaryHelper.formatAmount(this.netTaxableYtd) - ); - printable.put( - "totalCostEmployer", - SummaryHelper.formatAmount(this.totalCostEmployer) - ); - printable.put( - "totalTaxesAndDeductions", - SummaryHelper.formatAmount(this.totalTaxesAndDeductions) - ); + printable.put("grossSalary", SummaryHelper.formatAmount(this.grossSalary)); + printable.put("grossSalaryYtd", SummaryHelper.formatAmount(this.grossSalaryYtd)); + printable.put("incomeTaxRate", SummaryHelper.formatAmount(this.incomeTaxRate)); + printable.put("incomeTaxWithheld", SummaryHelper.formatAmount(this.incomeTaxWithheld)); + printable.put("netPaid", SummaryHelper.formatAmount(this.netPaid)); + printable.put("netPaidBeforeTax", SummaryHelper.formatAmount(this.netPaidBeforeTax)); + printable.put("netTaxable", SummaryHelper.formatAmount(this.netTaxable)); + printable.put("netTaxableYtd", SummaryHelper.formatAmount(this.netTaxableYtd)); + printable.put("totalCostEmployer", SummaryHelper.formatAmount(this.totalCostEmployer)); + printable + .put("totalTaxesAndDeductions", SummaryHelper.formatAmount(this.totalTaxesAndDeductions)); return printable; } } diff --git a/src/main/java/com/mindee/product/fr/payslip/PayslipV3PayPeriod.java b/src/main/java/com/mindee/product/fr/payslip/PayslipV3PayPeriod.java index 4ec17cbf2..3ecd7dd97 100644 --- a/src/main/java/com/mindee/product/fr/payslip/PayslipV3PayPeriod.java +++ b/src/main/java/com/mindee/product/fr/payslip/PayslipV3PayPeriod.java @@ -42,13 +42,11 @@ public class PayslipV3PayPeriod extends BaseField { String year; public boolean isEmpty() { - return ( - (endDate == null || endDate.isEmpty()) - && (month == null || month.isEmpty()) - && (paymentDate == null || paymentDate.isEmpty()) - && (startDate == null || startDate.isEmpty()) - && (year == null || year.isEmpty()) - ); + return ((endDate == null || endDate.isEmpty()) + && (month == null || month.isEmpty()) + && (paymentDate == null || paymentDate.isEmpty()) + && (startDate == null || startDate.isEmpty()) + && (year == null || year.isEmpty())); } /** @@ -57,10 +55,10 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :End Date: %s%n", printable.get("endDate")) - + String.format(" :Month: %s%n", printable.get("month")) - + String.format(" :Payment Date: %s%n", printable.get("paymentDate")) - + String.format(" :Start Date: %s%n", printable.get("startDate")) - + String.format(" :Year: %s%n", printable.get("year")); + + String.format(" :Month: %s%n", printable.get("month")) + + String.format(" :Payment Date: %s%n", printable.get("paymentDate")) + + String.format(" :Start Date: %s%n", printable.get("startDate")) + + String.format(" :Year: %s%n", printable.get("year")); } @Override diff --git a/src/main/java/com/mindee/product/fr/payslip/PayslipV3SalaryDetail.java b/src/main/java/com/mindee/product/fr/payslip/PayslipV3SalaryDetail.java index dcec4829c..bbef3d76d 100644 --- a/src/main/java/com/mindee/product/fr/payslip/PayslipV3SalaryDetail.java +++ b/src/main/java/com/mindee/product/fr/payslip/PayslipV3SalaryDetail.java @@ -43,35 +43,21 @@ public class PayslipV3SalaryDetail extends BaseField implements LineItemField { Double rate; public boolean isEmpty() { - return ( - amount == null - && base == null - && (description == null || description.isEmpty()) - && number == null - && rate == null - ); + return (amount == null + && base == null + && (description == null || description.isEmpty()) + && number == null + && rate == null); } private Map tablePrintableValues() { Map printable = new HashMap<>(); - printable.put( - "amount", - SummaryHelper.formatAmount(this.amount) - ); - printable.put( - "base", - SummaryHelper.formatAmount(this.base) - ); + printable.put("amount", SummaryHelper.formatAmount(this.amount)); + printable.put("base", SummaryHelper.formatAmount(this.base)); printable.put("description", SummaryHelper.formatForDisplay(this.description, 36)); - printable.put( - "number", - SummaryHelper.formatAmount(this.number) - ); - printable.put( - "rate", - SummaryHelper.formatAmount(this.rate) - ); + printable.put("number", SummaryHelper.formatAmount(this.number)); + printable.put("rate", SummaryHelper.formatAmount(this.rate)); return printable; } @@ -100,23 +86,11 @@ public String toString() { private Map printableValues() { Map printable = new HashMap<>(); - printable.put( - "amount", - SummaryHelper.formatAmount(this.amount) - ); - printable.put( - "base", - SummaryHelper.formatAmount(this.base) - ); + printable.put("amount", SummaryHelper.formatAmount(this.amount)); + printable.put("base", SummaryHelper.formatAmount(this.base)); printable.put("description", SummaryHelper.formatForDisplay(this.description, null)); - printable.put( - "number", - SummaryHelper.formatAmount(this.number) - ); - printable.put( - "rate", - SummaryHelper.formatAmount(this.rate) - ); + printable.put("number", SummaryHelper.formatAmount(this.number)); + printable.put("rate", SummaryHelper.formatAmount(this.rate)); return printable; } } diff --git a/src/main/java/com/mindee/product/ind/indianpassport/IndianPassportV1Document.java b/src/main/java/com/mindee/product/ind/indianpassport/IndianPassportV1Document.java index 262bd8ec2..85b7de6e4 100644 --- a/src/main/java/com/mindee/product/ind/indianpassport/IndianPassportV1Document.java +++ b/src/main/java/com/mindee/product/ind/indianpassport/IndianPassportV1Document.java @@ -136,8 +136,7 @@ public class IndianPassportV1Document extends Prediction { @Override public boolean isEmpty() { - return ( - this.pageNumber == null + return (this.pageNumber == null && this.country == null && this.idNumber == null && this.givenNames == null @@ -159,82 +158,39 @@ public boolean isEmpty() { && this.address1 == null && this.address2 == null && this.address3 == null - && this.fileNumber == null - ); + && this.fileNumber == null); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - outStr.append( - String.format(":Page Number: %s%n", this.getPageNumber()) - ); - outStr.append( - String.format(":Country: %s%n", this.getCountry()) - ); - outStr.append( - String.format(":ID Number: %s%n", this.getIdNumber()) - ); - outStr.append( - String.format(":Given Names: %s%n", this.getGivenNames()) - ); - outStr.append( - String.format(":Surname: %s%n", this.getSurname()) - ); - outStr.append( - String.format(":Birth Date: %s%n", this.getBirthDate()) - ); - outStr.append( - String.format(":Birth Place: %s%n", this.getBirthPlace()) - ); - outStr.append( - String.format(":Issuance Place: %s%n", this.getIssuancePlace()) - ); - outStr.append( - String.format(":Gender: %s%n", this.getGender()) - ); - outStr.append( - String.format(":Issuance Date: %s%n", this.getIssuanceDate()) - ); - outStr.append( - String.format(":Expiry Date: %s%n", this.getExpiryDate()) - ); - outStr.append( - String.format(":MRZ Line 1: %s%n", this.getMrz1()) - ); - outStr.append( - String.format(":MRZ Line 2: %s%n", this.getMrz2()) - ); - outStr.append( - String.format(":Legal Guardian: %s%n", this.getLegalGuardian()) - ); - outStr.append( - String.format(":Name of Spouse: %s%n", this.getNameOfSpouse()) - ); - outStr.append( - String.format(":Name of Mother: %s%n", this.getNameOfMother()) - ); - outStr.append( - String.format(":Old Passport Date of Issue: %s%n", this.getOldPassportDateOfIssue()) - ); - outStr.append( - String.format(":Old Passport Number: %s%n", this.getOldPassportNumber()) - ); - outStr.append( + outStr.append(String.format(":Page Number: %s%n", this.getPageNumber())); + outStr.append(String.format(":Country: %s%n", this.getCountry())); + outStr.append(String.format(":ID Number: %s%n", this.getIdNumber())); + outStr.append(String.format(":Given Names: %s%n", this.getGivenNames())); + outStr.append(String.format(":Surname: %s%n", this.getSurname())); + outStr.append(String.format(":Birth Date: %s%n", this.getBirthDate())); + outStr.append(String.format(":Birth Place: %s%n", this.getBirthPlace())); + outStr.append(String.format(":Issuance Place: %s%n", this.getIssuancePlace())); + outStr.append(String.format(":Gender: %s%n", this.getGender())); + outStr.append(String.format(":Issuance Date: %s%n", this.getIssuanceDate())); + outStr.append(String.format(":Expiry Date: %s%n", this.getExpiryDate())); + outStr.append(String.format(":MRZ Line 1: %s%n", this.getMrz1())); + outStr.append(String.format(":MRZ Line 2: %s%n", this.getMrz2())); + outStr.append(String.format(":Legal Guardian: %s%n", this.getLegalGuardian())); + outStr.append(String.format(":Name of Spouse: %s%n", this.getNameOfSpouse())); + outStr.append(String.format(":Name of Mother: %s%n", this.getNameOfMother())); + outStr + .append(String.format(":Old Passport Date of Issue: %s%n", this.getOldPassportDateOfIssue())); + outStr.append(String.format(":Old Passport Number: %s%n", this.getOldPassportNumber())); + outStr + .append( String.format(":Old Passport Place of Issue: %s%n", this.getOldPassportPlaceOfIssue()) - ); - outStr.append( - String.format(":Address Line 1: %s%n", this.getAddress1()) - ); - outStr.append( - String.format(":Address Line 2: %s%n", this.getAddress2()) - ); - outStr.append( - String.format(":Address Line 3: %s%n", this.getAddress3()) - ); - outStr.append( - String.format(":File Number: %s%n", this.getFileNumber()) - ); + ); + outStr.append(String.format(":Address Line 1: %s%n", this.getAddress1())); + outStr.append(String.format(":Address Line 2: %s%n", this.getAddress2())); + outStr.append(String.format(":Address Line 3: %s%n", this.getAddress3())); + outStr.append(String.format(":File Number: %s%n", this.getFileNumber())); return SummaryHelper.cleanSummary(outStr.toString()); } } diff --git a/src/main/java/com/mindee/product/internationalid/InternationalIdV2Document.java b/src/main/java/com/mindee/product/internationalid/InternationalIdV2Document.java index 05918814c..a473f56dc 100644 --- a/src/main/java/com/mindee/product/internationalid/InternationalIdV2Document.java +++ b/src/main/java/com/mindee/product/internationalid/InternationalIdV2Document.java @@ -108,8 +108,7 @@ public class InternationalIdV2Document extends Prediction { @Override public boolean isEmpty() { - return ( - this.documentType == null + return (this.documentType == null && this.documentNumber == null && (this.surnames == null || this.surnames.isEmpty()) && (this.givenNames == null || this.givenNames.isEmpty()) @@ -125,72 +124,31 @@ public boolean isEmpty() { && this.address == null && this.mrzLine1 == null && this.mrzLine2 == null - && this.mrzLine3 == null - ); + && this.mrzLine3 == null); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - outStr.append( - String.format(":Document Type: %s%n", this.getDocumentType()) - ); - outStr.append( - String.format(":Document Number: %s%n", this.getDocumentNumber()) - ); - String surnames = SummaryHelper.arrayToString( - this.getSurnames(), - "%n " - ); - outStr.append( - String.format(":Surnames: %s%n", surnames) - ); - String givenNames = SummaryHelper.arrayToString( - this.getGivenNames(), - "%n " - ); - outStr.append( - String.format(":Given Names: %s%n", givenNames) - ); - outStr.append( - String.format(":Sex: %s%n", this.getSex()) - ); - outStr.append( - String.format(":Birth Date: %s%n", this.getBirthDate()) - ); - outStr.append( - String.format(":Birth Place: %s%n", this.getBirthPlace()) - ); - outStr.append( - String.format(":Nationality: %s%n", this.getNationality()) - ); - outStr.append( - String.format(":Personal Number: %s%n", this.getPersonalNumber()) - ); - outStr.append( - String.format(":Country of Issue: %s%n", this.getCountryOfIssue()) - ); - outStr.append( - String.format(":State of Issue: %s%n", this.getStateOfIssue()) - ); - outStr.append( - String.format(":Issue Date: %s%n", this.getIssueDate()) - ); - outStr.append( - String.format(":Expiration Date: %s%n", this.getExpiryDate()) - ); - outStr.append( - String.format(":Address: %s%n", this.getAddress()) - ); - outStr.append( - String.format(":MRZ Line 1: %s%n", this.getMrzLine1()) - ); - outStr.append( - String.format(":MRZ Line 2: %s%n", this.getMrzLine2()) - ); - outStr.append( - String.format(":MRZ Line 3: %s%n", this.getMrzLine3()) - ); + outStr.append(String.format(":Document Type: %s%n", this.getDocumentType())); + outStr.append(String.format(":Document Number: %s%n", this.getDocumentNumber())); + String surnames = SummaryHelper.arrayToString(this.getSurnames(), "%n "); + outStr.append(String.format(":Surnames: %s%n", surnames)); + String givenNames = SummaryHelper.arrayToString(this.getGivenNames(), "%n "); + outStr.append(String.format(":Given Names: %s%n", givenNames)); + outStr.append(String.format(":Sex: %s%n", this.getSex())); + outStr.append(String.format(":Birth Date: %s%n", this.getBirthDate())); + outStr.append(String.format(":Birth Place: %s%n", this.getBirthPlace())); + outStr.append(String.format(":Nationality: %s%n", this.getNationality())); + outStr.append(String.format(":Personal Number: %s%n", this.getPersonalNumber())); + outStr.append(String.format(":Country of Issue: %s%n", this.getCountryOfIssue())); + outStr.append(String.format(":State of Issue: %s%n", this.getStateOfIssue())); + outStr.append(String.format(":Issue Date: %s%n", this.getIssueDate())); + outStr.append(String.format(":Expiration Date: %s%n", this.getExpiryDate())); + outStr.append(String.format(":Address: %s%n", this.getAddress())); + outStr.append(String.format(":MRZ Line 1: %s%n", this.getMrzLine1())); + outStr.append(String.format(":MRZ Line 2: %s%n", this.getMrzLine2())); + outStr.append(String.format(":MRZ Line 3: %s%n", this.getMrzLine3())); return SummaryHelper.cleanSummary(outStr.toString()); } } diff --git a/src/main/java/com/mindee/product/invoice/InvoiceV4.java b/src/main/java/com/mindee/product/invoice/InvoiceV4.java index 4ca25a224..4688476f7 100644 --- a/src/main/java/com/mindee/product/invoice/InvoiceV4.java +++ b/src/main/java/com/mindee/product/invoice/InvoiceV4.java @@ -11,6 +11,5 @@ @Getter @JsonIgnoreProperties(ignoreUnknown = true) @EndpointInfo(endpointName = "invoices", version = "4") -public class InvoiceV4 - extends Inference { +public class InvoiceV4 extends Inference { } diff --git a/src/main/java/com/mindee/product/invoice/InvoiceV4Document.java b/src/main/java/com/mindee/product/invoice/InvoiceV4Document.java index d10fe124f..6fd1daf1f 100644 --- a/src/main/java/com/mindee/product/invoice/InvoiceV4Document.java +++ b/src/main/java/com/mindee/product/invoice/InvoiceV4Document.java @@ -177,8 +177,7 @@ public class InvoiceV4Document extends Prediction { @Override public boolean isEmpty() { - return ( - this.locale == null + return (this.locale == null && this.invoiceNumber == null && this.poNumber == null && (this.referenceNumbers == null || this.referenceNumbers.isEmpty()) @@ -206,133 +205,69 @@ public boolean isEmpty() { && this.documentTypeExtended == null && this.subcategory == null && this.category == null - && (this.lineItems == null || this.lineItems.isEmpty()) - ); + && (this.lineItems == null || this.lineItems.isEmpty())); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - outStr.append( - String.format(":Locale: %s%n", this.getLocale()) - ); - outStr.append( - String.format(":Invoice Number: %s%n", this.getInvoiceNumber()) - ); - outStr.append( - String.format(":Purchase Order Number: %s%n", this.getPoNumber()) - ); - String referenceNumbers = SummaryHelper.arrayToString( - this.getReferenceNumbers(), - "%n " - ); - outStr.append( - String.format(":Reference Numbers: %s%n", referenceNumbers) - ); - outStr.append( - String.format(":Purchase Date: %s%n", this.getDate()) - ); - outStr.append( - String.format(":Due Date: %s%n", this.getDueDate()) - ); - outStr.append( - String.format(":Payment Date: %s%n", this.getPaymentDate()) - ); - outStr.append( - String.format(":Total Net: %s%n", this.getTotalNet()) - ); - outStr.append( - String.format(":Total Amount: %s%n", this.getTotalAmount()) - ); - outStr.append( - String.format(":Total Tax: %s%n", this.getTotalTax()) - ); - outStr.append( - String.format(":Taxes: %s%n", this.getTaxes()) - ); - String supplierPaymentDetails = SummaryHelper.arrayToString( - this.getSupplierPaymentDetails(), - "%n " - ); - outStr.append( - String.format(":Supplier Payment Details: %s%n", supplierPaymentDetails) - ); - outStr.append( - String.format(":Supplier Name: %s%n", this.getSupplierName()) - ); - String supplierCompanyRegistrations = SummaryHelper.arrayToString( - this.getSupplierCompanyRegistrations(), - "%n " - ); - outStr.append( - String.format(":Supplier Company Registrations: %s%n", supplierCompanyRegistrations) - ); - outStr.append( - String.format(":Supplier Address: %s%n", this.getSupplierAddress()) - ); - outStr.append( - String.format(":Supplier Phone Number: %s%n", this.getSupplierPhoneNumber()) - ); - outStr.append( - String.format(":Supplier Website: %s%n", this.getSupplierWebsite()) - ); - outStr.append( - String.format(":Supplier Email: %s%n", this.getSupplierEmail()) - ); - outStr.append( - String.format(":Customer Name: %s%n", this.getCustomerName()) - ); - String customerCompanyRegistrations = SummaryHelper.arrayToString( - this.getCustomerCompanyRegistrations(), - "%n " - ); - outStr.append( - String.format(":Customer Company Registrations: %s%n", customerCompanyRegistrations) - ); - outStr.append( - String.format(":Customer Address: %s%n", this.getCustomerAddress()) - ); - outStr.append( - String.format(":Customer ID: %s%n", this.getCustomerId()) - ); - outStr.append( - String.format(":Shipping Address: %s%n", this.getShippingAddress()) - ); - outStr.append( - String.format(":Billing Address: %s%n", this.getBillingAddress()) - ); - outStr.append( - String.format(":Document Type: %s%n", this.getDocumentType()) - ); - outStr.append( - String.format(":Document Type Extended: %s%n", this.getDocumentTypeExtended()) - ); - outStr.append( - String.format(":Purchase Subcategory: %s%n", this.getSubcategory()) - ); - outStr.append( - String.format(":Purchase Category: %s%n", this.getCategory()) - ); + outStr.append(String.format(":Locale: %s%n", this.getLocale())); + outStr.append(String.format(":Invoice Number: %s%n", this.getInvoiceNumber())); + outStr.append(String.format(":Purchase Order Number: %s%n", this.getPoNumber())); + String referenceNumbers = SummaryHelper + .arrayToString(this.getReferenceNumbers(), "%n "); + outStr.append(String.format(":Reference Numbers: %s%n", referenceNumbers)); + outStr.append(String.format(":Purchase Date: %s%n", this.getDate())); + outStr.append(String.format(":Due Date: %s%n", this.getDueDate())); + outStr.append(String.format(":Payment Date: %s%n", this.getPaymentDate())); + outStr.append(String.format(":Total Net: %s%n", this.getTotalNet())); + outStr.append(String.format(":Total Amount: %s%n", this.getTotalAmount())); + outStr.append(String.format(":Total Tax: %s%n", this.getTotalTax())); + outStr.append(String.format(":Taxes: %s%n", this.getTaxes())); + String supplierPaymentDetails = SummaryHelper + .arrayToString(this.getSupplierPaymentDetails(), "%n "); + outStr.append(String.format(":Supplier Payment Details: %s%n", supplierPaymentDetails)); + outStr.append(String.format(":Supplier Name: %s%n", this.getSupplierName())); + String supplierCompanyRegistrations = SummaryHelper + .arrayToString(this.getSupplierCompanyRegistrations(), "%n "); + outStr + .append(String.format(":Supplier Company Registrations: %s%n", supplierCompanyRegistrations)); + outStr.append(String.format(":Supplier Address: %s%n", this.getSupplierAddress())); + outStr.append(String.format(":Supplier Phone Number: %s%n", this.getSupplierPhoneNumber())); + outStr.append(String.format(":Supplier Website: %s%n", this.getSupplierWebsite())); + outStr.append(String.format(":Supplier Email: %s%n", this.getSupplierEmail())); + outStr.append(String.format(":Customer Name: %s%n", this.getCustomerName())); + String customerCompanyRegistrations = SummaryHelper + .arrayToString(this.getCustomerCompanyRegistrations(), "%n "); + outStr + .append(String.format(":Customer Company Registrations: %s%n", customerCompanyRegistrations)); + outStr.append(String.format(":Customer Address: %s%n", this.getCustomerAddress())); + outStr.append(String.format(":Customer ID: %s%n", this.getCustomerId())); + outStr.append(String.format(":Shipping Address: %s%n", this.getShippingAddress())); + outStr.append(String.format(":Billing Address: %s%n", this.getBillingAddress())); + outStr.append(String.format(":Document Type: %s%n", this.getDocumentType())); + outStr.append(String.format(":Document Type Extended: %s%n", this.getDocumentTypeExtended())); + outStr.append(String.format(":Purchase Subcategory: %s%n", this.getSubcategory())); + outStr.append(String.format(":Purchase Category: %s%n", this.getCategory())); String lineItemsSummary = ""; if (!this.getLineItems().isEmpty()) { - int[] lineItemsColSizes = new int[]{38, 14, 10, 12, 14, 14, 17, 12}; - lineItemsSummary = - String.format("%n%s%n ", SummaryHelper.lineSeparator(lineItemsColSizes, "-")) - + "| Description " - + "| Product code " - + "| Quantity " - + "| Tax Amount " - + "| Tax Rate (%) " - + "| Total Amount " - + "| Unit of measure " - + "| Unit Price " - + String.format("|%n%s%n ", SummaryHelper.lineSeparator(lineItemsColSizes, "=")); + int[] lineItemsColSizes = new int[] { 38, 14, 10, 12, 14, 14, 17, 12 }; + lineItemsSummary = String + .format("%n%s%n ", SummaryHelper.lineSeparator(lineItemsColSizes, "-")) + + "| Description " + + "| Product code " + + "| Quantity " + + "| Tax Amount " + + "| Tax Rate (%) " + + "| Total Amount " + + "| Unit of measure " + + "| Unit Price " + + String.format("|%n%s%n ", SummaryHelper.lineSeparator(lineItemsColSizes, "=")); lineItemsSummary += SummaryHelper.arrayToString(this.getLineItems(), lineItemsColSizes); - lineItemsSummary += String.format("%n%s", SummaryHelper.lineSeparator(lineItemsColSizes, "-")); + lineItemsSummary += String + .format("%n%s", SummaryHelper.lineSeparator(lineItemsColSizes, "-")); } - outStr.append( - String.format(":Line Items: %s%n", lineItemsSummary) - ); + outStr.append(String.format(":Line Items: %s%n", lineItemsSummary)); return SummaryHelper.cleanSummary(outStr.toString()); } } diff --git a/src/main/java/com/mindee/product/invoice/InvoiceV4LineItem.java b/src/main/java/com/mindee/product/invoice/InvoiceV4LineItem.java index 614a91b92..6d50cdfdd 100644 --- a/src/main/java/com/mindee/product/invoice/InvoiceV4LineItem.java +++ b/src/main/java/com/mindee/product/invoice/InvoiceV4LineItem.java @@ -58,16 +58,14 @@ public class InvoiceV4LineItem extends BaseField implements LineItemField { Double unitPrice; public boolean isEmpty() { - return ( - (description == null || description.isEmpty()) - && (productCode == null || productCode.isEmpty()) - && quantity == null - && taxAmount == null - && taxRate == null - && totalAmount == null - && (unitMeasure == null || unitMeasure.isEmpty()) - && unitPrice == null - ); + return ((description == null || description.isEmpty()) + && (productCode == null || productCode.isEmpty()) + && quantity == null + && taxAmount == null + && taxRate == null + && totalAmount == null + && (unitMeasure == null || unitMeasure.isEmpty()) + && unitPrice == null); } private Map tablePrintableValues() { @@ -75,27 +73,12 @@ private Map tablePrintableValues() { printable.put("description", SummaryHelper.formatForDisplay(this.description, 36)); printable.put("productCode", SummaryHelper.formatForDisplay(this.productCode, null)); - printable.put( - "quantity", - SummaryHelper.formatAmount(this.quantity) - ); - printable.put( - "taxAmount", - SummaryHelper.formatAmount(this.taxAmount) - ); - printable.put( - "taxRate", - SummaryHelper.formatAmount(this.taxRate) - ); - printable.put( - "totalAmount", - SummaryHelper.formatAmount(this.totalAmount) - ); + printable.put("quantity", SummaryHelper.formatAmount(this.quantity)); + printable.put("taxAmount", SummaryHelper.formatAmount(this.taxAmount)); + printable.put("taxRate", SummaryHelper.formatAmount(this.taxRate)); + printable.put("totalAmount", SummaryHelper.formatAmount(this.totalAmount)); printable.put("unitMeasure", SummaryHelper.formatForDisplay(this.unitMeasure, null)); - printable.put( - "unitPrice", - SummaryHelper.formatAmount(this.unitPrice) - ); + printable.put("unitPrice", SummaryHelper.formatAmount(this.unitPrice)); return printable; } @@ -132,27 +115,12 @@ private Map printableValues() { printable.put("description", SummaryHelper.formatForDisplay(this.description, null)); printable.put("productCode", SummaryHelper.formatForDisplay(this.productCode, null)); - printable.put( - "quantity", - SummaryHelper.formatAmount(this.quantity) - ); - printable.put( - "taxAmount", - SummaryHelper.formatAmount(this.taxAmount) - ); - printable.put( - "taxRate", - SummaryHelper.formatAmount(this.taxRate) - ); - printable.put( - "totalAmount", - SummaryHelper.formatAmount(this.totalAmount) - ); + printable.put("quantity", SummaryHelper.formatAmount(this.quantity)); + printable.put("taxAmount", SummaryHelper.formatAmount(this.taxAmount)); + printable.put("taxRate", SummaryHelper.formatAmount(this.taxRate)); + printable.put("totalAmount", SummaryHelper.formatAmount(this.totalAmount)); printable.put("unitMeasure", SummaryHelper.formatForDisplay(this.unitMeasure, null)); - printable.put( - "unitPrice", - SummaryHelper.formatAmount(this.unitPrice) - ); + printable.put("unitPrice", SummaryHelper.formatAmount(this.unitPrice)); return printable; } } diff --git a/src/main/java/com/mindee/product/invoicesplitter/InvoiceSplitterV1Document.java b/src/main/java/com/mindee/product/invoicesplitter/InvoiceSplitterV1Document.java index 599830b63..773c7991f 100644 --- a/src/main/java/com/mindee/product/invoicesplitter/InvoiceSplitterV1Document.java +++ b/src/main/java/com/mindee/product/invoicesplitter/InvoiceSplitterV1Document.java @@ -25,9 +25,7 @@ public class InvoiceSplitterV1Document extends Prediction { @Override public boolean isEmpty() { - return ( - (this.invoicePageGroups == null || this.invoicePageGroups.isEmpty()) - ); + return ((this.invoicePageGroups == null || this.invoicePageGroups.isEmpty())); } @Override @@ -35,17 +33,17 @@ public String toString() { StringBuilder outStr = new StringBuilder(); String invoicePageGroupsSummary = ""; if (!this.getInvoicePageGroups().isEmpty()) { - int[] invoicePageGroupsColSizes = new int[]{74}; - invoicePageGroupsSummary = - String.format("%n%s%n ", SummaryHelper.lineSeparator(invoicePageGroupsColSizes, "-")) - + "| Page Indexes " - + String.format("|%n%s%n ", SummaryHelper.lineSeparator(invoicePageGroupsColSizes, "=")); - invoicePageGroupsSummary += SummaryHelper.arrayToString(this.getInvoicePageGroups(), invoicePageGroupsColSizes); - invoicePageGroupsSummary += String.format("%n%s", SummaryHelper.lineSeparator(invoicePageGroupsColSizes, "-")); + int[] invoicePageGroupsColSizes = new int[] { 74 }; + invoicePageGroupsSummary = String + .format("%n%s%n ", SummaryHelper.lineSeparator(invoicePageGroupsColSizes, "-")) + + "| Page Indexes " + + String.format("|%n%s%n ", SummaryHelper.lineSeparator(invoicePageGroupsColSizes, "=")); + invoicePageGroupsSummary += SummaryHelper + .arrayToString(this.getInvoicePageGroups(), invoicePageGroupsColSizes); + invoicePageGroupsSummary += String + .format("%n%s", SummaryHelper.lineSeparator(invoicePageGroupsColSizes, "-")); } - outStr.append( - String.format(":Invoice Page Groups: %s%n", invoicePageGroupsSummary) - ); + outStr.append(String.format(":Invoice Page Groups: %s%n", invoicePageGroupsSummary)); return SummaryHelper.cleanSummary(outStr.toString()); } } diff --git a/src/main/java/com/mindee/product/invoicesplitter/InvoiceSplitterV1InvoicePageGroup.java b/src/main/java/com/mindee/product/invoicesplitter/InvoiceSplitterV1InvoicePageGroup.java index 42764ad07..50f56f91e 100644 --- a/src/main/java/com/mindee/product/invoicesplitter/InvoiceSplitterV1InvoicePageGroup.java +++ b/src/main/java/com/mindee/product/invoicesplitter/InvoiceSplitterV1InvoicePageGroup.java @@ -24,20 +24,17 @@ public class InvoiceSplitterV1InvoicePageGroup extends BaseField implements Line List pageIndexes; public boolean isEmpty() { - return ( - pageIndexes == null - ); + return (pageIndexes == null); } private Map tablePrintableValues() { Map printable = new HashMap<>(); - printable.put( + printable + .put( "pageIndexes", - this.pageIndexes.stream() - .map(String::valueOf) - .collect(Collectors.joining(", ")) - ); + this.pageIndexes.stream().map(String::valueOf).collect(Collectors.joining(", ")) + ); return printable; } @@ -58,12 +55,11 @@ public String toString() { private Map printableValues() { Map printable = new HashMap<>(); - printable.put( + printable + .put( "pageIndexes", - this.pageIndexes.stream() - .map(String::valueOf) - .collect(Collectors.joining(", ")) - ); + this.pageIndexes.stream().map(String::valueOf).collect(Collectors.joining(", ")) + ); return printable; } } diff --git a/src/main/java/com/mindee/product/multireceiptsdetector/MultiReceiptsDetectorV1Document.java b/src/main/java/com/mindee/product/multireceiptsdetector/MultiReceiptsDetectorV1Document.java index d5a498372..64d6f6d25 100644 --- a/src/main/java/com/mindee/product/multireceiptsdetector/MultiReceiptsDetectorV1Document.java +++ b/src/main/java/com/mindee/product/multireceiptsdetector/MultiReceiptsDetectorV1Document.java @@ -26,21 +26,14 @@ public class MultiReceiptsDetectorV1Document extends Prediction { @Override public boolean isEmpty() { - return ( - (this.receipts == null || this.receipts.isEmpty()) - ); + return ((this.receipts == null || this.receipts.isEmpty())); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - String receipts = SummaryHelper.arrayToString( - this.getReceipts(), - "%n " - ); - outStr.append( - String.format(":List of Receipts: %s%n", receipts) - ); + String receipts = SummaryHelper.arrayToString(this.getReceipts(), "%n "); + outStr.append(String.format(":List of Receipts: %s%n", receipts)); return SummaryHelper.cleanSummary(outStr.toString()); } } diff --git a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1AddedSugar.java b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1AddedSugar.java index 7bec45758..956120943 100644 --- a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1AddedSugar.java +++ b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1AddedSugar.java @@ -32,11 +32,7 @@ public class NutritionFactsLabelV1AddedSugar extends BaseField { Double perServing; public boolean isEmpty() { - return ( - dailyValue == null - && per100G == null - && perServing == null - ); + return (dailyValue == null && per100G == null && perServing == null); } /** @@ -45,8 +41,8 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Daily Value: %s%n", printable.get("dailyValue")) - + String.format(" :Per 100g: %s%n", printable.get("per100G")) - + String.format(" :Per Serving: %s%n", printable.get("perServing")); + + String.format(" :Per 100g: %s%n", printable.get("per100G")) + + String.format(" :Per Serving: %s%n", printable.get("perServing")); } @Override @@ -60,18 +56,9 @@ public String toString() { private Map printableValues() { Map printable = new HashMap<>(); - printable.put( - "dailyValue", - SummaryHelper.formatAmount(this.dailyValue) - ); - printable.put( - "per100G", - SummaryHelper.formatAmount(this.per100G) - ); - printable.put( - "perServing", - SummaryHelper.formatAmount(this.perServing) - ); + printable.put("dailyValue", SummaryHelper.formatAmount(this.dailyValue)); + printable.put("per100G", SummaryHelper.formatAmount(this.per100G)); + printable.put("perServing", SummaryHelper.formatAmount(this.perServing)); return printable; } } diff --git a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Calorie.java b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Calorie.java index 373fd7d3d..9aa468537 100644 --- a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Calorie.java +++ b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Calorie.java @@ -32,11 +32,7 @@ public class NutritionFactsLabelV1Calorie extends BaseField { Double perServing; public boolean isEmpty() { - return ( - dailyValue == null - && per100G == null - && perServing == null - ); + return (dailyValue == null && per100G == null && perServing == null); } /** @@ -45,8 +41,8 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Daily Value: %s%n", printable.get("dailyValue")) - + String.format(" :Per 100g: %s%n", printable.get("per100G")) - + String.format(" :Per Serving: %s%n", printable.get("perServing")); + + String.format(" :Per 100g: %s%n", printable.get("per100G")) + + String.format(" :Per Serving: %s%n", printable.get("perServing")); } @Override @@ -60,18 +56,9 @@ public String toString() { private Map printableValues() { Map printable = new HashMap<>(); - printable.put( - "dailyValue", - SummaryHelper.formatAmount(this.dailyValue) - ); - printable.put( - "per100G", - SummaryHelper.formatAmount(this.per100G) - ); - printable.put( - "perServing", - SummaryHelper.formatAmount(this.perServing) - ); + printable.put("dailyValue", SummaryHelper.formatAmount(this.dailyValue)); + printable.put("per100G", SummaryHelper.formatAmount(this.per100G)); + printable.put("perServing", SummaryHelper.formatAmount(this.perServing)); return printable; } } diff --git a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Cholesterol.java b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Cholesterol.java index 3fdddf883..90350a563 100644 --- a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Cholesterol.java +++ b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Cholesterol.java @@ -32,11 +32,7 @@ public class NutritionFactsLabelV1Cholesterol extends BaseField { Double perServing; public boolean isEmpty() { - return ( - dailyValue == null - && per100G == null - && perServing == null - ); + return (dailyValue == null && per100G == null && perServing == null); } /** @@ -45,8 +41,8 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Daily Value: %s%n", printable.get("dailyValue")) - + String.format(" :Per 100g: %s%n", printable.get("per100G")) - + String.format(" :Per Serving: %s%n", printable.get("perServing")); + + String.format(" :Per 100g: %s%n", printable.get("per100G")) + + String.format(" :Per Serving: %s%n", printable.get("perServing")); } @Override @@ -60,18 +56,9 @@ public String toString() { private Map printableValues() { Map printable = new HashMap<>(); - printable.put( - "dailyValue", - SummaryHelper.formatAmount(this.dailyValue) - ); - printable.put( - "per100G", - SummaryHelper.formatAmount(this.per100G) - ); - printable.put( - "perServing", - SummaryHelper.formatAmount(this.perServing) - ); + printable.put("dailyValue", SummaryHelper.formatAmount(this.dailyValue)); + printable.put("per100G", SummaryHelper.formatAmount(this.per100G)); + printable.put("perServing", SummaryHelper.formatAmount(this.perServing)); return printable; } } diff --git a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1DietaryFiber.java b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1DietaryFiber.java index 92a36a8a0..2428c48b0 100644 --- a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1DietaryFiber.java +++ b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1DietaryFiber.java @@ -32,11 +32,7 @@ public class NutritionFactsLabelV1DietaryFiber extends BaseField { Double perServing; public boolean isEmpty() { - return ( - dailyValue == null - && per100G == null - && perServing == null - ); + return (dailyValue == null && per100G == null && perServing == null); } /** @@ -45,8 +41,8 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Daily Value: %s%n", printable.get("dailyValue")) - + String.format(" :Per 100g: %s%n", printable.get("per100G")) - + String.format(" :Per Serving: %s%n", printable.get("perServing")); + + String.format(" :Per 100g: %s%n", printable.get("per100G")) + + String.format(" :Per Serving: %s%n", printable.get("perServing")); } @Override @@ -60,18 +56,9 @@ public String toString() { private Map printableValues() { Map printable = new HashMap<>(); - printable.put( - "dailyValue", - SummaryHelper.formatAmount(this.dailyValue) - ); - printable.put( - "per100G", - SummaryHelper.formatAmount(this.per100G) - ); - printable.put( - "perServing", - SummaryHelper.formatAmount(this.perServing) - ); + printable.put("dailyValue", SummaryHelper.formatAmount(this.dailyValue)); + printable.put("per100G", SummaryHelper.formatAmount(this.per100G)); + printable.put("perServing", SummaryHelper.formatAmount(this.perServing)); return printable; } } diff --git a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Document.java b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Document.java index 756cf5e72..87c69ef92 100644 --- a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Document.java +++ b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Document.java @@ -91,8 +91,7 @@ public class NutritionFactsLabelV1Document extends Prediction { @Override public boolean isEmpty() { - return ( - this.servingPerBox == null + return (this.servingPerBox == null && this.servingSize == null && this.calories == null && this.totalFat == null @@ -105,69 +104,42 @@ public boolean isEmpty() { && this.addedSugars == null && this.protein == null && this.sodium == null - && (this.nutrients == null || this.nutrients.isEmpty()) - ); + && (this.nutrients == null || this.nutrients.isEmpty())); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - outStr.append( - String.format(":Serving per Box: %s%n", this.getServingPerBox()) - ); - outStr.append( - String.format(":Serving Size:%n%s", this.getServingSize().toFieldList()) - ); - outStr.append( - String.format(":Calories:%n%s", this.getCalories().toFieldList()) - ); - outStr.append( - String.format(":Total Fat:%n%s", this.getTotalFat().toFieldList()) - ); - outStr.append( - String.format(":Saturated Fat:%n%s", this.getSaturatedFat().toFieldList()) - ); - outStr.append( - String.format(":Trans Fat:%n%s", this.getTransFat().toFieldList()) - ); - outStr.append( - String.format(":Cholesterol:%n%s", this.getCholesterol().toFieldList()) - ); - outStr.append( - String.format(":Total Carbohydrate:%n%s", this.getTotalCarbohydrate().toFieldList()) - ); - outStr.append( - String.format(":Dietary Fiber:%n%s", this.getDietaryFiber().toFieldList()) - ); - outStr.append( - String.format(":Total Sugars:%n%s", this.getTotalSugars().toFieldList()) - ); - outStr.append( - String.format(":Added Sugars:%n%s", this.getAddedSugars().toFieldList()) - ); - outStr.append( - String.format(":Protein:%n%s", this.getProtein().toFieldList()) - ); - outStr.append( - String.format(":sodium:%n%s", this.getSodium().toFieldList()) - ); + outStr.append(String.format(":Serving per Box: %s%n", this.getServingPerBox())); + outStr.append(String.format(":Serving Size:%n%s", this.getServingSize().toFieldList())); + outStr.append(String.format(":Calories:%n%s", this.getCalories().toFieldList())); + outStr.append(String.format(":Total Fat:%n%s", this.getTotalFat().toFieldList())); + outStr.append(String.format(":Saturated Fat:%n%s", this.getSaturatedFat().toFieldList())); + outStr.append(String.format(":Trans Fat:%n%s", this.getTransFat().toFieldList())); + outStr.append(String.format(":Cholesterol:%n%s", this.getCholesterol().toFieldList())); + outStr + .append(String.format(":Total Carbohydrate:%n%s", this.getTotalCarbohydrate().toFieldList())); + outStr.append(String.format(":Dietary Fiber:%n%s", this.getDietaryFiber().toFieldList())); + outStr.append(String.format(":Total Sugars:%n%s", this.getTotalSugars().toFieldList())); + outStr.append(String.format(":Added Sugars:%n%s", this.getAddedSugars().toFieldList())); + outStr.append(String.format(":Protein:%n%s", this.getProtein().toFieldList())); + outStr.append(String.format(":sodium:%n%s", this.getSodium().toFieldList())); String nutrientsSummary = ""; if (!this.getNutrients().isEmpty()) { - int[] nutrientsColSizes = new int[]{13, 22, 10, 13, 6}; - nutrientsSummary = - String.format("%n%s%n ", SummaryHelper.lineSeparator(nutrientsColSizes, "-")) - + "| Daily Value " - + "| Name " - + "| Per 100g " - + "| Per Serving " - + "| Unit " - + String.format("|%n%s%n ", SummaryHelper.lineSeparator(nutrientsColSizes, "=")); + int[] nutrientsColSizes = new int[] { 13, 22, 10, 13, 6 }; + nutrientsSummary = String + .format("%n%s%n ", SummaryHelper.lineSeparator(nutrientsColSizes, "-")) + + "| Daily Value " + + "| Name " + + "| Per 100g " + + "| Per Serving " + + "| Unit " + + String.format("|%n%s%n ", SummaryHelper.lineSeparator(nutrientsColSizes, "=")); nutrientsSummary += SummaryHelper.arrayToString(this.getNutrients(), nutrientsColSizes); - nutrientsSummary += String.format("%n%s", SummaryHelper.lineSeparator(nutrientsColSizes, "-")); + nutrientsSummary += String + .format("%n%s", SummaryHelper.lineSeparator(nutrientsColSizes, "-")); } - outStr.append( - String.format(":nutrients: %s%n", nutrientsSummary) - ); + outStr.append(String.format(":nutrients: %s%n", nutrientsSummary)); return SummaryHelper.cleanSummary(outStr.toString()); } } diff --git a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Nutrient.java b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Nutrient.java index 1ed950a45..5a2e4abff 100644 --- a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Nutrient.java +++ b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Nutrient.java @@ -43,31 +43,20 @@ public class NutritionFactsLabelV1Nutrient extends BaseField implements LineItem String unit; public boolean isEmpty() { - return ( - dailyValue == null - && (name == null || name.isEmpty()) - && per100G == null - && perServing == null - && (unit == null || unit.isEmpty()) - ); + return (dailyValue == null + && (name == null || name.isEmpty()) + && per100G == null + && perServing == null + && (unit == null || unit.isEmpty())); } private Map tablePrintableValues() { Map printable = new HashMap<>(); - printable.put( - "dailyValue", - SummaryHelper.formatAmount(this.dailyValue) - ); + printable.put("dailyValue", SummaryHelper.formatAmount(this.dailyValue)); printable.put("name", SummaryHelper.formatForDisplay(this.name, 20)); - printable.put( - "per100G", - SummaryHelper.formatAmount(this.per100G) - ); - printable.put( - "perServing", - SummaryHelper.formatAmount(this.perServing) - ); + printable.put("per100G", SummaryHelper.formatAmount(this.per100G)); + printable.put("perServing", SummaryHelper.formatAmount(this.perServing)); printable.put("unit", SummaryHelper.formatForDisplay(this.unit, null)); return printable; } @@ -97,19 +86,10 @@ public String toString() { private Map printableValues() { Map printable = new HashMap<>(); - printable.put( - "dailyValue", - SummaryHelper.formatAmount(this.dailyValue) - ); + printable.put("dailyValue", SummaryHelper.formatAmount(this.dailyValue)); printable.put("name", SummaryHelper.formatForDisplay(this.name, null)); - printable.put( - "per100G", - SummaryHelper.formatAmount(this.per100G) - ); - printable.put( - "perServing", - SummaryHelper.formatAmount(this.perServing) - ); + printable.put("per100G", SummaryHelper.formatAmount(this.per100G)); + printable.put("perServing", SummaryHelper.formatAmount(this.perServing)); printable.put("unit", SummaryHelper.formatForDisplay(this.unit, null)); return printable; } diff --git a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Protein.java b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Protein.java index 23a1eeaaf..000185c4a 100644 --- a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Protein.java +++ b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Protein.java @@ -32,11 +32,7 @@ public class NutritionFactsLabelV1Protein extends BaseField { Double perServing; public boolean isEmpty() { - return ( - dailyValue == null - && per100G == null - && perServing == null - ); + return (dailyValue == null && per100G == null && perServing == null); } /** @@ -45,8 +41,8 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Daily Value: %s%n", printable.get("dailyValue")) - + String.format(" :Per 100g: %s%n", printable.get("per100G")) - + String.format(" :Per Serving: %s%n", printable.get("perServing")); + + String.format(" :Per 100g: %s%n", printable.get("per100G")) + + String.format(" :Per Serving: %s%n", printable.get("perServing")); } @Override @@ -60,18 +56,9 @@ public String toString() { private Map printableValues() { Map printable = new HashMap<>(); - printable.put( - "dailyValue", - SummaryHelper.formatAmount(this.dailyValue) - ); - printable.put( - "per100G", - SummaryHelper.formatAmount(this.per100G) - ); - printable.put( - "perServing", - SummaryHelper.formatAmount(this.perServing) - ); + printable.put("dailyValue", SummaryHelper.formatAmount(this.dailyValue)); + printable.put("per100G", SummaryHelper.formatAmount(this.per100G)); + printable.put("perServing", SummaryHelper.formatAmount(this.perServing)); return printable; } } diff --git a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1SaturatedFat.java b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1SaturatedFat.java index feb299e66..871357dc0 100644 --- a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1SaturatedFat.java +++ b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1SaturatedFat.java @@ -32,11 +32,7 @@ public class NutritionFactsLabelV1SaturatedFat extends BaseField { Double perServing; public boolean isEmpty() { - return ( - dailyValue == null - && per100G == null - && perServing == null - ); + return (dailyValue == null && per100G == null && perServing == null); } /** @@ -45,8 +41,8 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Daily Value: %s%n", printable.get("dailyValue")) - + String.format(" :Per 100g: %s%n", printable.get("per100G")) - + String.format(" :Per Serving: %s%n", printable.get("perServing")); + + String.format(" :Per 100g: %s%n", printable.get("per100G")) + + String.format(" :Per Serving: %s%n", printable.get("perServing")); } @Override @@ -60,18 +56,9 @@ public String toString() { private Map printableValues() { Map printable = new HashMap<>(); - printable.put( - "dailyValue", - SummaryHelper.formatAmount(this.dailyValue) - ); - printable.put( - "per100G", - SummaryHelper.formatAmount(this.per100G) - ); - printable.put( - "perServing", - SummaryHelper.formatAmount(this.perServing) - ); + printable.put("dailyValue", SummaryHelper.formatAmount(this.dailyValue)); + printable.put("per100G", SummaryHelper.formatAmount(this.per100G)); + printable.put("perServing", SummaryHelper.formatAmount(this.perServing)); return printable; } } diff --git a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1ServingSize.java b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1ServingSize.java index 9b4bef0d3..b52d5101f 100644 --- a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1ServingSize.java +++ b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1ServingSize.java @@ -27,10 +27,7 @@ public class NutritionFactsLabelV1ServingSize extends BaseField { String unit; public boolean isEmpty() { - return ( - amount == null - && (unit == null || unit.isEmpty()) - ); + return (amount == null && (unit == null || unit.isEmpty())); } /** @@ -39,7 +36,7 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Amount: %s%n", printable.get("amount")) - + String.format(" :Unit: %s%n", printable.get("unit")); + + String.format(" :Unit: %s%n", printable.get("unit")); } @Override @@ -52,10 +49,7 @@ public String toString() { private Map printableValues() { Map printable = new HashMap<>(); - printable.put( - "amount", - SummaryHelper.formatAmount(this.amount) - ); + printable.put("amount", SummaryHelper.formatAmount(this.amount)); printable.put("unit", SummaryHelper.formatForDisplay(this.unit, null)); return printable; } diff --git a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Sodium.java b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Sodium.java index 9cd2d6556..0050056bc 100644 --- a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Sodium.java +++ b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Sodium.java @@ -37,12 +37,10 @@ public class NutritionFactsLabelV1Sodium extends BaseField { String unit; public boolean isEmpty() { - return ( - dailyValue == null - && per100G == null - && perServing == null - && (unit == null || unit.isEmpty()) - ); + return (dailyValue == null + && per100G == null + && perServing == null + && (unit == null || unit.isEmpty())); } /** @@ -51,9 +49,9 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Daily Value: %s%n", printable.get("dailyValue")) - + String.format(" :Per 100g: %s%n", printable.get("per100G")) - + String.format(" :Per Serving: %s%n", printable.get("perServing")) - + String.format(" :Unit: %s%n", printable.get("unit")); + + String.format(" :Per 100g: %s%n", printable.get("per100G")) + + String.format(" :Per Serving: %s%n", printable.get("perServing")) + + String.format(" :Unit: %s%n", printable.get("unit")); } @Override @@ -68,18 +66,9 @@ public String toString() { private Map printableValues() { Map printable = new HashMap<>(); - printable.put( - "dailyValue", - SummaryHelper.formatAmount(this.dailyValue) - ); - printable.put( - "per100G", - SummaryHelper.formatAmount(this.per100G) - ); - printable.put( - "perServing", - SummaryHelper.formatAmount(this.perServing) - ); + printable.put("dailyValue", SummaryHelper.formatAmount(this.dailyValue)); + printable.put("per100G", SummaryHelper.formatAmount(this.per100G)); + printable.put("perServing", SummaryHelper.formatAmount(this.perServing)); printable.put("unit", SummaryHelper.formatForDisplay(this.unit, null)); return printable; } diff --git a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1TotalCarbohydrate.java b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1TotalCarbohydrate.java index e17d5adb1..efb97e0c6 100644 --- a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1TotalCarbohydrate.java +++ b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1TotalCarbohydrate.java @@ -32,11 +32,7 @@ public class NutritionFactsLabelV1TotalCarbohydrate extends BaseField { Double perServing; public boolean isEmpty() { - return ( - dailyValue == null - && per100G == null - && perServing == null - ); + return (dailyValue == null && per100G == null && perServing == null); } /** @@ -45,8 +41,8 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Daily Value: %s%n", printable.get("dailyValue")) - + String.format(" :Per 100g: %s%n", printable.get("per100G")) - + String.format(" :Per Serving: %s%n", printable.get("perServing")); + + String.format(" :Per 100g: %s%n", printable.get("per100G")) + + String.format(" :Per Serving: %s%n", printable.get("perServing")); } @Override @@ -60,18 +56,9 @@ public String toString() { private Map printableValues() { Map printable = new HashMap<>(); - printable.put( - "dailyValue", - SummaryHelper.formatAmount(this.dailyValue) - ); - printable.put( - "per100G", - SummaryHelper.formatAmount(this.per100G) - ); - printable.put( - "perServing", - SummaryHelper.formatAmount(this.perServing) - ); + printable.put("dailyValue", SummaryHelper.formatAmount(this.dailyValue)); + printable.put("per100G", SummaryHelper.formatAmount(this.per100G)); + printable.put("perServing", SummaryHelper.formatAmount(this.perServing)); return printable; } } diff --git a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1TotalFat.java b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1TotalFat.java index b5e0633ad..ae6da0b5c 100644 --- a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1TotalFat.java +++ b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1TotalFat.java @@ -32,11 +32,7 @@ public class NutritionFactsLabelV1TotalFat extends BaseField { Double perServing; public boolean isEmpty() { - return ( - dailyValue == null - && per100G == null - && perServing == null - ); + return (dailyValue == null && per100G == null && perServing == null); } /** @@ -45,8 +41,8 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Daily Value: %s%n", printable.get("dailyValue")) - + String.format(" :Per 100g: %s%n", printable.get("per100G")) - + String.format(" :Per Serving: %s%n", printable.get("perServing")); + + String.format(" :Per 100g: %s%n", printable.get("per100G")) + + String.format(" :Per Serving: %s%n", printable.get("perServing")); } @Override @@ -60,18 +56,9 @@ public String toString() { private Map printableValues() { Map printable = new HashMap<>(); - printable.put( - "dailyValue", - SummaryHelper.formatAmount(this.dailyValue) - ); - printable.put( - "per100G", - SummaryHelper.formatAmount(this.per100G) - ); - printable.put( - "perServing", - SummaryHelper.formatAmount(this.perServing) - ); + printable.put("dailyValue", SummaryHelper.formatAmount(this.dailyValue)); + printable.put("per100G", SummaryHelper.formatAmount(this.per100G)); + printable.put("perServing", SummaryHelper.formatAmount(this.perServing)); return printable; } } diff --git a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1TotalSugar.java b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1TotalSugar.java index 198edcff7..ab7a55160 100644 --- a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1TotalSugar.java +++ b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1TotalSugar.java @@ -32,11 +32,7 @@ public class NutritionFactsLabelV1TotalSugar extends BaseField { Double perServing; public boolean isEmpty() { - return ( - dailyValue == null - && per100G == null - && perServing == null - ); + return (dailyValue == null && per100G == null && perServing == null); } /** @@ -45,8 +41,8 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Daily Value: %s%n", printable.get("dailyValue")) - + String.format(" :Per 100g: %s%n", printable.get("per100G")) - + String.format(" :Per Serving: %s%n", printable.get("perServing")); + + String.format(" :Per 100g: %s%n", printable.get("per100G")) + + String.format(" :Per Serving: %s%n", printable.get("perServing")); } @Override @@ -60,18 +56,9 @@ public String toString() { private Map printableValues() { Map printable = new HashMap<>(); - printable.put( - "dailyValue", - SummaryHelper.formatAmount(this.dailyValue) - ); - printable.put( - "per100G", - SummaryHelper.formatAmount(this.per100G) - ); - printable.put( - "perServing", - SummaryHelper.formatAmount(this.perServing) - ); + printable.put("dailyValue", SummaryHelper.formatAmount(this.dailyValue)); + printable.put("per100G", SummaryHelper.formatAmount(this.per100G)); + printable.put("perServing", SummaryHelper.formatAmount(this.perServing)); return printable; } } diff --git a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1TransFat.java b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1TransFat.java index 123196da6..cbbe14a4b 100644 --- a/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1TransFat.java +++ b/src/main/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1TransFat.java @@ -32,11 +32,7 @@ public class NutritionFactsLabelV1TransFat extends BaseField { Double perServing; public boolean isEmpty() { - return ( - dailyValue == null - && per100G == null - && perServing == null - ); + return (dailyValue == null && per100G == null && perServing == null); } /** @@ -45,8 +41,8 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :Daily Value: %s%n", printable.get("dailyValue")) - + String.format(" :Per 100g: %s%n", printable.get("per100G")) - + String.format(" :Per Serving: %s%n", printable.get("perServing")); + + String.format(" :Per 100g: %s%n", printable.get("per100G")) + + String.format(" :Per Serving: %s%n", printable.get("perServing")); } @Override @@ -60,18 +56,9 @@ public String toString() { private Map printableValues() { Map printable = new HashMap<>(); - printable.put( - "dailyValue", - SummaryHelper.formatAmount(this.dailyValue) - ); - printable.put( - "per100G", - SummaryHelper.formatAmount(this.per100G) - ); - printable.put( - "perServing", - SummaryHelper.formatAmount(this.perServing) - ); + printable.put("dailyValue", SummaryHelper.formatAmount(this.dailyValue)); + printable.put("per100G", SummaryHelper.formatAmount(this.per100G)); + printable.put("perServing", SummaryHelper.formatAmount(this.perServing)); return printable; } } diff --git a/src/main/java/com/mindee/product/passport/PassportV1.java b/src/main/java/com/mindee/product/passport/PassportV1.java index 7bd128862..d9549530b 100644 --- a/src/main/java/com/mindee/product/passport/PassportV1.java +++ b/src/main/java/com/mindee/product/passport/PassportV1.java @@ -11,6 +11,5 @@ @Getter @JsonIgnoreProperties(ignoreUnknown = true) @EndpointInfo(endpointName = "passport", version = "1") -public class PassportV1 - extends Inference { +public class PassportV1 extends Inference { } diff --git a/src/main/java/com/mindee/product/passport/PassportV1Document.java b/src/main/java/com/mindee/product/passport/PassportV1Document.java index 70ed3b7ae..feeb9a1bf 100644 --- a/src/main/java/com/mindee/product/passport/PassportV1Document.java +++ b/src/main/java/com/mindee/product/passport/PassportV1Document.java @@ -77,8 +77,7 @@ public class PassportV1Document extends Prediction { @Override public boolean isEmpty() { - return ( - this.country == null + return (this.country == null && this.idNumber == null && (this.givenNames == null || this.givenNames.isEmpty()) && this.surname == null @@ -88,50 +87,24 @@ public boolean isEmpty() { && this.issuanceDate == null && this.expiryDate == null && this.mrz1 == null - && this.mrz2 == null - ); + && this.mrz2 == null); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - outStr.append( - String.format(":Country Code: %s%n", this.getCountry()) - ); - outStr.append( - String.format(":ID Number: %s%n", this.getIdNumber()) - ); - String givenNames = SummaryHelper.arrayToString( - this.getGivenNames(), - "%n " - ); - outStr.append( - String.format(":Given Name(s): %s%n", givenNames) - ); - outStr.append( - String.format(":Surname: %s%n", this.getSurname()) - ); - outStr.append( - String.format(":Date of Birth: %s%n", this.getBirthDate()) - ); - outStr.append( - String.format(":Place of Birth: %s%n", this.getBirthPlace()) - ); - outStr.append( - String.format(":Gender: %s%n", this.getGender()) - ); - outStr.append( - String.format(":Date of Issue: %s%n", this.getIssuanceDate()) - ); - outStr.append( - String.format(":Expiry Date: %s%n", this.getExpiryDate()) - ); - outStr.append( - String.format(":MRZ Line 1: %s%n", this.getMrz1()) - ); - outStr.append( - String.format(":MRZ Line 2: %s%n", this.getMrz2()) - ); + outStr.append(String.format(":Country Code: %s%n", this.getCountry())); + outStr.append(String.format(":ID Number: %s%n", this.getIdNumber())); + String givenNames = SummaryHelper.arrayToString(this.getGivenNames(), "%n "); + outStr.append(String.format(":Given Name(s): %s%n", givenNames)); + outStr.append(String.format(":Surname: %s%n", this.getSurname())); + outStr.append(String.format(":Date of Birth: %s%n", this.getBirthDate())); + outStr.append(String.format(":Place of Birth: %s%n", this.getBirthPlace())); + outStr.append(String.format(":Gender: %s%n", this.getGender())); + outStr.append(String.format(":Date of Issue: %s%n", this.getIssuanceDate())); + outStr.append(String.format(":Expiry Date: %s%n", this.getExpiryDate())); + outStr.append(String.format(":MRZ Line 1: %s%n", this.getMrz1())); + outStr.append(String.format(":MRZ Line 2: %s%n", this.getMrz2())); return SummaryHelper.cleanSummary(outStr.toString()); } } diff --git a/src/main/java/com/mindee/product/receipt/ReceiptV5.java b/src/main/java/com/mindee/product/receipt/ReceiptV5.java index 97a3fd16f..64c071e54 100644 --- a/src/main/java/com/mindee/product/receipt/ReceiptV5.java +++ b/src/main/java/com/mindee/product/receipt/ReceiptV5.java @@ -11,6 +11,5 @@ @Getter @JsonIgnoreProperties(ignoreUnknown = true) @EndpointInfo(endpointName = "expense_receipts", version = "5") -public class ReceiptV5 - extends Inference { +public class ReceiptV5 extends Inference { } diff --git a/src/main/java/com/mindee/product/receipt/ReceiptV5Document.java b/src/main/java/com/mindee/product/receipt/ReceiptV5Document.java index bc8d76af9..1234964b6 100644 --- a/src/main/java/com/mindee/product/receipt/ReceiptV5Document.java +++ b/src/main/java/com/mindee/product/receipt/ReceiptV5Document.java @@ -115,8 +115,7 @@ public class ReceiptV5Document extends Prediction { @Override public boolean isEmpty() { - return ( - this.locale == null + return (this.locale == null && this.category == null && this.subcategory == null && this.documentType == null @@ -132,81 +131,46 @@ public boolean isEmpty() { && this.supplierAddress == null && this.supplierPhoneNumber == null && this.receiptNumber == null - && (this.lineItems == null || this.lineItems.isEmpty()) - ); + && (this.lineItems == null || this.lineItems.isEmpty())); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - outStr.append( - String.format(":Expense Locale: %s%n", this.getLocale()) - ); - outStr.append( - String.format(":Purchase Category: %s%n", this.getCategory()) - ); - outStr.append( - String.format(":Purchase Subcategory: %s%n", this.getSubcategory()) - ); - outStr.append( - String.format(":Document Type: %s%n", this.getDocumentType()) - ); - outStr.append( - String.format(":Purchase Date: %s%n", this.getDate()) - ); - outStr.append( - String.format(":Purchase Time: %s%n", this.getTime()) - ); - outStr.append( - String.format(":Total Amount: %s%n", this.getTotalAmount()) - ); - outStr.append( - String.format(":Total Net: %s%n", this.getTotalNet()) - ); - outStr.append( - String.format(":Total Tax: %s%n", this.getTotalTax()) - ); - outStr.append( - String.format(":Tip and Gratuity: %s%n", this.getTip()) - ); - outStr.append( - String.format(":Taxes: %s%n", this.getTaxes()) - ); - outStr.append( - String.format(":Supplier Name: %s%n", this.getSupplierName()) - ); - String supplierCompanyRegistrations = SummaryHelper.arrayToString( - this.getSupplierCompanyRegistrations(), - "%n " - ); - outStr.append( - String.format(":Supplier Company Registrations: %s%n", supplierCompanyRegistrations) - ); - outStr.append( - String.format(":Supplier Address: %s%n", this.getSupplierAddress()) - ); - outStr.append( - String.format(":Supplier Phone Number: %s%n", this.getSupplierPhoneNumber()) - ); - outStr.append( - String.format(":Receipt Number: %s%n", this.getReceiptNumber()) - ); + outStr.append(String.format(":Expense Locale: %s%n", this.getLocale())); + outStr.append(String.format(":Purchase Category: %s%n", this.getCategory())); + outStr.append(String.format(":Purchase Subcategory: %s%n", this.getSubcategory())); + outStr.append(String.format(":Document Type: %s%n", this.getDocumentType())); + outStr.append(String.format(":Purchase Date: %s%n", this.getDate())); + outStr.append(String.format(":Purchase Time: %s%n", this.getTime())); + outStr.append(String.format(":Total Amount: %s%n", this.getTotalAmount())); + outStr.append(String.format(":Total Net: %s%n", this.getTotalNet())); + outStr.append(String.format(":Total Tax: %s%n", this.getTotalTax())); + outStr.append(String.format(":Tip and Gratuity: %s%n", this.getTip())); + outStr.append(String.format(":Taxes: %s%n", this.getTaxes())); + outStr.append(String.format(":Supplier Name: %s%n", this.getSupplierName())); + String supplierCompanyRegistrations = SummaryHelper + .arrayToString(this.getSupplierCompanyRegistrations(), "%n "); + outStr + .append(String.format(":Supplier Company Registrations: %s%n", supplierCompanyRegistrations)); + outStr.append(String.format(":Supplier Address: %s%n", this.getSupplierAddress())); + outStr.append(String.format(":Supplier Phone Number: %s%n", this.getSupplierPhoneNumber())); + outStr.append(String.format(":Receipt Number: %s%n", this.getReceiptNumber())); String lineItemsSummary = ""; if (!this.getLineItems().isEmpty()) { - int[] lineItemsColSizes = new int[]{38, 10, 14, 12}; - lineItemsSummary = - String.format("%n%s%n ", SummaryHelper.lineSeparator(lineItemsColSizes, "-")) - + "| Description " - + "| Quantity " - + "| Total Amount " - + "| Unit Price " - + String.format("|%n%s%n ", SummaryHelper.lineSeparator(lineItemsColSizes, "=")); + int[] lineItemsColSizes = new int[] { 38, 10, 14, 12 }; + lineItemsSummary = String + .format("%n%s%n ", SummaryHelper.lineSeparator(lineItemsColSizes, "-")) + + "| Description " + + "| Quantity " + + "| Total Amount " + + "| Unit Price " + + String.format("|%n%s%n ", SummaryHelper.lineSeparator(lineItemsColSizes, "=")); lineItemsSummary += SummaryHelper.arrayToString(this.getLineItems(), lineItemsColSizes); - lineItemsSummary += String.format("%n%s", SummaryHelper.lineSeparator(lineItemsColSizes, "-")); + lineItemsSummary += String + .format("%n%s", SummaryHelper.lineSeparator(lineItemsColSizes, "-")); } - outStr.append( - String.format(":Line Items: %s%n", lineItemsSummary) - ); + outStr.append(String.format(":Line Items: %s%n", lineItemsSummary)); return SummaryHelper.cleanSummary(outStr.toString()); } } diff --git a/src/main/java/com/mindee/product/receipt/ReceiptV5LineItem.java b/src/main/java/com/mindee/product/receipt/ReceiptV5LineItem.java index 16db4f3e3..75ac5ca57 100644 --- a/src/main/java/com/mindee/product/receipt/ReceiptV5LineItem.java +++ b/src/main/java/com/mindee/product/receipt/ReceiptV5LineItem.java @@ -38,30 +38,19 @@ public class ReceiptV5LineItem extends BaseField implements LineItemField { Double unitPrice; public boolean isEmpty() { - return ( - (description == null || description.isEmpty()) - && quantity == null - && totalAmount == null - && unitPrice == null - ); + return ((description == null || description.isEmpty()) + && quantity == null + && totalAmount == null + && unitPrice == null); } private Map tablePrintableValues() { Map printable = new HashMap<>(); printable.put("description", SummaryHelper.formatForDisplay(this.description, 36)); - printable.put( - "quantity", - SummaryHelper.formatAmount(this.quantity) - ); - printable.put( - "totalAmount", - SummaryHelper.formatAmount(this.totalAmount) - ); - printable.put( - "unitPrice", - SummaryHelper.formatAmount(this.unitPrice) - ); + printable.put("quantity", SummaryHelper.formatAmount(this.quantity)); + printable.put("totalAmount", SummaryHelper.formatAmount(this.totalAmount)); + printable.put("unitPrice", SummaryHelper.formatAmount(this.unitPrice)); return printable; } @@ -89,18 +78,9 @@ private Map printableValues() { Map printable = new HashMap<>(); printable.put("description", SummaryHelper.formatForDisplay(this.description, null)); - printable.put( - "quantity", - SummaryHelper.formatAmount(this.quantity) - ); - printable.put( - "totalAmount", - SummaryHelper.formatAmount(this.totalAmount) - ); - printable.put( - "unitPrice", - SummaryHelper.formatAmount(this.unitPrice) - ); + printable.put("quantity", SummaryHelper.formatAmount(this.quantity)); + printable.put("totalAmount", SummaryHelper.formatAmount(this.totalAmount)); + printable.put("unitPrice", SummaryHelper.formatAmount(this.unitPrice)); return printable; } } diff --git a/src/main/java/com/mindee/product/resume/ResumeV1.java b/src/main/java/com/mindee/product/resume/ResumeV1.java index 6055ed6cc..c0b5d437a 100644 --- a/src/main/java/com/mindee/product/resume/ResumeV1.java +++ b/src/main/java/com/mindee/product/resume/ResumeV1.java @@ -11,6 +11,5 @@ @Getter @JsonIgnoreProperties(ignoreUnknown = true) @EndpointInfo(endpointName = "resume", version = "1") -public class ResumeV1 - extends Inference { +public class ResumeV1 extends Inference { } diff --git a/src/main/java/com/mindee/product/resume/ResumeV1Certificate.java b/src/main/java/com/mindee/product/resume/ResumeV1Certificate.java index d0b79428a..7d49e7ddd 100644 --- a/src/main/java/com/mindee/product/resume/ResumeV1Certificate.java +++ b/src/main/java/com/mindee/product/resume/ResumeV1Certificate.java @@ -38,12 +38,10 @@ public class ResumeV1Certificate extends BaseField implements LineItemField { String year; public boolean isEmpty() { - return ( - (grade == null || grade.isEmpty()) - && (name == null || name.isEmpty()) - && (provider == null || provider.isEmpty()) - && (year == null || year.isEmpty()) - ); + return ((grade == null || grade.isEmpty()) + && (name == null || name.isEmpty()) + && (provider == null || provider.isEmpty()) + && (year == null || year.isEmpty())); } private Map tablePrintableValues() { diff --git a/src/main/java/com/mindee/product/resume/ResumeV1Document.java b/src/main/java/com/mindee/product/resume/ResumeV1Document.java index fe610d71e..ac9d1728a 100644 --- a/src/main/java/com/mindee/product/resume/ResumeV1Document.java +++ b/src/main/java/com/mindee/product/resume/ResumeV1Document.java @@ -107,8 +107,7 @@ public class ResumeV1Document extends Prediction { @Override public boolean isEmpty() { - return ( - this.documentLanguage == null + return (this.documentLanguage == null && this.documentType == null && (this.givenNames == null || this.givenNames.isEmpty()) && (this.surnames == null || this.surnames.isEmpty()) @@ -124,149 +123,111 @@ public boolean isEmpty() { && (this.softSkills == null || this.softSkills.isEmpty()) && (this.education == null || this.education.isEmpty()) && (this.professionalExperiences == null || this.professionalExperiences.isEmpty()) - && (this.certificates == null || this.certificates.isEmpty()) - ); + && (this.certificates == null || this.certificates.isEmpty())); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - outStr.append( - String.format(":Document Language: %s%n", this.getDocumentLanguage()) - ); - outStr.append( - String.format(":Document Type: %s%n", this.getDocumentType()) - ); - String givenNames = SummaryHelper.arrayToString( - this.getGivenNames(), - "%n " - ); - outStr.append( - String.format(":Given Names: %s%n", givenNames) - ); - String surnames = SummaryHelper.arrayToString( - this.getSurnames(), - "%n " - ); - outStr.append( - String.format(":Surnames: %s%n", surnames) - ); - outStr.append( - String.format(":Nationality: %s%n", this.getNationality()) - ); - outStr.append( - String.format(":Email Address: %s%n", this.getEmailAddress()) - ); - outStr.append( - String.format(":Phone Number: %s%n", this.getPhoneNumber()) - ); - outStr.append( - String.format(":Address: %s%n", this.getAddress()) - ); + outStr.append(String.format(":Document Language: %s%n", this.getDocumentLanguage())); + outStr.append(String.format(":Document Type: %s%n", this.getDocumentType())); + String givenNames = SummaryHelper.arrayToString(this.getGivenNames(), "%n "); + outStr.append(String.format(":Given Names: %s%n", givenNames)); + String surnames = SummaryHelper.arrayToString(this.getSurnames(), "%n "); + outStr.append(String.format(":Surnames: %s%n", surnames)); + outStr.append(String.format(":Nationality: %s%n", this.getNationality())); + outStr.append(String.format(":Email Address: %s%n", this.getEmailAddress())); + outStr.append(String.format(":Phone Number: %s%n", this.getPhoneNumber())); + outStr.append(String.format(":Address: %s%n", this.getAddress())); String socialNetworksUrlsSummary = ""; if (!this.getSocialNetworksUrls().isEmpty()) { - int[] socialNetworksUrlsColSizes = new int[]{22, 52}; - socialNetworksUrlsSummary = - String.format("%n%s%n ", SummaryHelper.lineSeparator(socialNetworksUrlsColSizes, "-")) - + "| Name " - + "| URL " - + String.format("|%n%s%n ", SummaryHelper.lineSeparator(socialNetworksUrlsColSizes, "=")); - socialNetworksUrlsSummary += SummaryHelper.arrayToString(this.getSocialNetworksUrls(), socialNetworksUrlsColSizes); - socialNetworksUrlsSummary += String.format("%n%s", SummaryHelper.lineSeparator(socialNetworksUrlsColSizes, "-")); + int[] socialNetworksUrlsColSizes = new int[] { 22, 52 }; + socialNetworksUrlsSummary = String + .format("%n%s%n ", SummaryHelper.lineSeparator(socialNetworksUrlsColSizes, "-")) + + "| Name " + + "| URL " + + String.format("|%n%s%n ", SummaryHelper.lineSeparator(socialNetworksUrlsColSizes, "=")); + socialNetworksUrlsSummary += SummaryHelper + .arrayToString(this.getSocialNetworksUrls(), socialNetworksUrlsColSizes); + socialNetworksUrlsSummary += String + .format("%n%s", SummaryHelper.lineSeparator(socialNetworksUrlsColSizes, "-")); } - outStr.append( - String.format(":Social Networks: %s%n", socialNetworksUrlsSummary) - ); - outStr.append( - String.format(":Profession: %s%n", this.getProfession()) - ); - outStr.append( - String.format(":Job Applied: %s%n", this.getJobApplied()) - ); + outStr.append(String.format(":Social Networks: %s%n", socialNetworksUrlsSummary)); + outStr.append(String.format(":Profession: %s%n", this.getProfession())); + outStr.append(String.format(":Job Applied: %s%n", this.getJobApplied())); String languagesSummary = ""; if (!this.getLanguages().isEmpty()) { - int[] languagesColSizes = new int[]{10, 22}; - languagesSummary = - String.format("%n%s%n ", SummaryHelper.lineSeparator(languagesColSizes, "-")) - + "| Language " - + "| Level " - + String.format("|%n%s%n ", SummaryHelper.lineSeparator(languagesColSizes, "=")); + int[] languagesColSizes = new int[] { 10, 22 }; + languagesSummary = String + .format("%n%s%n ", SummaryHelper.lineSeparator(languagesColSizes, "-")) + + "| Language " + + "| Level " + + String.format("|%n%s%n ", SummaryHelper.lineSeparator(languagesColSizes, "=")); languagesSummary += SummaryHelper.arrayToString(this.getLanguages(), languagesColSizes); - languagesSummary += String.format("%n%s", SummaryHelper.lineSeparator(languagesColSizes, "-")); + languagesSummary += String + .format("%n%s", SummaryHelper.lineSeparator(languagesColSizes, "-")); } - outStr.append( - String.format(":Languages: %s%n", languagesSummary) - ); - String hardSkills = SummaryHelper.arrayToString( - this.getHardSkills(), - "%n " - ); - outStr.append( - String.format(":Hard Skills: %s%n", hardSkills) - ); - String softSkills = SummaryHelper.arrayToString( - this.getSoftSkills(), - "%n " - ); - outStr.append( - String.format(":Soft Skills: %s%n", softSkills) - ); + outStr.append(String.format(":Languages: %s%n", languagesSummary)); + String hardSkills = SummaryHelper.arrayToString(this.getHardSkills(), "%n "); + outStr.append(String.format(":Hard Skills: %s%n", hardSkills)); + String softSkills = SummaryHelper.arrayToString(this.getSoftSkills(), "%n "); + outStr.append(String.format(":Soft Skills: %s%n", softSkills)); String educationSummary = ""; if (!this.getEducation().isEmpty()) { - int[] educationColSizes = new int[]{17, 27, 11, 10, 27, 13, 12}; - educationSummary = - String.format("%n%s%n ", SummaryHelper.lineSeparator(educationColSizes, "-")) - + "| Domain " - + "| Degree " - + "| End Month " - + "| End Year " - + "| School " - + "| Start Month " - + "| Start Year " - + String.format("|%n%s%n ", SummaryHelper.lineSeparator(educationColSizes, "=")); + int[] educationColSizes = new int[] { 17, 27, 11, 10, 27, 13, 12 }; + educationSummary = String + .format("%n%s%n ", SummaryHelper.lineSeparator(educationColSizes, "-")) + + "| Domain " + + "| Degree " + + "| End Month " + + "| End Year " + + "| School " + + "| Start Month " + + "| Start Year " + + String.format("|%n%s%n ", SummaryHelper.lineSeparator(educationColSizes, "=")); educationSummary += SummaryHelper.arrayToString(this.getEducation(), educationColSizes); - educationSummary += String.format("%n%s", SummaryHelper.lineSeparator(educationColSizes, "-")); + educationSummary += String + .format("%n%s", SummaryHelper.lineSeparator(educationColSizes, "-")); } - outStr.append( - String.format(":Education: %s%n", educationSummary) - ); + outStr.append(String.format(":Education: %s%n", educationSummary)); String professionalExperiencesSummary = ""; if (!this.getProfessionalExperiences().isEmpty()) { - int[] professionalExperiencesColSizes = new int[]{17, 12, 38, 27, 11, 10, 22, 13, 12}; - professionalExperiencesSummary = - String.format("%n%s%n ", SummaryHelper.lineSeparator(professionalExperiencesColSizes, "-")) - + "| Contract Type " - + "| Department " - + "| Description " - + "| Employer " - + "| End Month " - + "| End Year " - + "| Role " - + "| Start Month " - + "| Start Year " - + String.format("|%n%s%n ", SummaryHelper.lineSeparator(professionalExperiencesColSizes, "=")); - professionalExperiencesSummary += SummaryHelper.arrayToString(this.getProfessionalExperiences(), professionalExperiencesColSizes); - professionalExperiencesSummary += String.format("%n%s", SummaryHelper.lineSeparator(professionalExperiencesColSizes, "-")); + int[] professionalExperiencesColSizes = new int[] { 17, 12, 38, 27, 11, 10, 22, 13, 12 }; + professionalExperiencesSummary = String + .format("%n%s%n ", SummaryHelper.lineSeparator(professionalExperiencesColSizes, "-")) + + "| Contract Type " + + "| Department " + + "| Description " + + "| Employer " + + "| End Month " + + "| End Year " + + "| Role " + + "| Start Month " + + "| Start Year " + + String + .format("|%n%s%n ", SummaryHelper.lineSeparator(professionalExperiencesColSizes, "=")); + professionalExperiencesSummary += SummaryHelper + .arrayToString(this.getProfessionalExperiences(), professionalExperiencesColSizes); + professionalExperiencesSummary += String + .format("%n%s", SummaryHelper.lineSeparator(professionalExperiencesColSizes, "-")); } - outStr.append( - String.format(":Professional Experiences: %s%n", professionalExperiencesSummary) - ); + outStr.append(String.format(":Professional Experiences: %s%n", professionalExperiencesSummary)); String certificatesSummary = ""; if (!this.getCertificates().isEmpty()) { - int[] certificatesColSizes = new int[]{12, 32, 27, 6}; - certificatesSummary = - String.format("%n%s%n ", SummaryHelper.lineSeparator(certificatesColSizes, "-")) - + "| Grade " - + "| Name " - + "| Provider " - + "| Year " - + String.format("|%n%s%n ", SummaryHelper.lineSeparator(certificatesColSizes, "=")); - certificatesSummary += SummaryHelper.arrayToString(this.getCertificates(), certificatesColSizes); - certificatesSummary += String.format("%n%s", SummaryHelper.lineSeparator(certificatesColSizes, "-")); + int[] certificatesColSizes = new int[] { 12, 32, 27, 6 }; + certificatesSummary = String + .format("%n%s%n ", SummaryHelper.lineSeparator(certificatesColSizes, "-")) + + "| Grade " + + "| Name " + + "| Provider " + + "| Year " + + String.format("|%n%s%n ", SummaryHelper.lineSeparator(certificatesColSizes, "=")); + certificatesSummary += SummaryHelper + .arrayToString(this.getCertificates(), certificatesColSizes); + certificatesSummary += String + .format("%n%s", SummaryHelper.lineSeparator(certificatesColSizes, "-")); } - outStr.append( - String.format(":Certificates: %s%n", certificatesSummary) - ); + outStr.append(String.format(":Certificates: %s%n", certificatesSummary)); return SummaryHelper.cleanSummary(outStr.toString()); } } diff --git a/src/main/java/com/mindee/product/resume/ResumeV1Education.java b/src/main/java/com/mindee/product/resume/ResumeV1Education.java index 75951659e..a3c32c8c6 100644 --- a/src/main/java/com/mindee/product/resume/ResumeV1Education.java +++ b/src/main/java/com/mindee/product/resume/ResumeV1Education.java @@ -53,15 +53,13 @@ public class ResumeV1Education extends BaseField implements LineItemField { String startYear; public boolean isEmpty() { - return ( - (degreeDomain == null || degreeDomain.isEmpty()) - && (degreeType == null || degreeType.isEmpty()) - && (endMonth == null || endMonth.isEmpty()) - && (endYear == null || endYear.isEmpty()) - && (school == null || school.isEmpty()) - && (startMonth == null || startMonth.isEmpty()) - && (startYear == null || startYear.isEmpty()) - ); + return ((degreeDomain == null || degreeDomain.isEmpty()) + && (degreeType == null || degreeType.isEmpty()) + && (endMonth == null || endMonth.isEmpty()) + && (endYear == null || endYear.isEmpty()) + && (school == null || school.isEmpty()) + && (startMonth == null || startMonth.isEmpty()) + && (startYear == null || startYear.isEmpty())); } private Map tablePrintableValues() { diff --git a/src/main/java/com/mindee/product/resume/ResumeV1Language.java b/src/main/java/com/mindee/product/resume/ResumeV1Language.java index 6baed5e3e..b097f3750 100644 --- a/src/main/java/com/mindee/product/resume/ResumeV1Language.java +++ b/src/main/java/com/mindee/product/resume/ResumeV1Language.java @@ -28,10 +28,7 @@ public class ResumeV1Language extends BaseField implements LineItemField { String level; public boolean isEmpty() { - return ( - (language == null || language.isEmpty()) - && (level == null || level.isEmpty()) - ); + return ((language == null || language.isEmpty()) && (level == null || level.isEmpty())); } private Map tablePrintableValues() { diff --git a/src/main/java/com/mindee/product/resume/ResumeV1ProfessionalExperience.java b/src/main/java/com/mindee/product/resume/ResumeV1ProfessionalExperience.java index cd6964539..b7cb1d29f 100644 --- a/src/main/java/com/mindee/product/resume/ResumeV1ProfessionalExperience.java +++ b/src/main/java/com/mindee/product/resume/ResumeV1ProfessionalExperience.java @@ -63,17 +63,15 @@ public class ResumeV1ProfessionalExperience extends BaseField implements LineIte String startYear; public boolean isEmpty() { - return ( - (contractType == null || contractType.isEmpty()) - && (department == null || department.isEmpty()) - && (description == null || description.isEmpty()) - && (employer == null || employer.isEmpty()) - && (endMonth == null || endMonth.isEmpty()) - && (endYear == null || endYear.isEmpty()) - && (role == null || role.isEmpty()) - && (startMonth == null || startMonth.isEmpty()) - && (startYear == null || startYear.isEmpty()) - ); + return ((contractType == null || contractType.isEmpty()) + && (department == null || department.isEmpty()) + && (description == null || description.isEmpty()) + && (employer == null || employer.isEmpty()) + && (endMonth == null || endMonth.isEmpty()) + && (endYear == null || endYear.isEmpty()) + && (role == null || role.isEmpty()) + && (startMonth == null || startMonth.isEmpty()) + && (startYear == null || startYear.isEmpty())); } private Map tablePrintableValues() { diff --git a/src/main/java/com/mindee/product/resume/ResumeV1SocialNetworksUrl.java b/src/main/java/com/mindee/product/resume/ResumeV1SocialNetworksUrl.java index 0854131e9..c0085c47e 100644 --- a/src/main/java/com/mindee/product/resume/ResumeV1SocialNetworksUrl.java +++ b/src/main/java/com/mindee/product/resume/ResumeV1SocialNetworksUrl.java @@ -28,10 +28,7 @@ public class ResumeV1SocialNetworksUrl extends BaseField implements LineItemFiel String url; public boolean isEmpty() { - return ( - (name == null || name.isEmpty()) - && (url == null || url.isEmpty()) - ); + return ((name == null || name.isEmpty()) && (url == null || url.isEmpty())); } private Map tablePrintableValues() { diff --git a/src/main/java/com/mindee/product/us/bankcheck/BankCheckV1.java b/src/main/java/com/mindee/product/us/bankcheck/BankCheckV1.java index 21e0443e5..4874692a7 100644 --- a/src/main/java/com/mindee/product/us/bankcheck/BankCheckV1.java +++ b/src/main/java/com/mindee/product/us/bankcheck/BankCheckV1.java @@ -11,6 +11,5 @@ @Getter @JsonIgnoreProperties(ignoreUnknown = true) @EndpointInfo(endpointName = "bank_check", version = "1") -public class BankCheckV1 - extends Inference { +public class BankCheckV1 extends Inference { } diff --git a/src/main/java/com/mindee/product/us/bankcheck/BankCheckV1Document.java b/src/main/java/com/mindee/product/us/bankcheck/BankCheckV1Document.java index a3aba6430..9aaf119f6 100644 --- a/src/main/java/com/mindee/product/us/bankcheck/BankCheckV1Document.java +++ b/src/main/java/com/mindee/product/us/bankcheck/BankCheckV1Document.java @@ -53,41 +53,24 @@ public class BankCheckV1Document extends Prediction { @Override public boolean isEmpty() { - return ( - this.date == null + return (this.date == null && this.amount == null && (this.payees == null || this.payees.isEmpty()) && this.routingNumber == null && this.accountNumber == null - && this.checkNumber == null - ); + && this.checkNumber == null); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - outStr.append( - String.format(":Check Issue Date: %s%n", this.getDate()) - ); - outStr.append( - String.format(":Amount: %s%n", this.getAmount()) - ); - String payees = SummaryHelper.arrayToString( - this.getPayees(), - "%n " - ); - outStr.append( - String.format(":Payees: %s%n", payees) - ); - outStr.append( - String.format(":Routing Number: %s%n", this.getRoutingNumber()) - ); - outStr.append( - String.format(":Account Number: %s%n", this.getAccountNumber()) - ); - outStr.append( - String.format(":Check Number: %s%n", this.getCheckNumber()) - ); + outStr.append(String.format(":Check Issue Date: %s%n", this.getDate())); + outStr.append(String.format(":Amount: %s%n", this.getAmount())); + String payees = SummaryHelper.arrayToString(this.getPayees(), "%n "); + outStr.append(String.format(":Payees: %s%n", payees)); + outStr.append(String.format(":Routing Number: %s%n", this.getRoutingNumber())); + outStr.append(String.format(":Account Number: %s%n", this.getAccountNumber())); + outStr.append(String.format(":Check Number: %s%n", this.getCheckNumber())); return SummaryHelper.cleanSummary(outStr.toString()); } } diff --git a/src/main/java/com/mindee/product/us/bankcheck/BankCheckV1Page.java b/src/main/java/com/mindee/product/us/bankcheck/BankCheckV1Page.java index e1496c099..28c2b991e 100644 --- a/src/main/java/com/mindee/product/us/bankcheck/BankCheckV1Page.java +++ b/src/main/java/com/mindee/product/us/bankcheck/BankCheckV1Page.java @@ -31,25 +31,17 @@ public class BankCheckV1Page extends BankCheckV1Document { @Override public boolean isEmpty() { - return ( - this.checkPosition == null - && (this.signaturesPositions == null || this.signaturesPositions.isEmpty()) - ); + return (this.checkPosition == null + && (this.signaturesPositions == null || this.signaturesPositions.isEmpty())); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - outStr.append( - String.format(":Check Position: %s%n", this.getCheckPosition()) - ); - String signaturesPositions = SummaryHelper.arrayToString( - this.getSignaturesPositions(), - "%n " - ); - outStr.append( - String.format(":Signature Positions: %s%n", signaturesPositions) - ); + outStr.append(String.format(":Check Position: %s%n", this.getCheckPosition())); + String signaturesPositions = SummaryHelper + .arrayToString(this.getSignaturesPositions(), "%n "); + outStr.append(String.format(":Signature Positions: %s%n", signaturesPositions)); outStr.append(super.toString()); return SummaryHelper.cleanSummary(outStr.toString()); } diff --git a/src/main/java/com/mindee/product/us/healthcarecard/HealthcareCardV1Copay.java b/src/main/java/com/mindee/product/us/healthcarecard/HealthcareCardV1Copay.java index c4a39ce37..4e6e3c10b 100644 --- a/src/main/java/com/mindee/product/us/healthcarecard/HealthcareCardV1Copay.java +++ b/src/main/java/com/mindee/product/us/healthcarecard/HealthcareCardV1Copay.java @@ -28,19 +28,13 @@ public class HealthcareCardV1Copay extends BaseField implements LineItemField { String serviceName; public boolean isEmpty() { - return ( - serviceFees == null - && (serviceName == null || serviceName.isEmpty()) - ); + return (serviceFees == null && (serviceName == null || serviceName.isEmpty())); } private Map tablePrintableValues() { Map printable = new HashMap<>(); - printable.put( - "serviceFees", - SummaryHelper.formatAmount(this.serviceFees) - ); + printable.put("serviceFees", SummaryHelper.formatAmount(this.serviceFees)); printable.put("serviceName", SummaryHelper.formatForDisplay(this.serviceName, 20)); return printable; } @@ -64,10 +58,7 @@ public String toString() { private Map printableValues() { Map printable = new HashMap<>(); - printable.put( - "serviceFees", - SummaryHelper.formatAmount(this.serviceFees) - ); + printable.put("serviceFees", SummaryHelper.formatAmount(this.serviceFees)); printable.put("serviceName", SummaryHelper.formatForDisplay(this.serviceName, null)); return printable; } diff --git a/src/main/java/com/mindee/product/us/healthcarecard/HealthcareCardV1Document.java b/src/main/java/com/mindee/product/us/healthcarecard/HealthcareCardV1Document.java index 9af1bfca1..008ff16a9 100644 --- a/src/main/java/com/mindee/product/us/healthcarecard/HealthcareCardV1Document.java +++ b/src/main/java/com/mindee/product/us/healthcarecard/HealthcareCardV1Document.java @@ -92,8 +92,7 @@ public class HealthcareCardV1Document extends Prediction { @Override public boolean isEmpty() { - return ( - this.companyName == null + return (this.companyName == null && this.planName == null && this.memberName == null && this.memberId == null @@ -106,70 +105,37 @@ public boolean isEmpty() { && this.rxGrp == null && this.rxPcn == null && (this.copays == null || this.copays.isEmpty()) - && this.enrollmentDate == null - ); + && this.enrollmentDate == null); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - outStr.append( - String.format(":Company Name: %s%n", this.getCompanyName()) - ); - outStr.append( - String.format(":Plan Name: %s%n", this.getPlanName()) - ); - outStr.append( - String.format(":Member Name: %s%n", this.getMemberName()) - ); - outStr.append( - String.format(":Member ID: %s%n", this.getMemberId()) - ); - outStr.append( - String.format(":Issuer 80840: %s%n", this.getIssuer80840()) - ); - String dependents = SummaryHelper.arrayToString( - this.getDependents(), - "%n " - ); - outStr.append( - String.format(":Dependents: %s%n", dependents) - ); - outStr.append( - String.format(":Group Number: %s%n", this.getGroupNumber()) - ); - outStr.append( - String.format(":Payer ID: %s%n", this.getPayerId()) - ); - outStr.append( - String.format(":RX BIN: %s%n", this.getRxBin()) - ); - outStr.append( - String.format(":RX ID: %s%n", this.getRxId()) - ); - outStr.append( - String.format(":RX GRP: %s%n", this.getRxGrp()) - ); - outStr.append( - String.format(":RX PCN: %s%n", this.getRxPcn()) - ); + outStr.append(String.format(":Company Name: %s%n", this.getCompanyName())); + outStr.append(String.format(":Plan Name: %s%n", this.getPlanName())); + outStr.append(String.format(":Member Name: %s%n", this.getMemberName())); + outStr.append(String.format(":Member ID: %s%n", this.getMemberId())); + outStr.append(String.format(":Issuer 80840: %s%n", this.getIssuer80840())); + String dependents = SummaryHelper.arrayToString(this.getDependents(), "%n "); + outStr.append(String.format(":Dependents: %s%n", dependents)); + outStr.append(String.format(":Group Number: %s%n", this.getGroupNumber())); + outStr.append(String.format(":Payer ID: %s%n", this.getPayerId())); + outStr.append(String.format(":RX BIN: %s%n", this.getRxBin())); + outStr.append(String.format(":RX ID: %s%n", this.getRxId())); + outStr.append(String.format(":RX GRP: %s%n", this.getRxGrp())); + outStr.append(String.format(":RX PCN: %s%n", this.getRxPcn())); String copaysSummary = ""; if (!this.getCopays().isEmpty()) { - int[] copaysColSizes = new int[]{14, 22}; - copaysSummary = - String.format("%n%s%n ", SummaryHelper.lineSeparator(copaysColSizes, "-")) - + "| Service Fees " - + "| Service Name " - + String.format("|%n%s%n ", SummaryHelper.lineSeparator(copaysColSizes, "=")); + int[] copaysColSizes = new int[] { 14, 22 }; + copaysSummary = String.format("%n%s%n ", SummaryHelper.lineSeparator(copaysColSizes, "-")) + + "| Service Fees " + + "| Service Name " + + String.format("|%n%s%n ", SummaryHelper.lineSeparator(copaysColSizes, "=")); copaysSummary += SummaryHelper.arrayToString(this.getCopays(), copaysColSizes); copaysSummary += String.format("%n%s", SummaryHelper.lineSeparator(copaysColSizes, "-")); } - outStr.append( - String.format(":Copays: %s%n", copaysSummary) - ); - outStr.append( - String.format(":Enrollment Date: %s%n", this.getEnrollmentDate()) - ); + outStr.append(String.format(":Copays: %s%n", copaysSummary)); + outStr.append(String.format(":Enrollment Date: %s%n", this.getEnrollmentDate())); return SummaryHelper.cleanSummary(outStr.toString()); } } diff --git a/src/main/java/com/mindee/product/us/usmail/UsMailV3.java b/src/main/java/com/mindee/product/us/usmail/UsMailV3.java index 22a31eda4..f84039435 100644 --- a/src/main/java/com/mindee/product/us/usmail/UsMailV3.java +++ b/src/main/java/com/mindee/product/us/usmail/UsMailV3.java @@ -11,6 +11,5 @@ @Getter @JsonIgnoreProperties(ignoreUnknown = true) @EndpointInfo(endpointName = "us_mail", version = "3") -public class UsMailV3 - extends Inference { +public class UsMailV3 extends Inference { } diff --git a/src/main/java/com/mindee/product/us/usmail/UsMailV3Document.java b/src/main/java/com/mindee/product/us/usmail/UsMailV3Document.java index 7c6766470..c3f617cfb 100644 --- a/src/main/java/com/mindee/product/us/usmail/UsMailV3Document.java +++ b/src/main/java/com/mindee/product/us/usmail/UsMailV3Document.java @@ -47,54 +47,42 @@ public class UsMailV3Document extends Prediction { @Override public boolean isEmpty() { - return ( - this.senderName == null + return (this.senderName == null && this.senderAddress == null && (this.recipientNames == null || this.recipientNames.isEmpty()) && (this.recipientAddresses == null || this.recipientAddresses.isEmpty()) - && this.isReturnToSender == null - ); + && this.isReturnToSender == null); } @Override public String toString() { StringBuilder outStr = new StringBuilder(); - outStr.append( - String.format(":Sender Name: %s%n", this.getSenderName()) - ); - outStr.append( - String.format(":Sender Address:%n%s", this.getSenderAddress().toFieldList()) - ); - String recipientNames = SummaryHelper.arrayToString( - this.getRecipientNames(), - "%n " - ); - outStr.append( - String.format(":Recipient Names: %s%n", recipientNames) - ); + outStr.append(String.format(":Sender Name: %s%n", this.getSenderName())); + outStr.append(String.format(":Sender Address:%n%s", this.getSenderAddress().toFieldList())); + String recipientNames = SummaryHelper + .arrayToString(this.getRecipientNames(), "%n "); + outStr.append(String.format(":Recipient Names: %s%n", recipientNames)); String recipientAddressesSummary = ""; if (!this.getRecipientAddresses().isEmpty()) { - int[] recipientAddressesColSizes = new int[]{17, 37, 19, 13, 24, 7, 27, 17}; - recipientAddressesSummary = - String.format("%n%s%n ", SummaryHelper.lineSeparator(recipientAddressesColSizes, "-")) - + "| City " - + "| Complete Address " - + "| Is Address Change " - + "| Postal Code " - + "| Private Mailbox Number " - + "| State " - + "| Street " - + "| Unit " - + String.format("|%n%s%n ", SummaryHelper.lineSeparator(recipientAddressesColSizes, "=")); - recipientAddressesSummary += SummaryHelper.arrayToString(this.getRecipientAddresses(), recipientAddressesColSizes); - recipientAddressesSummary += String.format("%n%s", SummaryHelper.lineSeparator(recipientAddressesColSizes, "-")); + int[] recipientAddressesColSizes = new int[] { 17, 37, 19, 13, 24, 7, 27, 17 }; + recipientAddressesSummary = String + .format("%n%s%n ", SummaryHelper.lineSeparator(recipientAddressesColSizes, "-")) + + "| City " + + "| Complete Address " + + "| Is Address Change " + + "| Postal Code " + + "| Private Mailbox Number " + + "| State " + + "| Street " + + "| Unit " + + String.format("|%n%s%n ", SummaryHelper.lineSeparator(recipientAddressesColSizes, "=")); + recipientAddressesSummary += SummaryHelper + .arrayToString(this.getRecipientAddresses(), recipientAddressesColSizes); + recipientAddressesSummary += String + .format("%n%s", SummaryHelper.lineSeparator(recipientAddressesColSizes, "-")); } - outStr.append( - String.format(":Recipient Addresses: %s%n", recipientAddressesSummary) - ); - outStr.append( - String.format(":Return to Sender: %s%n", this.getIsReturnToSender()) - ); + outStr.append(String.format(":Recipient Addresses: %s%n", recipientAddressesSummary)); + outStr.append(String.format(":Return to Sender: %s%n", this.getIsReturnToSender())); return SummaryHelper.cleanSummary(outStr.toString()); } } diff --git a/src/main/java/com/mindee/product/us/usmail/UsMailV3RecipientAddress.java b/src/main/java/com/mindee/product/us/usmail/UsMailV3RecipientAddress.java index a126d2527..008d51d81 100644 --- a/src/main/java/com/mindee/product/us/usmail/UsMailV3RecipientAddress.java +++ b/src/main/java/com/mindee/product/us/usmail/UsMailV3RecipientAddress.java @@ -58,16 +58,14 @@ public class UsMailV3RecipientAddress extends BaseField implements LineItemField String unit; public boolean isEmpty() { - return ( - (city == null || city.isEmpty()) - && (complete == null || complete.isEmpty()) - && isAddressChange == null - && (postalCode == null || postalCode.isEmpty()) - && (privateMailboxNumber == null || privateMailboxNumber.isEmpty()) - && (state == null || state.isEmpty()) - && (street == null || street.isEmpty()) - && (unit == null || unit.isEmpty()) - ); + return ((city == null || city.isEmpty()) + && (complete == null || complete.isEmpty()) + && isAddressChange == null + && (postalCode == null || postalCode.isEmpty()) + && (privateMailboxNumber == null || privateMailboxNumber.isEmpty()) + && (state == null || state.isEmpty()) + && (street == null || street.isEmpty()) + && (unit == null || unit.isEmpty())); } private Map tablePrintableValues() { @@ -77,7 +75,8 @@ private Map tablePrintableValues() { printable.put("complete", SummaryHelper.formatForDisplay(this.complete, 35)); printable.put("isAddressChange", SummaryHelper.formatForDisplay(this.isAddressChange, null)); printable.put("postalCode", SummaryHelper.formatForDisplay(this.postalCode, null)); - printable.put("privateMailboxNumber", SummaryHelper.formatForDisplay(this.privateMailboxNumber, null)); + printable + .put("privateMailboxNumber", SummaryHelper.formatForDisplay(this.privateMailboxNumber, null)); printable.put("state", SummaryHelper.formatForDisplay(this.state, null)); printable.put("street", SummaryHelper.formatForDisplay(this.street, 25)); printable.put("unit", SummaryHelper.formatForDisplay(this.unit, 15)); @@ -119,7 +118,8 @@ private Map printableValues() { printable.put("complete", SummaryHelper.formatForDisplay(this.complete, null)); printable.put("isAddressChange", SummaryHelper.formatForDisplay(this.isAddressChange, null)); printable.put("postalCode", SummaryHelper.formatForDisplay(this.postalCode, null)); - printable.put("privateMailboxNumber", SummaryHelper.formatForDisplay(this.privateMailboxNumber, null)); + printable + .put("privateMailboxNumber", SummaryHelper.formatForDisplay(this.privateMailboxNumber, null)); printable.put("state", SummaryHelper.formatForDisplay(this.state, null)); printable.put("street", SummaryHelper.formatForDisplay(this.street, null)); printable.put("unit", SummaryHelper.formatForDisplay(this.unit, null)); diff --git a/src/main/java/com/mindee/product/us/usmail/UsMailV3SenderAddress.java b/src/main/java/com/mindee/product/us/usmail/UsMailV3SenderAddress.java index 1206ba06c..45f89ca48 100644 --- a/src/main/java/com/mindee/product/us/usmail/UsMailV3SenderAddress.java +++ b/src/main/java/com/mindee/product/us/usmail/UsMailV3SenderAddress.java @@ -42,13 +42,11 @@ public class UsMailV3SenderAddress extends BaseField { String street; public boolean isEmpty() { - return ( - (city == null || city.isEmpty()) - && (complete == null || complete.isEmpty()) - && (postalCode == null || postalCode.isEmpty()) - && (state == null || state.isEmpty()) - && (street == null || street.isEmpty()) - ); + return ((city == null || city.isEmpty()) + && (complete == null || complete.isEmpty()) + && (postalCode == null || postalCode.isEmpty()) + && (state == null || state.isEmpty()) + && (street == null || street.isEmpty())); } /** @@ -57,10 +55,10 @@ public boolean isEmpty() { public String toFieldList() { Map printable = this.printableValues(); return String.format(" :City: %s%n", printable.get("city")) - + String.format(" :Complete Address: %s%n", printable.get("complete")) - + String.format(" :Postal Code: %s%n", printable.get("postalCode")) - + String.format(" :State: %s%n", printable.get("state")) - + String.format(" :Street: %s%n", printable.get("street")); + + String.format(" :Complete Address: %s%n", printable.get("complete")) + + String.format(" :Postal Code: %s%n", printable.get("postalCode")) + + String.format(" :State: %s%n", printable.get("state")) + + String.format(" :Street: %s%n", printable.get("street")); } @Override diff --git a/src/test/java/com/mindee/MindeeClientTest.java b/src/test/java/com/mindee/MindeeClientTest.java index 68c182102..4264532c1 100644 --- a/src/test/java/com/mindee/MindeeClientTest.java +++ b/src/test/java/com/mindee/MindeeClientTest.java @@ -51,31 +51,29 @@ public void setUp() { } @Test - void givenAClientForCustom_withFile_parse_thenShouldCallMindeeApi() - throws IOException { + void givenAClientForCustom_withFile_parse_thenShouldCallMindeeApi() throws IOException { PredictResponse predictResponse = new PredictResponse(); predictResponse.setDocument(new Document<>()); predictResponse.setApiRequest(null); - Mockito.when( - mindeeApi.predictPost( - Mockito.any(), - Mockito.any(), - Mockito.any())) - .thenReturn(predictResponse); - - PredictResponse document = client.parse( + Mockito + .when(mindeeApi.predictPost(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(predictResponse); + + PredictResponse document = client + .parse( new LocalInputSource(getResourcePath("file_types/pdf/blank_1.pdf")), - new Endpoint("", "", "")); + new Endpoint("", "", "") + ); Assertions.assertNotNull(document); - Mockito.verify(mindeeApi, Mockito.times(1)) - .predictPost(Mockito.any(), Mockito.any(), Mockito.any()); + Mockito + .verify(mindeeApi, Mockito.times(1)) + .predictPost(Mockito.any(), Mockito.any(), Mockito.any()); } @Test - void givenAClientForCustomAndPageOptions_parse_thenShouldOperateCutOnPagesAndCallTheHttpClientCorrectly() - throws IOException { + void givenAClientForCustomAndPageOptions_parse_thenShouldOperateCutOnPagesAndCallTheHttpClientCorrectly() throws IOException { List pageNumberToKeep = new ArrayList<>(); pageNumberToKeep.add(1); @@ -83,160 +81,142 @@ void givenAClientForCustomAndPageOptions_parse_thenShouldOperateCutOnPagesAndCal PredictResponse predictResponse = new PredictResponse(); predictResponse.setDocument(new Document<>()); predictResponse.setApiRequest(null); - Mockito.when( - mindeeApi.predictPost( - Mockito.any(), - Mockito.any(), - Mockito.any())) - .thenReturn(predictResponse); - Mockito.when(pdfOperation.split(Mockito.any())) - .thenReturn(new SplitPdf(new byte[0], 0)); - - PredictResponse document = client.parse( + Mockito + .when(mindeeApi.predictPost(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(predictResponse); + Mockito.when(pdfOperation.split(Mockito.any())).thenReturn(new SplitPdf(new byte[0], 0)); + + PredictResponse document = client + .parse( new LocalInputSource(getResourcePath("file_types/pdf/multipage.pdf")), new Endpoint("", "", ""), - new PageOptions( - pageNumberToKeep, PageOptionsOperation.KEEP_ONLY, 0)); + new PageOptions(pageNumberToKeep, PageOptionsOperation.KEEP_ONLY, 0) + ); Assertions.assertNotNull(document); - Mockito.verify(mindeeApi, Mockito.times(1)) - .predictPost(Mockito.any(), Mockito.any(), Mockito.any()); - Mockito.verify(pdfOperation, Mockito.times(1)) - .split(Mockito.any()); + Mockito + .verify(mindeeApi, Mockito.times(1)) + .predictPost(Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.verify(pdfOperation, Mockito.times(1)).split(Mockito.any()); } @Test - void givenAClientForInvoice_withFile_parse_thenShouldCallMindeeApi() - throws IOException { + void givenAClientForInvoice_withFile_parse_thenShouldCallMindeeApi() throws IOException { PredictResponse predictResponse = new PredictResponse(); predictResponse.setDocument(new Document<>()); predictResponse.setApiRequest(null); - Mockito.when( - mindeeApi.predictPost( - Mockito.any(), - Mockito.any(), - Mockito.any())) - .thenReturn(predictResponse); + Mockito + .when(mindeeApi.predictPost(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(predictResponse); - PredictResponse document = client.parse( - InvoiceV4.class, - new LocalInputSource(getResourcePath("file_types/pdf/blank_1.pdf"))); + PredictResponse document = client + .parse(InvoiceV4.class, new LocalInputSource(getResourcePath("file_types/pdf/blank_1.pdf"))); Assertions.assertNotNull(document); - Mockito.verify(mindeeApi, Mockito.times(1)) - .predictPost(Mockito.any(), Mockito.any(), Mockito.any()); + Mockito + .verify(mindeeApi, Mockito.times(1)) + .predictPost(Mockito.any(), Mockito.any(), Mockito.any()); } @Test - void givenAClientForInvoice_withInputStream_parse_thenShouldCallMindeeApi() - throws IOException { + void givenAClientForInvoice_withInputStream_parse_thenShouldCallMindeeApi() throws IOException { PredictResponse predictResponse = new PredictResponse(); predictResponse.setDocument(new Document<>()); predictResponse.setApiRequest(null); - Mockito.when( - mindeeApi.predictPost( - Mockito.any(), - Mockito.any(), - Mockito.any())) - .thenReturn(predictResponse); - - PredictResponse document = client.parse( + Mockito + .when(mindeeApi.predictPost(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(predictResponse); + + PredictResponse document = client + .parse( InvoiceV4.class, new LocalInputSource( - Files.newInputStream(getResourcePath("file_types/pdf/blank_1.pdf")), - "")); + Files.newInputStream(getResourcePath("file_types/pdf/blank_1.pdf")), + "" + ) + ); Assertions.assertNotNull(document); - Mockito.verify(mindeeApi, Mockito.times(1)) - .predictPost(Mockito.any(), Mockito.any(), Mockito.any()); + Mockito + .verify(mindeeApi, Mockito.times(1)) + .predictPost(Mockito.any(), Mockito.any(), Mockito.any()); } @Test - void givenAClientForInvoice_withByteArray_parse_thenShouldCallMindeeApi() - throws IOException { + void givenAClientForInvoice_withByteArray_parse_thenShouldCallMindeeApi() throws IOException { PredictResponse predictResponse = new PredictResponse(); predictResponse.setDocument(new Document<>()); predictResponse.setApiRequest(null); - Mockito.when( - mindeeApi.predictPost( - Mockito.any(), - Mockito.any(), - Mockito.any())) - .thenReturn(predictResponse); - - PredictResponse document = client.parse( + Mockito + .when(mindeeApi.predictPost(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(predictResponse); + + PredictResponse document = client + .parse( InvoiceV4.class, - new LocalInputSource( - Files.readAllBytes(getResourcePath("file_types/pdf/blank_1.pdf")), - "")); + new LocalInputSource(Files.readAllBytes(getResourcePath("file_types/pdf/blank_1.pdf")), "") + ); Assertions.assertNotNull(document); - Mockito.verify(mindeeApi, Mockito.times(1)) - .predictPost(Mockito.any(), Mockito.any(), Mockito.any()); + Mockito + .verify(mindeeApi, Mockito.times(1)) + .predictPost(Mockito.any(), Mockito.any(), Mockito.any()); } @Test - void givenAClientForInvoiceAndPageOptions_parse_thenShouldOperateCutOnPagesAndCallTheHttpClientCorrectly() - throws IOException { + void givenAClientForInvoiceAndPageOptions_parse_thenShouldOperateCutOnPagesAndCallTheHttpClientCorrectly() throws IOException { List pageNumberToKeep = new ArrayList<>(); pageNumberToKeep.add(1); PredictResponse predictResponse = new PredictResponse(); predictResponse.setDocument(new Document<>()); predictResponse.setApiRequest(null); - Mockito.when( - mindeeApi.predictPost( - Mockito.any(), - Mockito.any(), - Mockito.any())) - .thenReturn(predictResponse); - Mockito.when( - pdfOperation.split( - Mockito.any())) - .thenReturn(new SplitPdf(new byte[0], 0)); - - PredictResponse document = client.parse( + Mockito + .when(mindeeApi.predictPost(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(predictResponse); + Mockito.when(pdfOperation.split(Mockito.any())).thenReturn(new SplitPdf(new byte[0], 0)); + + PredictResponse document = client + .parse( InvoiceV4.class, new LocalInputSource(getResourcePath("file_types/pdf/multipage.pdf")), - new PageOptions( - pageNumberToKeep, PageOptionsOperation.KEEP_ONLY, 0)); + new PageOptions(pageNumberToKeep, PageOptionsOperation.KEEP_ONLY, 0) + ); Assertions.assertNotNull(document); - Mockito.verify(mindeeApi, Mockito.times(1)) - .predictPost(Mockito.any(), Mockito.any(), Mockito.any()); - Mockito.verify(pdfOperation, Mockito.times(1)) - .split(Mockito.any()); + Mockito + .verify(mindeeApi, Mockito.times(1)) + .predictPost(Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.verify(pdfOperation, Mockito.times(1)).split(Mockito.any()); } @Test void givenADocumentUrl_whenParsed_shouldCallApiWithCorrectParams() throws IOException { ArgumentCaptor classArgumentCaptor = ArgumentCaptor.forClass(Class.class); - ArgumentCaptor requestParametersArgumentCaptor = ArgumentCaptor.forClass( - RequestParameters.class); + ArgumentCaptor requestParametersArgumentCaptor = ArgumentCaptor + .forClass(RequestParameters.class); URL docUrl = new URL("https://this.document.does.not.exist"); PredictResponse predictResponse = new PredictResponse(); predictResponse.setDocument(new Document<>()); predictResponse.setApiRequest(null); - Mockito.when( - mindeeApi.predictPost( - Mockito.any(), - Mockito.any(), - Mockito.any())) - .thenReturn(predictResponse); + Mockito + .when(mindeeApi.predictPost(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(predictResponse); PredictResponse document = client.parse(InvoiceV4.class, docUrl); - Mockito.verify(mindeeApi, Mockito.times(1)) - .predictPost( - classArgumentCaptor.capture(), - Mockito.any(), - requestParametersArgumentCaptor.capture() - ); + Mockito + .verify(mindeeApi, Mockito.times(1)) + .predictPost( + classArgumentCaptor.capture(), + Mockito.any(), + requestParametersArgumentCaptor.capture() + ); Assertions.assertEquals(InvoiceV4.class, classArgumentCaptor.getValue()); Assertions.assertEquals(docUrl, requestParametersArgumentCaptor.getValue().getFileUrl()); Assertions.assertNull(requestParametersArgumentCaptor.getValue().getFile()); @@ -247,30 +227,27 @@ void givenADocumentUrl_whenParsed_shouldCallApiWithCorrectParams() throws IOExce void givenACustomDocumentUrl_whenParsed_shouldCallApiWithCorrectParams() throws IOException { ArgumentCaptor classArgumentCaptor = ArgumentCaptor.forClass(Class.class); - ArgumentCaptor endpointArgumentCaptor = ArgumentCaptor.forClass( - Endpoint.class); - ArgumentCaptor requestParametersArgumentCaptor = ArgumentCaptor.forClass( - RequestParameters.class); + ArgumentCaptor endpointArgumentCaptor = ArgumentCaptor.forClass(Endpoint.class); + ArgumentCaptor requestParametersArgumentCaptor = ArgumentCaptor + .forClass(RequestParameters.class); URL docUrl = new URL("https://this.document.does.not.exist"); Endpoint endpoint = new Endpoint("dsddw", "dcsdcd", "dsfdd"); PredictResponse predictResponse = new PredictResponse(); predictResponse.setDocument(new Document<>()); predictResponse.setApiRequest(null); - Mockito.when( - mindeeApi.predictPost( - Mockito.any(), - Mockito.any(), - Mockito.any())) - .thenReturn(predictResponse); + Mockito + .when(mindeeApi.predictPost(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(predictResponse); PredictResponse document = client.parse(docUrl, endpoint); - Mockito.verify(mindeeApi, Mockito.times(1)) - .predictPost( - classArgumentCaptor.capture(), - endpointArgumentCaptor.capture(), - requestParametersArgumentCaptor.capture() - ); + Mockito + .verify(mindeeApi, Mockito.times(1)) + .predictPost( + classArgumentCaptor.capture(), + endpointArgumentCaptor.capture(), + requestParametersArgumentCaptor.capture() + ); Assertions.assertEquals(CustomV1.class, classArgumentCaptor.getValue()); Assertions.assertEquals(docUrl, requestParametersArgumentCaptor.getValue().getFileUrl()); Assertions.assertEquals(endpoint, endpointArgumentCaptor.getValue()); @@ -282,7 +259,7 @@ void givenACustomDocumentUrl_whenParsed_shouldCallApiWithCorrectParams() throws void givenAnAsyncDoc_whenEnqueued_shouldInvokeApiCorrectly() throws IOException { LocalInputSource localInputSource = new LocalInputSource( - getResourcePath("file_types/pdf/blank_1.pdf") + getResourcePath("file_types/pdf/blank_1.pdf") ); Job job = new Job(LocalDateTime.now(), "someid", LocalDateTime.now(), "Completed", null); @@ -290,25 +267,25 @@ void givenAnAsyncDoc_whenEnqueued_shouldInvokeApiCorrectly() throws IOException predictResponse.setDocument(new Document<>()); predictResponse.setApiRequest(null); predictResponse.setJob(job); - Mockito.when( - mindeeApi.predictAsyncPost( - Mockito.any(), - Mockito.any(), - Mockito.any())) - .thenReturn(predictResponse); + Mockito + .when(mindeeApi.predictAsyncPost(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(predictResponse); PredictOptions predictOptions = PredictOptions.builder().allWords(Boolean.TRUE).build(); - String jobId = client.enqueue(InvoiceV4.class, localInputSource, predictOptions, null) - .getJob().getId(); + String jobId = client + .enqueue(InvoiceV4.class, localInputSource, predictOptions, null) + .getJob() + .getId(); ArgumentCaptor classArgumentCaptor = ArgumentCaptor.forClass(Class.class); - ArgumentCaptor requestParametersArgumentCaptor = ArgumentCaptor.forClass( - RequestParameters.class); - Mockito.verify(mindeeApi, Mockito.times(1)) - .predictAsyncPost( - classArgumentCaptor.capture(), - Mockito.any(), - requestParametersArgumentCaptor.capture() - ); + ArgumentCaptor requestParametersArgumentCaptor = ArgumentCaptor + .forClass(RequestParameters.class); + Mockito + .verify(mindeeApi, Mockito.times(1)) + .predictAsyncPost( + classArgumentCaptor.capture(), + Mockito.any(), + requestParametersArgumentCaptor.capture() + ); RequestParameters requestParameters = requestParametersArgumentCaptor.getValue(); Assertions.assertEquals(InvoiceV4.class, classArgumentCaptor.getValue()); Assertions.assertEquals("blank_1.pdf", requestParameters.getFileName()); @@ -323,7 +300,7 @@ void givenAnAsyncDoc_whenEnqueued_shouldInvokeApiCorrectly() throws IOException void givenAnAsyncDoc_whenEnqueuedNoParams_shouldInvokeApiCorrectly() throws IOException { LocalInputSource localInputSource = new LocalInputSource( - getResourcePath("file_types/pdf/blank_1.pdf") + getResourcePath("file_types/pdf/blank_1.pdf") ); Job job = new Job(LocalDateTime.now(), "someid", LocalDateTime.now(), "Completed", null); @@ -331,19 +308,16 @@ void givenAnAsyncDoc_whenEnqueuedNoParams_shouldInvokeApiCorrectly() throws IOEx predictResponse.setDocument(new Document<>()); predictResponse.setApiRequest(null); predictResponse.setJob(job); - Mockito.when( - mindeeApi.predictAsyncPost( - Mockito.any(), - Mockito.any(), - Mockito.any())) + Mockito + .when(mindeeApi.predictAsyncPost(Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(predictResponse); - String jobId = client.enqueue(InvoiceV4.class, localInputSource) - .getJob().getId(); + String jobId = client.enqueue(InvoiceV4.class, localInputSource).getJob().getId(); ArgumentCaptor classArgumentCaptor = ArgumentCaptor.forClass(Class.class); - ArgumentCaptor requestParametersArgumentCaptor = ArgumentCaptor.forClass( - RequestParameters.class); - Mockito.verify(mindeeApi, Mockito.times(1)) + ArgumentCaptor requestParametersArgumentCaptor = ArgumentCaptor + .forClass(RequestParameters.class); + Mockito + .verify(mindeeApi, Mockito.times(1)) .predictAsyncPost( classArgumentCaptor.capture(), Mockito.any(), @@ -367,23 +341,20 @@ void givenAnAsyncUrl_whenEnqueued_shouldInvokeApiCorrectly() throws IOException predictResponse.setDocument(new Document<>()); predictResponse.setApiRequest(null); predictResponse.setJob(job); - Mockito.when( - mindeeApi.predictAsyncPost( - Mockito.any(), - Mockito.any(), - Mockito.any())) - .thenReturn(predictResponse); - String jobId = client.enqueue(InvoiceV4.class, new URL("https://fake.pdf")) - .getJob().getId(); + Mockito + .when(mindeeApi.predictAsyncPost(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(predictResponse); + String jobId = client.enqueue(InvoiceV4.class, new URL("https://fake.pdf")).getJob().getId(); ArgumentCaptor classArgumentCaptor = ArgumentCaptor.forClass(Class.class); - ArgumentCaptor requestParametersArgumentCaptor = ArgumentCaptor.forClass( - RequestParameters.class); - Mockito.verify(mindeeApi, Mockito.times(1)) - .predictAsyncPost( - classArgumentCaptor.capture(), - Mockito.any(), - requestParametersArgumentCaptor.capture() - ); + ArgumentCaptor requestParametersArgumentCaptor = ArgumentCaptor + .forClass(RequestParameters.class); + Mockito + .verify(mindeeApi, Mockito.times(1)) + .predictAsyncPost( + classArgumentCaptor.capture(), + Mockito.any(), + requestParametersArgumentCaptor.capture() + ); RequestParameters requestParameters = requestParametersArgumentCaptor.getValue(); Assertions.assertEquals(InvoiceV4.class, classArgumentCaptor.getValue()); Assertions.assertNull(requestParameters.getFileName()); @@ -397,7 +368,7 @@ void givenAnAsyncUrl_whenEnqueued_shouldInvokeApiCorrectly() throws IOException void givenAnAsyncGeneratedDoc_whenEnqueuedNoParams_shouldInvokeApiCorrectly() throws IOException, InterruptedException { LocalInputSource localInputSource = new LocalInputSource( - getResourcePath("file_types/pdf/blank_1.pdf") + getResourcePath("file_types/pdf/blank_1.pdf") ); Job job = new Job(LocalDateTime.now(), "someid", LocalDateTime.now(), "Completed", null); Endpoint endpoint = new Endpoint("dsddw", "dcsdcd", "dsfdd"); @@ -405,19 +376,16 @@ void givenAnAsyncGeneratedDoc_whenEnqueuedNoParams_shouldInvokeApiCorrectly() th predictResponse.setDocument(new Document<>()); predictResponse.setApiRequest(null); predictResponse.setJob(job); - Mockito.when( - mindeeApi.predictAsyncPost( - Mockito.any(), - Mockito.any(), - Mockito.any())) + Mockito + .when(mindeeApi.predictAsyncPost(Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(predictResponse); - String jobId = client.enqueue(GeneratedV1.class, endpoint, localInputSource) - .getJob().getId(); + String jobId = client.enqueue(GeneratedV1.class, endpoint, localInputSource).getJob().getId(); ArgumentCaptor classArgumentCaptor = ArgumentCaptor.forClass(Class.class); - ArgumentCaptor requestParametersArgumentCaptor = ArgumentCaptor.forClass( - RequestParameters.class); - Mockito.verify(mindeeApi, Mockito.times(1)) + ArgumentCaptor requestParametersArgumentCaptor = ArgumentCaptor + .forClass(RequestParameters.class); + Mockito + .verify(mindeeApi, Mockito.times(1)) .predictAsyncPost( classArgumentCaptor.capture(), Mockito.any(), @@ -437,21 +405,22 @@ void givenAnAsyncGeneratedDoc_whenEnqueuedNoParams_shouldInvokeApiCorrectly() th void givenJsonInput_whenSync_shouldDeserializeCorrectly() throws IOException { File file = new File(getV1ResourcePathString("products/invoices/response_v4/complete.json")); LocalResponse localResponse = new LocalResponse(file); - AsyncPredictResponse predictResponse = client.loadPrediction(InvoiceV4.class, localResponse); + AsyncPredictResponse predictResponse = client + .loadPrediction(InvoiceV4.class, localResponse); assertStringEqualsFile( predictResponse.getDocumentObj().toString(), - getV1ResourcePathString("/products/invoices/response_v4/summary_full.rst") + getV1ResourcePathString("/products/invoices/response_v4/summary_full.rst") ); } @Test void givenJsonInput_whenAsync_shouldDeserializeCorrectly() throws IOException { - File file = new File(getV1ResourcePathString("products/international_id/response_v2/complete.json")); - LocalResponse localResponse = new LocalResponse(file); - AsyncPredictResponse predictResponse = client.loadPrediction( - InternationalIdV2.class, - localResponse + File file = new File( + getV1ResourcePathString("products/international_id/response_v2/complete.json") ); + LocalResponse localResponse = new LocalResponse(file); + AsyncPredictResponse predictResponse = client + .loadPrediction(InternationalIdV2.class, localResponse); assertStringEqualsFile( predictResponse.getDocumentObj().toString(), getV1ResourcePathString("products/international_id/response_v2/summary_full.rst") diff --git a/src/test/java/com/mindee/MindeeClientV2IT.java b/src/test/java/com/mindee/MindeeClientV2IT.java index 0f3e6af55..296690cf8 100644 --- a/src/test/java/com/mindee/MindeeClientV2IT.java +++ b/src/test/java/com/mindee/MindeeClientV2IT.java @@ -38,24 +38,20 @@ void setUp() { @DisplayName("Empty, multi-page PDF – enqueue & parse must succeed") void parseFile_emptyMultiPage_mustSucceed() throws IOException, InterruptedException { LocalInputSource source = new LocalInputSource( - getResourcePath("file_types/pdf/multipage_cut-2.pdf") + getResourcePath("file_types/pdf/multipage_cut-2.pdf") ); InferenceParameters params = InferenceParameters - .builder(modelId) - .rag(false) - .rawText(true) - .polygon(null) - .confidence(null) - .alias("java-integration-test_multipage") - .textContext(null) - .pollingOptions( - AsyncPollingOptions.builder() - .initialDelaySec(3.0) - .intervalSec(1.5) - .maxRetries(80) - .build() - ) - .build(); + .builder(modelId) + .rag(false) + .rawText(true) + .polygon(null) + .confidence(null) + .alias("java-integration-test_multipage") + .textContext(null) + .pollingOptions( + AsyncPollingOptions.builder().initialDelaySec(3.0).intervalSec(1.5).maxRetries(80).build() + ) + .build(); InferenceResponse response = mindeeClient.enqueueAndGetInference(source, params); assertNotNull(response); @@ -91,14 +87,15 @@ void parseFile_emptyMultiPage_mustSucceed() throws IOException, InterruptedExcep @DisplayName("Filled, single-page image – enqueue & parse must succeed") void parseFile_filledSinglePage_mustSucceed() throws IOException, InterruptedException { LocalInputSource source = new LocalInputSource( - getV2ResourcePath("products/financial_document/default_sample.jpg")); + getV2ResourcePath("products/financial_document/default_sample.jpg") + ); InferenceParameters params = InferenceParameters - .builder(modelId) - .rag(false) - .alias("java-integration-test_single-page") - .textContext("this is an invoice") - .build(); + .builder(modelId) + .rag(false) + .alias("java-integration-test_single-page") + .textContext("this is an invoice") + .build(); InferenceResponse response = mindeeClient.enqueueAndGetInference(source, params); assertNotNull(response); @@ -138,14 +135,15 @@ void parseFile_filledSinglePage_mustSucceed() throws IOException, InterruptedExc @DisplayName("Data Schema Replace – enqueue & parse must succeed") void parseFile_dataSchemaReplace_mustSucceed() throws IOException, InterruptedException { LocalInputSource source = new LocalInputSource( - getV2ResourcePath("products/financial_document/default_sample.jpg")); + getV2ResourcePath("products/financial_document/default_sample.jpg") + ); InferenceParameters params = InferenceParameters - .builder(modelId) - .rag(false) - .alias("java-integration-test_data-schema-replace") - .dataSchema(readFileAsString(getV2ResourcePath("inference/data_schema_replace_param.json"))) - .build(); + .builder(modelId) + .rag(false) + .alias("java-integration-test_data-schema-replace") + .dataSchema(readFileAsString(getV2ResourcePath("inference/data_schema_replace_param.json"))) + .build(); InferenceResponse response = mindeeClient.enqueueAndGetInference(source, params); assertNotNull(response); @@ -166,21 +164,18 @@ void parseFile_dataSchemaReplace_mustSucceed() throws IOException, InterruptedEx assertEquals("a test value", supplierName.getStringValue()); } - @Test @DisplayName("Invalid model ID – enqueue must raise 422") void invalidModel_mustThrowError() throws IOException { - LocalInputSource source = new LocalInputSource( - getResourcePath("file_types/pdf/blank_1.pdf") - ); + LocalInputSource source = new LocalInputSource(getResourcePath("file_types/pdf/blank_1.pdf")); InferenceParameters params = InferenceParameters - .builder("INVALID_MODEL_ID") - .textContext("this is invalid") - .build(); + .builder("INVALID_MODEL_ID") + .textContext("this is invalid") + .build(); MindeeHttpExceptionV2 ex = assertThrows( - MindeeHttpExceptionV2.class, - () -> mindeeClient.enqueueInference(source, params) + MindeeHttpExceptionV2.class, + () -> mindeeClient.enqueueInference(source, params) ); assertEquals(422, ex.getStatus()); } @@ -188,17 +183,15 @@ void invalidModel_mustThrowError() throws IOException { @Test @DisplayName("Invalid webhook ID – enqueue must raise 422") void invalidWebhook_mustThrowError() throws IOException { - LocalInputSource source = new LocalInputSource( - getResourcePath("file_types/pdf/blank_1.pdf") - ); + LocalInputSource source = new LocalInputSource(getResourcePath("file_types/pdf/blank_1.pdf")); InferenceParameters params = InferenceParameters - .builder(modelId) - .webhookIds(new String[]{"INVALID_WEBHOOK_ID"}) - .build(); + .builder(modelId) + .webhookIds(new String[] { "INVALID_WEBHOOK_ID" }) + .build(); MindeeHttpExceptionV2 ex = assertThrows( - MindeeHttpExceptionV2.class, - () -> mindeeClient.enqueueInference(source, params) + MindeeHttpExceptionV2.class, + () -> mindeeClient.enqueueInference(source, params) ); assertEquals(422, ex.getStatus()); } @@ -207,8 +200,8 @@ void invalidWebhook_mustThrowError() throws IOException { @DisplayName("Invalid job ID – parseQueued must raise an error") void invalidJob_mustThrowError() { MindeeHttpExceptionV2 ex = assertThrows( - MindeeHttpExceptionV2.class, - () -> mindeeClient.getInference("INVALID_JOB_ID") + MindeeHttpExceptionV2.class, + () -> mindeeClient.getInference("INVALID_JOB_ID") ); assertEquals(422, ex.getStatus()); assertNotNull(ex); @@ -217,11 +210,11 @@ void invalidJob_mustThrowError() { @Test @DisplayName("URL input source - A url param should not raise errors.") void urlInputSource_mustNotRaiseErrors() throws IOException, InterruptedException { - URLInputSource urlSource = URLInputSource.builder(System.getenv("MINDEE_V2_SE_TESTS_BLANK_PDF_URL")).build(); + URLInputSource urlSource = URLInputSource + .builder(System.getenv("MINDEE_V2_SE_TESTS_BLANK_PDF_URL")) + .build(); - InferenceParameters options = InferenceParameters - .builder(modelId) - .build(); + InferenceParameters options = InferenceParameters.builder(modelId).build(); InferenceResponse response = mindeeClient.enqueueAndGetInference(urlSource, options); diff --git a/src/test/java/com/mindee/MindeeClientV2Test.java b/src/test/java/com/mindee/MindeeClientV2Test.java index e01c64e83..67a5a0179 100644 --- a/src/test/java/com/mindee/MindeeClientV2Test.java +++ b/src/test/java/com/mindee/MindeeClientV2Test.java @@ -35,21 +35,23 @@ class Enqueue { @DisplayName("sends exactly one HTTP call and yields a non-null response") void enqueue_post_async() throws IOException { MindeeApiV2 predictable = Mockito.mock(MindeeApiV2.class); - when(predictable.reqPostInferenceEnqueue(any(LocalInputSource.class), any(InferenceParameters.class))) - .thenReturn(new JobResponse()); + when( + predictable + .reqPostInferenceEnqueue(any(LocalInputSource.class), any(InferenceParameters.class)) + ).thenReturn(new JobResponse()); MindeeClientV2 mindeeClient = makeClientWithMockedApi(predictable); - LocalInputSource input = - new LocalInputSource(getResourcePath("file_types/pdf/blank_1.pdf")); - JobResponse response = mindeeClient.enqueueInference( + LocalInputSource input = new LocalInputSource(getResourcePath("file_types/pdf/blank_1.pdf")); + JobResponse response = mindeeClient + .enqueueInference( input, InferenceParameters.builder("dummy-model-id").textContext("test text context").build() - ); + ); assertNotNull(response, "enqueue() must return a response"); verify(predictable, atMostOnce()) - .reqPostInferenceEnqueue(any(LocalInputSource.class), any(InferenceParameters.class)); + .reqPostInferenceEnqueue(any(LocalInputSource.class), any(InferenceParameters.class)); } } @@ -66,8 +68,7 @@ void document_getJob_async() throws JsonProcessingException { JobResponse processing = mapper.readValue(json, JobResponse.class); - when(predictable.reqGetJob(anyString())) - .thenReturn(processing); + when(predictable.reqGetJob(anyString())).thenReturn(processing); MindeeClientV2 mindeeClient = makeClientWithMockedApi(predictable); @@ -77,7 +78,6 @@ void document_getJob_async() throws JsonProcessingException { } } - @Nested @DisplayName("getInference()") class GetInference { @@ -86,30 +86,36 @@ class GetInference { void document_getInference_async() throws IOException { MindeeApiV2 predictable = Mockito.mock(MindeeApiV2.class); - String json = FileUtils.readFileToString( - getResourcePath("v2/products/financial_document/complete.json").toFile() - ); + String json = FileUtils + .readFileToString(getResourcePath("v2/products/financial_document/complete.json").toFile()); ObjectMapper mapper = new ObjectMapper(); mapper.findAndRegisterModules(); InferenceResponse processing = mapper.readValue(json, InferenceResponse.class); - when(predictable.reqGetInference(anyString())) - .thenReturn(processing); + when(predictable.reqGetInference(anyString())).thenReturn(processing); MindeeClientV2 mindeeClient = makeClientWithMockedApi(predictable); - InferenceResponse response = mindeeClient.getInference("12345678-1234-1234-1234-123456789abc"); + InferenceResponse response = mindeeClient + .getInference("12345678-1234-1234-1234-123456789abc"); assertNotNull(response, "getInference() must return a response"); assertEquals( - 21, response.getInference().getResult().getFields().size(), - "Result must have one field" + 21, + response.getInference().getResult().getFields().size(), + "Result must have one field" ); assertEquals( - "John Smith", - response.getInference().getResult().getFields().get("supplier_name").getSimpleField().getValue(), - "Result must deserialize fields properly." + "John Smith", + response + .getInference() + .getResult() + .getFields() + .get("supplier_name") + .getSimpleField() + .getValue(), + "Result must deserialize fields properly." ); verify(predictable, atMostOnce()).reqGetInference(anyString()); } @@ -123,25 +129,26 @@ class DeserializeResponse { @DisplayName("parses local JSON and exposes correct field values") void inference_loadsLocally() throws IOException { LocalResponse localResponse = new LocalResponse( - getResourcePath("v2/products/financial_document/complete.json") + getResourcePath("v2/products/financial_document/complete.json") ); InferenceResponse loaded = localResponse.deserializeResponse(InferenceResponse.class); assertNotNull(loaded, "Loaded InferenceResponse must not be null"); assertEquals( - "12345678-1234-1234-1234-123456789abc", - loaded.getInference().getModel().getId(), - "Model Id mismatch" + "12345678-1234-1234-1234-123456789abc", + loaded.getInference().getModel().getId(), + "Model Id mismatch" ); assertEquals( - "John Smith", - loaded.getInference() - .getResult() - .getFields() - .get("supplier_name") - .getSimpleField() - .getValue(), - "Supplier name mismatch" + "John Smith", + loaded + .getInference() + .getResult() + .getFields() + .get("supplier_name") + .getSimpleField() + .getValue(), + "Supplier name mismatch" ); } } diff --git a/src/test/java/com/mindee/TestingUtilities.java b/src/test/java/com/mindee/TestingUtilities.java index cba05f158..560a5f627 100644 --- a/src/test/java/com/mindee/TestingUtilities.java +++ b/src/test/java/com/mindee/TestingUtilities.java @@ -25,9 +25,7 @@ public static String getV1ResourcePathString(String filePath) { return getV1ResourcePath(filePath).toString(); } - public static String readFileAsString(Path path) - throws IOException - { + public static String readFileAsString(Path path) throws IOException { byte[] encoded = Files.readAllBytes(path); return new String(encoded); } @@ -85,7 +83,8 @@ public static String getFileName(String rstStr) { /** * Compute the Levenshtein distance between two strings. - * Taken & adapted from here + * Taken & adapted from here * * @param refStr Source string to compare. * @param targetStr Target string to compare. @@ -122,11 +121,13 @@ private static int levenshteinDistance(String refStr, String targetStr) { int previousDistance = i - 1; int minDistance = previousDistance; for (int j = 1; j <= targetLength; j++) { - int currentDistance = - previousDistance + (refStr.charAt(i - 1) == targetStr.charAt(j - 1) ? 0 : 1); - distanceVector[j] = - Math.min(Math.min(1 + (previousDistance = distanceVector[j]), 1 + distanceVector[j - 1]), - currentDistance); + int currentDistance = previousDistance + + (refStr.charAt(i - 1) == targetStr.charAt(j - 1) ? 0 : 1); + distanceVector[j] = Math + .min( + Math.min(1 + (previousDistance = distanceVector[j]), 1 + distanceVector[j - 1]), + currentDistance + ); if (previousDistance < minDistance) { minDistance = previousDistance; } @@ -139,7 +140,7 @@ private static int levenshteinDistance(String refStr, String targetStr) { * Computes the Levenshtein ratio between two given strings. * * @param referenceString First string. - * @param targetString Second string. + * @param targetString Second string. * @return The ratio of similarities between the two strings. */ public static double levenshteinRatio(String referenceString, String targetString) { diff --git a/src/test/java/com/mindee/extraction/ImageExtractorTest.java b/src/test/java/com/mindee/extraction/ImageExtractorTest.java index fe170bd33..d5798c265 100644 --- a/src/test/java/com/mindee/extraction/ImageExtractorTest.java +++ b/src/test/java/com/mindee/extraction/ImageExtractorTest.java @@ -18,35 +18,39 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; - public class ImageExtractorTest { - protected PredictResponse getMultiReceiptsPrediction(String name) throws IOException { + protected PredictResponse getMultiReceiptsPrediction( + String name + ) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - MultiReceiptsDetectorV1.class - ); - return objectMapper.readValue( - getV1ResourcePath("products/multi_receipts_detector/response_v1/" + name + ".json").toFile(), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, MultiReceiptsDetectorV1.class); + return objectMapper + .readValue( + getV1ResourcePath("products/multi_receipts_detector/response_v1/" + name + ".json") + .toFile(), + type + ); } - protected PredictResponse getBarcodeReaderPrediction(String name) throws IOException { + protected PredictResponse getBarcodeReaderPrediction( + String name + ) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - BarcodeReaderV1.class - ); - return objectMapper.readValue( - getV1ResourcePath("products/barcode_reader/response_v1/" + name + ".json").toFile(), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, BarcodeReaderV1.class); + return objectMapper + .readValue( + getV1ResourcePath("products/barcode_reader/response_v1/" + name + ".json").toFile(), + type + ); } @Test @@ -61,19 +65,19 @@ public void givenAnImage_shouldExtractPositionFields() throws IOException { Assertions.assertEquals(1, extractor.getPageCount()); for (Page page : inference.getPages()) { - List subImages = extractor.extractImagesFromPage( - page.getPrediction().getReceipts(), page.getPageId() - ); + List subImages = extractor + .extractImagesFromPage(page.getPrediction().getReceipts(), page.getPageId()); for (int i = 0; i < subImages.size(); i++) { ExtractedImage extractedImage = subImages.get(i); Assertions.assertNotNull(extractedImage.getImage()); extractedImage.writeToFile("src/test/resources/output/"); LocalInputSource source = extractedImage.asInputSource(); - Assertions.assertEquals( - String.format("default_sample_page-001_%3s.jpg", i + 1).replace(" ", "0"), - source.getFilename() - ); + Assertions + .assertEquals( + String.format("default_sample_page-001_%3s.jpg", i + 1).replace(" ", "0"), + source.getFilename() + ); } } } @@ -84,27 +88,34 @@ public void givenAnImage_shouldExtractValueFields() throws IOException { BarcodeReaderV1 inference = response.getDocument().getInference(); ImageExtractor extractor = new ImageExtractor( - getV1ResourcePathString("products/barcode_reader/default_sample.jpg") + getV1ResourcePathString("products/barcode_reader/default_sample.jpg") ); Assertions.assertEquals(1, extractor.getPageCount()); for (Page page : inference.getPages()) { - List codes1D = extractor.extractImagesFromPage( - page.getPrediction().getCodes1D(), page.getPageId(), "barcodes_1D.png" - ); + List codes1D = extractor + .extractImagesFromPage( + page.getPrediction().getCodes1D(), + page.getPageId(), + "barcodes_1D.png" + ); for (int i = 0; i < codes1D.size(); i++) { ExtractedImage extractedImage = codes1D.get(i); Assertions.assertNotNull(extractedImage.getImage()); LocalInputSource source = extractedImage.asInputSource(); - Assertions.assertEquals( - String.format("barcodes_1D_page-001_%3s.png", i + 1).replace(" ", "0"), - source.getFilename() - ); + Assertions + .assertEquals( + String.format("barcodes_1D_page-001_%3s.png", i + 1).replace(" ", "0"), + source.getFilename() + ); extractedImage.writeToFile(getResourcePath("output/")); } - List codes2D = extractor.extractImagesFromPage( - page.getPrediction().getCodes2D(), page.getPageId(),"barcodes_2D.png" - ); + List codes2D = extractor + .extractImagesFromPage( + page.getPrediction().getCodes2D(), + page.getPageId(), + "barcodes_2D.png" + ); for (ExtractedImage extractedImage : codes2D) { Assertions.assertNotNull(extractedImage.getImage()); extractedImage.writeToFile(getResourcePath("output/")); @@ -117,17 +128,17 @@ public void givenAPdf_shouldExtractPositionFields() throws IOException { LocalInputSource image = new LocalInputSource( getV1ResourcePath("products/multi_receipts_detector/multipage_sample.pdf") ); - PredictResponse response = getMultiReceiptsPrediction("multipage_sample"); + PredictResponse response = getMultiReceiptsPrediction( + "multipage_sample" + ); MultiReceiptsDetectorV1 inference = response.getDocument().getInference(); ImageExtractor extractor = new ImageExtractor(image); Assertions.assertEquals(2, extractor.getPageCount()); for (Page page : inference.getPages()) { - List subImages = extractor.extractImagesFromPage( - page.getPrediction().getReceipts(), - page.getPageId() - ); + List subImages = extractor + .extractImagesFromPage(page.getPrediction().getReceipts(), page.getPageId()); for (int i = 0; i < subImages.size(); i++) { ExtractedImage extractedImage = subImages.get(i); @@ -135,10 +146,13 @@ public void givenAPdf_shouldExtractPositionFields() throws IOException { extractedImage.writeToFile(getResourcePath("output/")); LocalInputSource source = extractedImage.asInputSource(); - Assertions.assertEquals( - String.format("multipage_sample_page-%3s_%3s.jpg", page.getPageId() + 1, i + 1).replace(" ", "0"), - source.getFilename() - ); + Assertions + .assertEquals( + String + .format("multipage_sample_page-%3s_%3s.jpg", page.getPageId() + 1, i + 1) + .replace(" ", "0"), + source.getFilename() + ); } } } diff --git a/src/test/java/com/mindee/extraction/InvoiceSplitterAutoExtractionIT.java b/src/test/java/com/mindee/extraction/InvoiceSplitterAutoExtractionIT.java index d8e5ac61f..e4d80c16b 100644 --- a/src/test/java/com/mindee/extraction/InvoiceSplitterAutoExtractionIT.java +++ b/src/test/java/com/mindee/extraction/InvoiceSplitterAutoExtractionIT.java @@ -33,20 +33,22 @@ static void clientSetUp() throws IOException { ); } - protected Document getInvoiceSplitterPrediction() throws - IOException, MindeeException, InterruptedException { - AsyncPredictResponse response = - client.enqueueAndParse(InvoiceSplitterV1.class, invoiceSplitterInputSource); + protected Document getInvoiceSplitterPrediction() throws IOException, MindeeException, InterruptedException { + AsyncPredictResponse response = client + .enqueueAndParse(InvoiceSplitterV1.class, invoiceSplitterInputSource); return response.getDocumentObj(); } - protected PredictResponse getInvoicePrediction(LocalInputSource invoicePDF) throws - IOException, MindeeException { + protected PredictResponse getInvoicePrediction( + LocalInputSource invoicePDF + ) throws IOException, MindeeException { return client.parse(InvoiceV4.class, invoicePDF); } - protected String prepareInvoiceReturn(Path rstFilePath, Document invoicePrediction) - throws IOException { + protected String prepareInvoiceReturn( + Path rstFilePath, + Document invoicePrediction + ) throws IOException { List rstRefLines = Files.readAllLines(rstFilePath); String parsingVersion = invoicePrediction.getInference().getProduct().getVersion(); String parsingId = invoicePrediction.getId(); @@ -65,41 +67,37 @@ public void givenAPDF_shouldExtractInvoices() throws IOException, InterruptedExc PDFExtractor extractor = new PDFExtractor(invoiceSplitterInputSource); Assertions.assertEquals(2, extractor.getPageCount()); - List extractedPDFsStrict = - extractor.extractInvoices(inference.getPrediction().getInvoicePageGroups(), false); + List extractedPDFsStrict = extractor + .extractInvoices(inference.getPrediction().getInvoicePageGroups(), false); Assertions.assertEquals(2, extractedPDFsStrict.size()); Assertions.assertEquals("default_sample_001-001.pdf", extractedPDFsStrict.get(0).getFilename()); Assertions.assertEquals("default_sample_002-002.pdf", extractedPDFsStrict.get(1).getFilename()); PredictResponse invoice0 = getInvoicePrediction( - extractedPDFsStrict.get(0).asInputSource() + extractedPDFsStrict.get(0).asInputSource() ); String testStringRSTInvoice0 = prepareInvoiceReturn( - getV1ResourcePath("products/invoices/response_v4/summary_full_invoice_p1.rst"), + getV1ResourcePath("products/invoices/response_v4/summary_full_invoice_p1.rst"), invoice0.getDocument() ); double invoice0Ratio = levenshteinRatio( - testStringRSTInvoice0, - String.join( - String.format("%n"), - invoice0.getDocument().toString().split(System.lineSeparator()) - ) + testStringRSTInvoice0, + String + .join(String.format("%n"), invoice0.getDocument().toString().split(System.lineSeparator())) ); Assertions.assertTrue(invoice0Ratio > 0.90); PredictResponse invoice1 = getInvoicePrediction( - extractedPDFsStrict.get(1).asInputSource() + extractedPDFsStrict.get(1).asInputSource() ); String testStringRSTInvoice1 = prepareInvoiceReturn( - getV1ResourcePath("products/invoices/response_v4/summary_full_invoice_p2.rst"), + getV1ResourcePath("products/invoices/response_v4/summary_full_invoice_p2.rst"), invoice1.getDocument() ); double invoice1Ratio = levenshteinRatio( - testStringRSTInvoice1, - String.join( - String.format("%n"), - invoice1.getDocument().toString().split(System.lineSeparator()) - ) + testStringRSTInvoice1, + String + .join(String.format("%n"), invoice1.getDocument().toString().split(System.lineSeparator())) ); Assertions.assertTrue(invoice1Ratio > 0.90); } diff --git a/src/test/java/com/mindee/extraction/PDFExtractorTest.java b/src/test/java/com/mindee/extraction/PDFExtractorTest.java index b8fb3c027..bfdaaaf8c 100644 --- a/src/test/java/com/mindee/extraction/PDFExtractorTest.java +++ b/src/test/java/com/mindee/extraction/PDFExtractorTest.java @@ -14,22 +14,20 @@ public class PDFExtractorTest { - protected PredictResponse getInvoiceSplitterPrediction() throws - IOException { + protected PredictResponse getInvoiceSplitterPrediction() throws IOException { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - InvoiceSplitterV1.class - ); - return objectMapper.readValue( - getV1ResourcePath("products/invoice_splitter/response_v1/complete.json").toFile(), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, InvoiceSplitterV1.class); + return objectMapper + .readValue( + getV1ResourcePath("products/invoice_splitter/response_v1/complete.json").toFile(), + type + ); } - @Test public void givenAPDF_shouldExtractInvoicesNoStrict() throws IOException { LocalInputSource pdf = new LocalInputSource( @@ -40,8 +38,8 @@ public void givenAPDF_shouldExtractInvoicesNoStrict() throws IOException { PDFExtractor extractor = new PDFExtractor(pdf); Assertions.assertEquals(5, extractor.getPageCount()); - List extractedPDFSNoStrict = - extractor.extractInvoices(inference.getPrediction().getInvoicePageGroups(), false); + List extractedPDFSNoStrict = extractor + .extractInvoices(inference.getPrediction().getInvoicePageGroups(), false); Assertions.assertEquals(3, extractedPDFSNoStrict.size()); Assertions.assertEquals("invoice_5p_001-001.pdf", extractedPDFSNoStrict.get(0).getFilename()); Assertions.assertEquals("invoice_5p_002-004.pdf", extractedPDFSNoStrict.get(1).getFilename()); @@ -58,8 +56,8 @@ public void givenAPDF_shouldExtractInvoicesStrict() throws IOException { PDFExtractor extractor = new PDFExtractor(pdf); Assertions.assertEquals(5, extractor.getPageCount()); - List extractedPDFStrict = - extractor.extractInvoices(inference.getPrediction().getInvoicePageGroups(), true); + List extractedPDFStrict = extractor + .extractInvoices(inference.getPrediction().getInvoicePageGroups(), true); Assertions.assertEquals(2, extractedPDFStrict.size()); Assertions.assertEquals("invoice_5p_001-001.pdf", extractedPDFStrict.get(0).getFilename()); Assertions.assertEquals("invoice_5p_002-005.pdf", extractedPDFStrict.get(1).getFilename()); diff --git a/src/test/java/com/mindee/geometry/BboxUtilsTest.java b/src/test/java/com/mindee/geometry/BboxUtilsTest.java index f348d69ed..18d71a867 100644 --- a/src/test/java/com/mindee/geometry/BboxUtilsTest.java +++ b/src/test/java/com/mindee/geometry/BboxUtilsTest.java @@ -9,16 +9,15 @@ class BboxUtilsTest { private static final Polygon polyA = new Polygon( - Arrays.asList( - new Point(0.081, 0.442), - new Point(0.15, 0.442), - new Point(0.15, 0.451), - new Point(0.081, 0.451) - ) - ); - private static final Bbox bboxA = new Bbox( - 0.081, 0.15, 0.442, 0.451 + Arrays + .asList( + new Point(0.081, 0.442), + new Point(0.15, 0.442), + new Point(0.15, 0.451), + new Point(0.081, 0.451) + ) ); + private static final Bbox bboxA = new Bbox(0.081, 0.15, 0.442, 0.451); @Test public void withZeroPolygonMustGetNull() { @@ -41,10 +40,7 @@ public void withPolygonMustGetValidBbox() { @Test public void withOnePolygonAndANullPolygonMustGetNull() { - List polygons = Arrays.asList( - BboxUtilsTest.polyA, - null - ); + List polygons = Arrays.asList(BboxUtilsTest.polyA, null); Bbox bbox = BboxUtils.generate(polygons); Assertions.assertEquals(0.442, bbox.getMinY()); @@ -55,9 +51,7 @@ public void withOnePolygonAndANullPolygonMustGetNull() { @Test public void withOnePolygonMustGetValidBbox() { - List polygons = Arrays.asList( - BboxUtilsTest.polyA - ); + List polygons = Arrays.asList(BboxUtilsTest.polyA); Bbox bbox = BboxUtils.generate(polygons); Assertions.assertEquals(0.442, bbox.getMinY()); @@ -68,13 +62,19 @@ public void withOnePolygonMustGetValidBbox() { @Test public void withTwoPolygonsMustGetValidBbox() { - List polygons = Arrays.asList( - BboxUtilsTest.polyA, - new Polygon(Arrays.asList( - new Point(0.157, 0.442), - new Point(0.26, 0.442), - new Point(0.26, 0.451), - new Point(0.157, 0.451)))); + List polygons = Arrays + .asList( + BboxUtilsTest.polyA, + new Polygon( + Arrays + .asList( + new Point(0.157, 0.442), + new Point(0.26, 0.442), + new Point(0.26, 0.451), + new Point(0.157, 0.451) + ) + ) + ); Bbox bbox = BboxUtils.generate(polygons); @@ -86,9 +86,7 @@ public void withTwoPolygonsMustGetValidBbox() { @Test public void merge2BboxMustGetValidBbox() { - List bboxs = Arrays.asList( - BboxUtilsTest.bboxA, - new Bbox(0.157, 0.26, 0.442, 0.451)); + List bboxs = Arrays.asList(BboxUtilsTest.bboxA, new Bbox(0.157, 0.26, 0.442, 0.451)); Bbox bbox = BboxUtils.merge(bboxs); diff --git a/src/test/java/com/mindee/geometry/BoundingBoxUtilsTest.java b/src/test/java/com/mindee/geometry/BoundingBoxUtilsTest.java index 177bc3578..b72afab78 100644 --- a/src/test/java/com/mindee/geometry/BoundingBoxUtilsTest.java +++ b/src/test/java/com/mindee/geometry/BoundingBoxUtilsTest.java @@ -5,60 +5,52 @@ class BoundingBoxUtilsTest { - @Test - public void bboxFromARectanglePolygonMustHaveALimitedNumberOfCoordinates() { - // given - Polygon polygonAsRectangle = PolygonSample.getPolygonAsRectangle(); - - // then - Polygon boundingBox = BoundingBoxUtils.createBoundingBoxFrom(polygonAsRectangle); - - Assertions.assertEquals(4, boundingBox.getCoordinates().size()); - } - - @Test - public void fromARectanglePolygonMustGetAValidBbox() { - // given - Polygon polygonAsRectangle = PolygonSample.getPolygonAsRectangle(); - - // then - Polygon boundingBox = BoundingBoxUtils.createBoundingBoxFrom(polygonAsRectangle); - - Assertions.assertTrue(boundingBox.getCoordinates().stream() - .anyMatch(c -> c.getX() - .equals(0.123))); - Assertions.assertTrue(boundingBox.getCoordinates().stream() - .anyMatch(c -> c.getX() - .equals(0.175))); - - Assertions.assertTrue(boundingBox.getCoordinates().stream() - .anyMatch(c -> c.getY() - .equals(0.53))); - Assertions.assertTrue(boundingBox.getCoordinates().stream() - .anyMatch(c -> c.getY() - .equals(0.546))); - } - - @Test - public void fromPolygonMustGetAValidBbox() { - // given - Polygon polygonWichIsNotRectangle = PolygonSample.getPolygonWichIsNotRectangle(); - - // then - Polygon boundingBox = BoundingBoxUtils.createBoundingBoxFrom(polygonWichIsNotRectangle); - - Assertions.assertTrue(boundingBox.getCoordinates().stream() - .anyMatch(c -> c.getX() - .equals(0.205))); - Assertions.assertTrue(boundingBox.getCoordinates().stream() - .anyMatch(c -> c.getX() - .equals(0.381))); - - Assertions.assertTrue(boundingBox.getCoordinates().stream() - .anyMatch(c -> c.getY() - .equals(0.407))); - Assertions.assertTrue(boundingBox.getCoordinates().stream() - .anyMatch(c -> c.getY() - .equals(0.43))); - } + @Test + public void bboxFromARectanglePolygonMustHaveALimitedNumberOfCoordinates() { + // given + Polygon polygonAsRectangle = PolygonSample.getPolygonAsRectangle(); + + // then + Polygon boundingBox = BoundingBoxUtils.createBoundingBoxFrom(polygonAsRectangle); + + Assertions.assertEquals(4, boundingBox.getCoordinates().size()); + } + + @Test + public void fromARectanglePolygonMustGetAValidBbox() { + // given + Polygon polygonAsRectangle = PolygonSample.getPolygonAsRectangle(); + + // then + Polygon boundingBox = BoundingBoxUtils.createBoundingBoxFrom(polygonAsRectangle); + + Assertions + .assertTrue(boundingBox.getCoordinates().stream().anyMatch(c -> c.getX().equals(0.123))); + Assertions + .assertTrue(boundingBox.getCoordinates().stream().anyMatch(c -> c.getX().equals(0.175))); + + Assertions + .assertTrue(boundingBox.getCoordinates().stream().anyMatch(c -> c.getY().equals(0.53))); + Assertions + .assertTrue(boundingBox.getCoordinates().stream().anyMatch(c -> c.getY().equals(0.546))); + } + + @Test + public void fromPolygonMustGetAValidBbox() { + // given + Polygon polygonWichIsNotRectangle = PolygonSample.getPolygonWichIsNotRectangle(); + + // then + Polygon boundingBox = BoundingBoxUtils.createBoundingBoxFrom(polygonWichIsNotRectangle); + + Assertions + .assertTrue(boundingBox.getCoordinates().stream().anyMatch(c -> c.getX().equals(0.205))); + Assertions + .assertTrue(boundingBox.getCoordinates().stream().anyMatch(c -> c.getX().equals(0.381))); + + Assertions + .assertTrue(boundingBox.getCoordinates().stream().anyMatch(c -> c.getY().equals(0.407))); + Assertions + .assertTrue(boundingBox.getCoordinates().stream().anyMatch(c -> c.getY().equals(0.43))); + } } diff --git a/src/test/java/com/mindee/geometry/PolygonSample.java b/src/test/java/com/mindee/geometry/PolygonSample.java index b8c6b3413..cbbcd5b3c 100644 --- a/src/test/java/com/mindee/geometry/PolygonSample.java +++ b/src/test/java/com/mindee/geometry/PolygonSample.java @@ -8,19 +8,23 @@ private PolygonSample() { } public static List getPointsAsRectangle() { - return Arrays.asList( + return Arrays + .asList( new Point(0.123, 0.53), new Point(0.175, 0.53), new Point(0.175, 0.546), - new Point(0.123, 0.546)); + new Point(0.123, 0.546) + ); } public static List getPointsWichIsNotRectangle() { - return Arrays.asList( + return Arrays + .asList( new Point(0.205, 0.407), new Point(0.379, 0.407), new Point(0.381, 0.43), - new Point(0.207, 0.43)); + new Point(0.207, 0.43) + ); } public static Polygon getPolygonAsRectangle() { diff --git a/src/test/java/com/mindee/geometry/PolygonUtilsTest.java b/src/test/java/com/mindee/geometry/PolygonUtilsTest.java index 561321cf3..6829c962b 100644 --- a/src/test/java/com/mindee/geometry/PolygonUtilsTest.java +++ b/src/test/java/com/mindee/geometry/PolygonUtilsTest.java @@ -15,8 +15,7 @@ public void givenAValidPolygonMustGetTheValidCentroid() { // then Point centroid = polygonWichIsNotRectangle.getCentroid(); - Assertions.assertEquals(new Point(0.149, 0.538), - centroid); + Assertions.assertEquals(new Point(0.149, 0.538), centroid); } @Test @@ -66,17 +65,25 @@ public void givenAValidPolygonMustGetTheMinY() { @Test public void combinePolygonsWithTwoNotNullMustGetAValidPolygon() { // given - Polygon polygon1 = new Polygon(Arrays.asList( - new Point(0.081, 0.442), - new Point(0.15, 0.442), - new Point(0.15, 0.451), - new Point(0.081, 0.451))); - - Polygon polygon2 = new Polygon(Arrays.asList( - new Point(0.157, 0.442), - new Point(0.26, 0.442), - new Point(0.26, 0.451), - new Point(0.157, 0.451))); + Polygon polygon1 = new Polygon( + Arrays + .asList( + new Point(0.081, 0.442), + new Point(0.15, 0.442), + new Point(0.15, 0.451), + new Point(0.081, 0.451) + ) + ); + + Polygon polygon2 = new Polygon( + Arrays + .asList( + new Point(0.157, 0.442), + new Point(0.26, 0.442), + new Point(0.26, 0.451), + new Point(0.157, 0.451) + ) + ); // then Polygon mergedPolygon = PolygonUtils.combine(polygon1, polygon2); @@ -98,11 +105,15 @@ public void combineWithNullPolygonMustThrow() { @Test public void combineWith1PolygonAndANullPolygonMustGetNull() { // given - Polygon polygon1 = new Polygon(Arrays.asList( - new Point(0.081, 0.442), - new Point(0.15, 0.442), - new Point(0.15, 0.451), - new Point(0.081, 0.451))); + Polygon polygon1 = new Polygon( + Arrays + .asList( + new Point(0.081, 0.442), + new Point(0.15, 0.442), + new Point(0.15, 0.451), + new Point(0.081, 0.451) + ) + ); Polygon polygon2 = null; diff --git a/src/test/java/com/mindee/http/MindeeHttpApiTest.java b/src/test/java/com/mindee/http/MindeeHttpApiTest.java index c18b5be42..e933d50e2 100644 --- a/src/test/java/com/mindee/http/MindeeHttpApiTest.java +++ b/src/test/java/com/mindee/http/MindeeHttpApiTest.java @@ -59,17 +59,19 @@ public void stopWebServer() throws Exception { private MindeeHttpApi getClientForResponse(Path filePath, int statusCode) throws IOException { String url = String.format("http://localhost:%s", mockWebServer.getPort()); - mockWebServer.enqueue(new MockResponse() - .setResponseCode(statusCode) - .setBody(new String(Files.readAllBytes(filePath))) - ); - HttpClientBuilder httpClientBuilder = HttpClients.custom() - .disableAutomaticRetries(); - - return MindeeHttpApi.builder() - .mindeeSettings(new MindeeSettings("abc", url)) - .httpClientBuilder(httpClientBuilder) - .build(); + mockWebServer + .enqueue( + new MockResponse() + .setResponseCode(statusCode) + .setBody(new String(Files.readAllBytes(filePath))) + ); + HttpClientBuilder httpClientBuilder = HttpClients.custom().disableAutomaticRetries(); + + return MindeeHttpApi + .builder() + .mindeeSettings(new MindeeSettings("abc", url)) + .httpClientBuilder(httpClientBuilder) + .build(); } private MindeeHttpApi getClientForResponse(String filePath, int statusCode) throws IOException { @@ -77,29 +79,29 @@ private MindeeHttpApi getClientForResponse(String filePath, int statusCode) thro } @Test - void givenAResponseFromTheEndpoint_whenDeserialized_mustHaveValidSummary() - throws IOException { + void givenAResponseFromTheEndpoint_whenDeserialized_mustHaveValidSummary() throws IOException { MindeeHttpApi client = getClientForResponse("products/invoices/response_v4/complete.json", 200); Path filePath = getV1ResourcePath("products/invoices/invoice.pdf"); - Document document = client.predictPost( - InvoiceV4.class, - new Endpoint("", ""), - RequestParameters.builder() - .file(Files.readAllBytes(filePath)) - .fileName(filePath.getFileName().toString()) - .build() - ) - .getDocument(); + Document document = client + .predictPost( + InvoiceV4.class, + new Endpoint("", ""), + RequestParameters + .builder() + .file(Files.readAllBytes(filePath)) + .fileName(filePath.getFileName().toString()) + .build() + ) + .getDocument(); Assertions.assertNotNull(document); String[] actualLines = document.toString().split(System.lineSeparator()); String actualSummary = String.join(String.format("%n"), actualLines); - List expectedLines = Files.readAllLines( - getV1ResourcePath("products/invoices/response_v4/summary_full.rst") - ); + List expectedLines = Files + .readAllLines(getV1ResourcePath("products/invoices/response_v4/summary_full.rst")); String expectedSummary = String.join(String.format("%n"), expectedLines); Assertions.assertNotNull(document); @@ -107,61 +109,58 @@ void givenAResponseFromTheEndpoint_whenDeserialized_mustHaveValidSummary() } @Test - void givenParseParametersWithFile_whenParsed_shouldBuildRequestCorrectly() - throws IOException, InterruptedException { - MindeeHttpApi client = getClientForResponse( - "products/invoices/response_v4/complete.json", 200 - ); + void givenParseParametersWithFile_whenParsed_shouldBuildRequestCorrectly() throws IOException, InterruptedException { + MindeeHttpApi client = getClientForResponse("products/invoices/response_v4/complete.json", 200); Path filePath = getV1ResourcePath("products/invoices/invoice.pdf"); byte[] fileBytes = Files.readAllBytes(filePath); - Document document = client.predictPost( - InvoiceV4.class, - new Endpoint("", ""), - RequestParameters.builder() - .file(fileBytes) - .fileName(filePath.getFileName().toString()) - .build() - ) - .getDocument(); + Document document = client + .predictPost( + InvoiceV4.class, + new Endpoint("", ""), + RequestParameters + .builder() + .file(fileBytes) + .fileName(filePath.getFileName().toString()) + .build() + ) + .getDocument(); RecordedRequest recordedRequest = mockWebServer.takeRequest(); Assertions.assertEquals("abc", recordedRequest.getHeader("Authorization")); - Assertions.assertEquals( + Assertions + .assertEquals( Long.toString(recordedRequest.getBodySize()), recordedRequest.getHeader("Content-Length") - ); + ); Assertions.assertTrue(recordedRequest.getBodySize() > fileBytes.length); } @Test - void givenPredictOptions_whenParsed_shouldBuildRequestCorrectly() - throws IOException, InterruptedException { - MindeeHttpApi client = getClientForResponse( - "products/invoices/response_v4/complete.json", 200 - ); + void givenPredictOptions_whenParsed_shouldBuildRequestCorrectly() throws IOException, InterruptedException { + MindeeHttpApi client = getClientForResponse("products/invoices/response_v4/complete.json", 200); Path filePath = getV1ResourcePath("products/invoices/invoice.pdf"); byte[] fileBytes = Files.readAllBytes(filePath); - PredictOptions predictOptions = PredictOptions.builder() - .cropper(true) - .allWords(true) - .build(); - Document document = client.predictPost( - InvoiceV4.class, - new Endpoint("", ""), - RequestParameters.builder() - .file(fileBytes) - .fileName(filePath.getFileName().toString()) - .predictOptions(predictOptions) - .build() - ) - .getDocument(); + PredictOptions predictOptions = PredictOptions.builder().cropper(true).allWords(true).build(); + Document document = client + .predictPost( + InvoiceV4.class, + new Endpoint("", ""), + RequestParameters + .builder() + .file(fileBytes) + .fileName(filePath.getFileName().toString()) + .predictOptions(predictOptions) + .build() + ) + .getDocument(); RecordedRequest recordedRequest = mockWebServer.takeRequest(); Assertions.assertEquals("abc", recordedRequest.getHeader("Authorization")); - Assertions.assertEquals( + Assertions + .assertEquals( Long.toString(recordedRequest.getBodySize()), recordedRequest.getHeader("Content-Length") - ); + ); assert recordedRequest.getRequestUrl() != null; Assertions.assertTrue(recordedRequest.getRequestUrl().toString().contains("cropper=true")); Assertions.assertTrue(recordedRequest.getBody().readUtf8().contains("include_mvision")); @@ -169,77 +168,82 @@ void givenPredictOptions_whenParsed_shouldBuildRequestCorrectly() } @Test - void givenParseParametersWithFileUrl_whenParsed_shouldBuildRequestCorrectly() - throws IOException, InterruptedException { + void givenParseParametersWithFileUrl_whenParsed_shouldBuildRequestCorrectly() throws IOException, InterruptedException { MindeeHttpApi client = getClientForResponse("products/invoices/response_v4/complete.json", 200); - Document document = client.predictPost( - InvoiceV4.class, - new Endpoint("", ""), - RequestParameters.builder() - .file(null) - .fileName(null) - .urlInputSource(new URL("https://thisfile.does.not.exist")) - .build() - ) - .getDocument(); + Document document = client + .predictPost( + InvoiceV4.class, + new Endpoint("", ""), + RequestParameters + .builder() + .file(null) + .fileName(null) + .urlInputSource(new URL("https://thisfile.does.not.exist")) + .build() + ) + .getDocument(); RecordedRequest recordedRequest = mockWebServer.takeRequest(); Assertions.assertEquals("abc", recordedRequest.getHeader("Authorization")); - Assertions.assertEquals( + Assertions + .assertEquals( Long.toString(recordedRequest.getBodySize()), recordedRequest.getHeader("Content-Length") - ); - Assertions.assertTrue( - Objects.requireNonNull(recordedRequest.getHeader("Content-Type")).contains("application/json") - ); - Map requestMap = objectMapper.readValue( - recordedRequest.getBody().readUtf8(), - new TypeReference>() {} - ); + ); + Assertions + .assertTrue( + Objects + .requireNonNull(recordedRequest.getHeader("Content-Type")) + .contains("application/json") + ); + Map requestMap = objectMapper + .readValue(recordedRequest.getBody().readUtf8(), new TypeReference>() { + }); assertThat(requestMap, IsMapContaining.hasEntry("document", "https://thisfile.does.not.exist")); } @Test - void givenAnUrlBuilderFunction_whenParsed_callsTheCorrectUrl() - throws IOException, InterruptedException { + void givenAnUrlBuilderFunction_whenParsed_callsTheCorrectUrl() throws IOException, InterruptedException { String url = String.format("http://localhost:%s", mockWebServer.getPort()); String mockPath = "/testinvoice/v2/test"; Path path = getV1ResourcePath("products/invoices/response_v4/complete.json"); - mockWebServer.enqueue(new MockResponse() - .setResponseCode(200) - .setBody(new String(Files.readAllBytes(path))) - ); - - HttpClientBuilder httpClientBuilder = HttpClients.custom() - .disableAutomaticRetries(); - - MindeeHttpApi client = MindeeHttpApi.builder() - .mindeeSettings(new MindeeSettings("abc", url)) - .httpClientBuilder(httpClientBuilder) - .urlFromEndpoint( - endpoint -> String.format("http://localhost:%s%s", mockWebServer.getPort(), mockPath)) - .build(); + mockWebServer + .enqueue( + new MockResponse().setResponseCode(200).setBody(new String(Files.readAllBytes(path))) + ); + + HttpClientBuilder httpClientBuilder = HttpClients.custom().disableAutomaticRetries(); + + MindeeHttpApi client = MindeeHttpApi + .builder() + .mindeeSettings(new MindeeSettings("abc", url)) + .httpClientBuilder(httpClientBuilder) + .urlFromEndpoint( + endpoint -> String.format("http://localhost:%s%s", mockWebServer.getPort(), mockPath) + ) + .build(); File file = new File(getV1ResourcePathString("products/invoices/invoice.pdf")); - Document document = client.predictPost( - InvoiceV4.class, - new Endpoint("", ""), - RequestParameters.builder() - .file(Files.readAllBytes(file.toPath())) - .fileName(file.getName()) - .build() - ) - .getDocument(); + Document document = client + .predictPost( + InvoiceV4.class, + new Endpoint("", ""), + RequestParameters + .builder() + .file(Files.readAllBytes(file.toPath())) + .fileName(file.getName()) + .build() + ) + .getDocument(); Assertions.assertNotNull(document); String[] actualLines = document.toString().split(System.lineSeparator()); String actualSummary = String.join(String.format("%n"), actualLines); - List expectedLines = Files.readAllLines( - getV1ResourcePath("products/invoices/response_v4/summary_full.rst") - ); + List expectedLines = Files + .readAllLines(getV1ResourcePath("products/invoices/response_v4/summary_full.rst")); String expectedSummary = String.join(String.format("%n"), expectedLines); Assertions.assertNotNull(document); @@ -248,81 +252,81 @@ void givenAnUrlBuilderFunction_whenParsed_callsTheCorrectUrl() } @Test - void givenAHttpClientBuilder_whenParseCalled_usesClientBuilderToMakeHttpClient() - throws IOException { + void givenAHttpClientBuilder_whenParseCalled_usesClientBuilderToMakeHttpClient() throws IOException { WireMockRule proxyMock = new WireMockRule(); proxyMock.start(); int proxyPort = proxyMock.port(); String url = String.format("http://localhost:%s", mockWebServer.getPort()); - proxyMock.stubFor(post(urlMatching(".*")) - .willReturn(aResponse().proxiedFrom(url))); + proxyMock.stubFor(post(urlMatching(".*")).willReturn(aResponse().proxiedFrom(url))); Path path = getV1ResourcePath("products/invoices/response_v4/complete.json"); - mockWebServer.enqueue(new MockResponse() - .setResponseCode(200) - .setBody(new String(Files.readAllBytes(path)))); + mockWebServer + .enqueue( + new MockResponse().setResponseCode(200).setBody(new String(Files.readAllBytes(path))) + ); File file = new File(getV1ResourcePathString("products/invoices/invoice.pdf")); HttpHost proxy = new HttpHost("localhost", proxyPort); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); - HttpClientBuilder httpClientBuilder = HttpClients.custom() - .setRoutePlanner(routePlanner) - .disableAutomaticRetries(); - - MindeeHttpApi client = MindeeHttpApi.builder() - .mindeeSettings(new MindeeSettings("abc", url)) - .httpClientBuilder(httpClientBuilder) - .build(); - - PredictResponse response = client.predictPost( + HttpClientBuilder httpClientBuilder = HttpClients + .custom() + .setRoutePlanner(routePlanner) + .disableAutomaticRetries(); + + MindeeHttpApi client = MindeeHttpApi + .builder() + .mindeeSettings(new MindeeSettings("abc", url)) + .httpClientBuilder(httpClientBuilder) + .build(); + + PredictResponse response = client + .predictPost( InvoiceV4.class, new Endpoint(InvoiceV4.class), - RequestParameters.builder() - .file(Files.readAllBytes(file.toPath())) - .fileName(file.getName()) - .build() - ); + RequestParameters + .builder() + .file(Files.readAllBytes(file.toPath())) + .fileName(file.getName()) + .build() + ); Assertions.assertNotNull(response); - Assertions.assertEquals( - new String(Files.readAllBytes(path)), - response.getRawResponse() - ); + Assertions.assertEquals(new String(Files.readAllBytes(path)), response.getRawResponse()); String[] actualLines = response.getDocument().toString().split(System.lineSeparator()); String actualSummary = String.join(String.format("%n"), actualLines); - List expectedLines = Files.readAllLines( - getV1ResourcePath("products/invoices/response_v4/summary_full.rst") - ); + List expectedLines = Files + .readAllLines(getV1ResourcePath("products/invoices/response_v4/summary_full.rst")); String expectedSummary = String.join(String.format("%n"), expectedLines); - proxyMock.verify(postRequestedFor(urlEqualTo("/products/mindee/invoices/v4/predict")) - .withHeader("Authorization", containing("abc"))); + proxyMock + .verify( + postRequestedFor(urlEqualTo("/products/mindee/invoices/v4/predict")) + .withHeader("Authorization", containing("abc")) + ); Assertions.assertNotNull(response.getDocument()); Assertions.assertEquals(expectedSummary, actualSummary); proxyMock.shutdown(); } @Test - void givenAnAsncResponse_whenDeserialized_mustHaveValidJob() - throws IOException, InterruptedException { + void givenAnAsncResponse_whenDeserialized_mustHaveValidJob() throws IOException, InterruptedException { Path path = getV1ResourcePath("async/post_success.json"); MindeeHttpApi client = getClientForResponse(path, 200); File file = new File(getV1ResourcePathString("products/invoices/invoice.pdf")); - AsyncPredictResponse response = client.predictAsyncPost( + AsyncPredictResponse response = client + .predictAsyncPost( InvoiceV4.class, new Endpoint(InvoiceV4.class), - RequestParameters.builder() - .file(Files.readAllBytes(file.toPath())) - .fileName(file.getName()) - .build() - ); + RequestParameters + .builder() + .file(Files.readAllBytes(file.toPath())) + .fileName(file.getName()) + .build() + ); Assertions.assertNotNull(response); - Assertions.assertEquals( - new String(Files.readAllBytes(path)), - response.getRawResponse() - ); + Assertions.assertEquals(new String(Files.readAllBytes(path)), response.getRawResponse()); Assertions.assertEquals("waiting", response.getJob().getStatus()); Assertions.assertFalse(response.getDocument().isPresent()); @@ -331,29 +335,24 @@ void givenAnAsncResponse_whenDeserialized_mustHaveValidJob() Assertions.assertEquals("abc", recordedRequest.getHeader("Authorization")); Assertions.assertEquals("POST", recordedRequest.getMethod()); - Assertions.assertEquals( - "/products/mindee/invoices/v4/predict_async", - recordedRequest.getPath() - ); + Assertions + .assertEquals("/products/mindee/invoices/v4/predict_async", recordedRequest.getPath()); } @Test - void givenAResponseFromTheJobEndpoint_whenDeserialized_mustHaveValidJobAndDocument() - throws IOException, InterruptedException { + void givenAResponseFromTheJobEndpoint_whenDeserialized_mustHaveValidJobAndDocument() throws IOException, InterruptedException { Path path = getV1ResourcePath("async/get_completed.json"); MindeeHttpApi client = getClientForResponse(path, 200); - AsyncPredictResponse response = client.documentQueueGet( + AsyncPredictResponse response = client + .documentQueueGet( InvoiceSplitterV1.class, new Endpoint(InvoiceSplitterV1.class), "2134e243244" - ); + ); Assertions.assertNotNull(response); - Assertions.assertEquals( - new String(Files.readAllBytes(path)), - response.getRawResponse() - ); + Assertions.assertEquals(new String(Files.readAllBytes(path)), response.getRawResponse()); Assertions.assertEquals("completed", response.getJob().getStatus()); Assertions.assertTrue(response.getDocument().isPresent()); @@ -362,60 +361,52 @@ void givenAResponseFromTheJobEndpoint_whenDeserialized_mustHaveValidJobAndDocume Assertions.assertEquals("abc", recordedRequest.getHeader("Authorization")); Assertions.assertEquals("GET", recordedRequest.getMethod()); - Assertions.assertEquals( + Assertions + .assertEquals( "/products/mindee/invoice_splitter/v1/documents/queue/2134e243244", recordedRequest.getPath() - ); + ); } @Test - void givenError401_noToken_mustThrowMindeeHttpException() - throws IOException { + void givenError401_noToken_mustThrowMindeeHttpException() throws IOException { MindeeHttpApi client = getClientForResponse("errors/error_401_no_token.json", 401); File file = new File(getV1ResourcePathString("products/invoices/invoice.pdf")); byte[] fileInBytes = Files.readAllBytes(file.toPath()); - RequestParameters parseParameter = - RequestParameters.builder() - .file(fileInBytes) - .fileName(file.getName()) - .build(); - - MindeeHttpException httpError = Assertions.assertThrows( + RequestParameters parseParameter = RequestParameters + .builder() + .file(fileInBytes) + .fileName(file.getName()) + .build(); + + MindeeHttpException httpError = Assertions + .assertThrows( MindeeHttpException.class, - () -> client.predictPost( - InvoiceV4.class, - new Endpoint(InvoiceV4.class), - parseParameter - ) - ); + () -> client.predictPost(InvoiceV4.class, new Endpoint(InvoiceV4.class), parseParameter) + ); Assertions.assertEquals(401, httpError.getStatusCode()); Assertions.assertEquals("Authorization required", httpError.getMessage()); Assertions.assertEquals("No token provided", httpError.getDetails()); } - @Test - void givenError429_mustThrowMindeeHttpException() - throws IOException - { + void givenError429_mustThrowMindeeHttpException() throws IOException { MindeeHttpApi client = getClientForResponse("errors/error_429_too_many_requests.json", 429); File file = new File(getV1ResourcePathString("products/invoices/invoice.pdf")); byte[] fileInBytes = Files.readAllBytes(file.toPath()); - RequestParameters parseParameter = - RequestParameters.builder() - .file(fileInBytes) - .fileName(file.getName()) - .build(); - - MindeeHttpException httpError = Assertions.assertThrows( + RequestParameters parseParameter = RequestParameters + .builder() + .file(fileInBytes) + .fileName(file.getName()) + .build(); + + MindeeHttpException httpError = Assertions + .assertThrows( MindeeHttpException.class, - () -> client.predictPost( - InvoiceV4.class, - new Endpoint(InvoiceV4.class), - parseParameter) - ); + () -> client.predictPost(InvoiceV4.class, new Endpoint(InvoiceV4.class), parseParameter) + ); Assertions.assertEquals(429, httpError.getStatusCode()); Assertions.assertEquals("Too many requests", httpError.getMessage()); Assertions.assertEquals("Too Many Requests.", httpError.getDetails()); @@ -423,54 +414,49 @@ void givenError429_mustThrowMindeeHttpException() } @Test - void givenError_inHtml_mustThrowMindeeHttpException() - throws IOException { + void givenError_inHtml_mustThrowMindeeHttpException() throws IOException { MindeeHttpApi client = getClientForResponse("errors/error_50x.html", 413); Path filePath = getV1ResourcePath("products/invoices/invoice.pdf"); byte[] fileBytes = Files.readAllBytes(filePath); - RequestParameters parseParameter = - RequestParameters.builder() - .file(fileBytes) - .fileName(filePath.getFileName().toString()) - .build(); - - MindeeHttpException httpError = Assertions.assertThrows( + RequestParameters parseParameter = RequestParameters + .builder() + .file(fileBytes) + .fileName(filePath.getFileName().toString()) + .build(); + + MindeeHttpException httpError = Assertions + .assertThrows( MindeeHttpException.class, - () -> client.predictPost( - InvoiceV4.class, - new Endpoint(InvoiceV4.class), - parseParameter - ) - ); + () -> client.predictPost(InvoiceV4.class, new Endpoint(InvoiceV4.class), parseParameter) + ); Assertions.assertEquals(413, httpError.getStatusCode()); - Assertions.assertEquals( - "HTTP Status 413 - Unhandled server response, check details.", httpError.getMessage()); + Assertions + .assertEquals( + "HTTP Status 413 - Unhandled server response, check details.", + httpError.getMessage() + ); Assertions.assertTrue(httpError.getDetails().contains("

An error occurred.

")); Assertions.assertEquals("", httpError.getCode()); } @Test - void givenError400_noDetails_mustThrowMindeeHttpException() - throws IOException { + void givenError400_noDetails_mustThrowMindeeHttpException() throws IOException { MindeeHttpApi client = getClientForResponse("errors/error_400_no_details.json", 400); Path filePath = getV1ResourcePath("products/invoices/invoice.pdf"); byte[] fileBytes = Files.readAllBytes(filePath); - RequestParameters parseParameter = - RequestParameters.builder() - .file(fileBytes) - .fileName(filePath.getFileName().toString()) - .build(); - - MindeeHttpException httpError = Assertions.assertThrows( + RequestParameters parseParameter = RequestParameters + .builder() + .file(fileBytes) + .fileName(filePath.getFileName().toString()) + .build(); + + MindeeHttpException httpError = Assertions + .assertThrows( MindeeHttpException.class, - () -> client.predictPost( - InvoiceV4.class, - new Endpoint(InvoiceV4.class), - parseParameter - ) - ); + () -> client.predictPost(InvoiceV4.class, new Endpoint(InvoiceV4.class), parseParameter) + ); Assertions.assertEquals(400, httpError.getStatusCode()); Assertions.assertEquals("Some scary message here", httpError.getMessage()); Assertions.assertEquals("", httpError.getDetails()); diff --git a/src/test/java/com/mindee/input/FileCompressionTest.java b/src/test/java/com/mindee/input/FileCompressionTest.java index 5d32563ef..a8e6d3a35 100644 --- a/src/test/java/com/mindee/input/FileCompressionTest.java +++ b/src/test/java/com/mindee/input/FileCompressionTest.java @@ -36,11 +36,15 @@ public void fromInputSource_imageQuality_should_Compress() throws IOException { long initialFileSize = Files.size(testFilePath); long compressedFileSize = Files.size(outputPath); - Assertions.assertTrue( + Assertions + .assertTrue( compressedFileSize < initialFileSize, - "Compressed file size (" + compressedFileSize + - ") should be less than initial file size (" + initialFileSize + ")" - ); + "Compressed file size (" + + compressedFileSize + + ") should be less than initial file size (" + + initialFileSize + + ")" + ); } @Test @@ -50,60 +54,81 @@ public void testImageQualityCompressesFromCompressor() throws IOException { LocalInputSource receiptInput = new LocalInputSource(testFilePath); - List compresses = Arrays.asList( + List compresses = Arrays + .asList( ImageCompressor.compressImage(receiptInput.getFile(), 100), ImageCompressor.compressImage(receiptInput.getFile()), ImageCompressor.compressImage(receiptInput.getFile(), 50), ImageCompressor.compressImage(receiptInput.getFile(), 10), ImageCompressor.compressImage(receiptInput.getFile(), 1) - ); - List outputPaths = Arrays.asList( + ); + List outputPaths = Arrays + .asList( outputDir.resolve("compress100.jpg"), outputDir.resolve("compress75.jpg"), outputDir.resolve("compress50.jpg"), outputDir.resolve("compress10.jpg"), outputDir.resolve("compress1.jpg") - ); + ); for (int i = 0; i < compresses.size(); i++) { Files.write(outputPaths.get(i), compresses.get(i)); } long initialFileSize = Files.size(testFilePath); - List compressedFileSizes = outputPaths.stream() - .map(path -> { - try { - return Files.size(path); - } catch (IOException e) { - throw new RuntimeException(e); - } - }).collect(Collectors.toList()); - - Assertions.assertTrue( + List compressedFileSizes = outputPaths.stream().map(path -> { + try { + return Files.size(path); + } catch (IOException e) { + throw new RuntimeException(e); + } + }).collect(Collectors.toList()); + + Assertions + .assertTrue( initialFileSize < compressedFileSizes.get(0), - "Compressed file size (" + compressedFileSizes.get(0) + - ") should be less than initial file size (" + initialFileSize + ")" - ); - Assertions.assertTrue( + "Compressed file size (" + + compressedFileSizes.get(0) + + ") should be less than initial file size (" + + initialFileSize + + ")" + ); + Assertions + .assertTrue( initialFileSize < compressedFileSizes.get(1), - "Compressed file size (" + compressedFileSizes.get(1) + - ") should be less than initial file size (" + initialFileSize + ")" - ); - Assertions.assertTrue( + "Compressed file size (" + + compressedFileSizes.get(1) + + ") should be less than initial file size (" + + initialFileSize + + ")" + ); + Assertions + .assertTrue( compressedFileSizes.get(1) > compressedFileSizes.get(2), - "Compressed file size (" + compressedFileSizes.get(2) + - ") should be less than initial file size (" + compressedFileSizes.get(1) + ")" - ); - Assertions.assertTrue( + "Compressed file size (" + + compressedFileSizes.get(2) + + ") should be less than initial file size (" + + compressedFileSizes.get(1) + + ")" + ); + Assertions + .assertTrue( compressedFileSizes.get(2) > compressedFileSizes.get(3), - "Compressed file size (" + compressedFileSizes.get(3) + - ") should be less than initial file size (" + compressedFileSizes.get(2) + ")" - ); - Assertions.assertTrue( + "Compressed file size (" + + compressedFileSizes.get(3) + + ") should be less than initial file size (" + + compressedFileSizes.get(2) + + ")" + ); + Assertions + .assertTrue( compressedFileSizes.get(3) > compressedFileSizes.get(4), - "Compressed file size (" + compressedFileSizes.get(4) + - ") should be less than initial file size (" + compressedFileSizes.get(3) + ")" - ); + "Compressed file size (" + + compressedFileSizes.get(4) + + ") should be less than initial file size (" + + compressedFileSizes.get(3) + + ")" + ); } @Test @@ -129,53 +154,72 @@ public void testImageResizeFromCompressor() throws IOException { Path testFilePath = getResourcePath("file_types/receipt.jpg"); Path outputDir = getResourcePath("output"); LocalInputSource imageResizeInput = new LocalInputSource(testFilePath); - List resizes = Arrays.asList( + List resizes = Arrays + .asList( ImageCompressor.compressImage(imageResizeInput.getFile(), 75, 500, null), ImageCompressor.compressImage(imageResizeInput.getFile(), 75, 250, 500), ImageCompressor.compressImage(imageResizeInput.getFile(), 75, 500, 250), ImageCompressor.compressImage(imageResizeInput.getFile(), 75, null, 250) - ); + ); - List outputPaths = Arrays.asList( + List outputPaths = Arrays + .asList( outputDir.resolve("resize500xnull.jpg"), outputDir.resolve("resize250x500.jpg"), outputDir.resolve("resize500x250.jpg"), outputDir.resolve("resizenullx250.jpg") - ); + ); for (int i = 0; i < resizes.size(); i++) { Files.write(outputPaths.get(i), resizes.get(i)); } long initialFileSize = Files.size(testFilePath); - List resizedFileSizes = outputPaths.stream() - .map(path -> { - try { - return Files.size(path); - } catch (IOException e) { - throw new RuntimeException(e); - } - }).collect(Collectors.toList()); - - Assertions.assertTrue( + List resizedFileSizes = outputPaths.stream().map(path -> { + try { + return Files.size(path); + } catch (IOException e) { + throw new RuntimeException(e); + } + }).collect(Collectors.toList()); + + Assertions + .assertTrue( initialFileSize > resizedFileSizes.get(0), - "Resized file size (" + resizedFileSizes.get(0) + - ") should be less than initial file size (" + initialFileSize + ")" - ); - Assertions.assertTrue( + "Resized file size (" + + resizedFileSizes.get(0) + + ") should be less than initial file size (" + + initialFileSize + + ")" + ); + Assertions + .assertTrue( resizedFileSizes.get(0) > resizedFileSizes.get(1), - "Resized file size (" + resizedFileSizes.get(1) + - ") should be less than initial file size (" + initialFileSize + ")" - ); - Assertions.assertTrue( + "Resized file size (" + + resizedFileSizes.get(1) + + ") should be less than initial file size (" + + initialFileSize + + ")" + ); + Assertions + .assertTrue( resizedFileSizes.get(1) > resizedFileSizes.get(2), - "Resized file size (" + resizedFileSizes.get(2) + - ") should be less than initial file size (" + resizedFileSizes.get(1) + ")" - ); - Assertions.assertEquals(resizedFileSizes.get(2), resizedFileSizes.get(3), - "Resized file size (" + resizedFileSizes.get(3) + - ") should be less than initial file size (" + resizedFileSizes.get(2) + ")" - ); + "Resized file size (" + + resizedFileSizes.get(2) + + ") should be less than initial file size (" + + resizedFileSizes.get(1) + + ")" + ); + Assertions + .assertEquals( + resizedFileSizes.get(2), + resizedFileSizes.get(3), + "Resized file size (" + + resizedFileSizes.get(3) + + ") should be less than initial file size (" + + resizedFileSizes.get(2) + + ")" + ); } @Test @@ -191,11 +235,15 @@ public void testPdfResizeFromInputSource() throws IOException { long initialFileSize = Files.size(inputPath); long renderedFileSize = Files.size(outputPath); - Assertions.assertTrue( + Assertions + .assertTrue( renderedFileSize < initialFileSize, - "Resized file size (" + renderedFileSize + - ") should be less than initial file size (" + initialFileSize + ")" - ); + "Resized file size (" + + renderedFileSize + + ") should be less than initial file size (" + + initialFileSize + + ")" + ); } @Test @@ -204,63 +252,79 @@ public void testPdfResizeFromCompressor() throws IOException { Path inputPath = getV1ResourcePath("products/invoice_splitter/default_sample.pdf"); LocalInputSource pdfResizeInput = new LocalInputSource(inputPath.toString()); - List resizes = Arrays.asList( + List resizes = Arrays + .asList( PdfCompressor.compressPdf(pdfResizeInput.getFile()), PdfCompressor.compressPdf(pdfResizeInput.getFile(), 75), PdfCompressor.compressPdf(pdfResizeInput.getFile(), 50), PdfCompressor.compressPdf(pdfResizeInput.getFile(), 10) - ); + ); - List outputPaths = Arrays.asList( + List outputPaths = Arrays + .asList( outputDir.resolve("compress85.pdf"), outputDir.resolve("compress75.pdf"), outputDir.resolve("compress50.pdf"), outputDir.resolve("compress10.pdf") - ); + ); for (int i = 0; i < resizes.size(); i++) { Files.write(outputPaths.get(i), resizes.get(i)); } long initialFileSize = Files.size(inputPath); - List renderedFileSizes = outputPaths.stream() - .map(path -> { - try { - return Files.size(path); - } catch (IOException e) { - throw new RuntimeException(e); - } - }) - .collect(Collectors.toList()); - - Assertions.assertTrue( + List renderedFileSizes = outputPaths.stream().map(path -> { + try { + return Files.size(path); + } catch (IOException e) { + throw new RuntimeException(e); + } + }).collect(Collectors.toList()); + + Assertions + .assertTrue( initialFileSize > renderedFileSizes.get(0), - "Compressed file size (" + renderedFileSizes.get(0) + - ") should be less than initial file size (" + initialFileSize + ")" - ); - Assertions.assertTrue( + "Compressed file size (" + + renderedFileSizes.get(0) + + ") should be less than initial file size (" + + initialFileSize + + ")" + ); + Assertions + .assertTrue( renderedFileSizes.get(0) > renderedFileSizes.get(1), - "Compressed file size (" + renderedFileSizes.get(1) + - ") should be less than initial file size (" + renderedFileSizes.get(0) + ")" - ); - Assertions.assertTrue( + "Compressed file size (" + + renderedFileSizes.get(1) + + ") should be less than initial file size (" + + renderedFileSizes.get(0) + + ")" + ); + Assertions + .assertTrue( renderedFileSizes.get(1) > renderedFileSizes.get(2), - "Compressed file size (" + renderedFileSizes.get(2) + - ") should be less than initial file size (" + renderedFileSizes.get(1) + ")" - ); - Assertions.assertTrue( + "Compressed file size (" + + renderedFileSizes.get(2) + + ") should be less than initial file size (" + + renderedFileSizes.get(1) + + ")" + ); + Assertions + .assertTrue( renderedFileSizes.get(2) > renderedFileSizes.get(3), - "Compressed file size (" + renderedFileSizes.get(3) + - ") should be less than initial file size (" + renderedFileSizes.get(2) + ")" - ); + "Compressed file size (" + + renderedFileSizes.get(3) + + ") should be less than initial file size (" + + renderedFileSizes.get(2) + + ")" + ); } @Test public void testPdfResizeWithTextKeepsText() throws IOException { Path inputPath = getResourcePath("file_types/pdf/multipage.pdf"); LocalInputSource initialWithText = new LocalInputSource(inputPath.toString()); - byte[] compressedWithText = - PdfCompressor.compressPdf(initialWithText.getFile(), 100, true, false); + byte[] compressedWithText = PdfCompressor + .compressPdf(initialWithText.getFile(), 100, true, false); PDDocument originalDoc = Loader.loadPDF(initialWithText.getFile()); PDDocument compressedDoc = Loader.loadPDF(compressedWithText); @@ -277,10 +341,8 @@ public void testPdfResizeWithTextKeepsText() throws IOException { String compressedText = textStripper.getText(compressedDoc).trim().replaceAll(" ", ""); Assertions.assertEquals(originalText, compressedText); - Assertions.assertNotEquals( - originalDoc.getPage(i).hashCode(), - compressedDoc.getPage(i).hashCode() - ); + Assertions + .assertNotEquals(originalDoc.getPage(i).hashCode(), compressedDoc.getPage(i).hashCode()); } originalDoc.close(); diff --git a/src/test/java/com/mindee/input/LocalInputSourceTest.java b/src/test/java/com/mindee/input/LocalInputSourceTest.java index 4d1d4e15c..6e7815c57 100644 --- a/src/test/java/com/mindee/input/LocalInputSourceTest.java +++ b/src/test/java/com/mindee/input/LocalInputSourceTest.java @@ -39,8 +39,8 @@ void loadPDF_withFile_mustReturnAValidLocalInputSource() throws IOException { void loadPDF_withInputStream_mustReturnAValidLocalInputSource() throws IOException { Path filePath = getResourcePath("file_types/pdf/multipage_cut-3.pdf"); LocalInputSource localInputSource = new LocalInputSource( - Files.newInputStream(filePath), - "multipage_cut-3.pdf" + Files.newInputStream(filePath), + "multipage_cut-3.pdf" ); assertMultipagePDF(localInputSource, filePath); } @@ -49,8 +49,8 @@ void loadPDF_withInputStream_mustReturnAValidLocalInputSource() throws IOExcepti void loadPDF_withByteArray_mustReturnAValidLocalInputSource() throws IOException { Path filePath = getResourcePath("file_types/pdf/multipage_cut-3.pdf"); LocalInputSource localInputSource = new LocalInputSource( - Files.readAllBytes(filePath), - "multipage_cut-3.pdf" + Files.readAllBytes(filePath), + "multipage_cut-3.pdf" ); assertMultipagePDF(localInputSource, filePath); } @@ -59,10 +59,7 @@ void loadPDF_withByteArray_mustReturnAValidLocalInputSource() throws IOException void loadPDF_withBase64Encoded_mustReturnAValidLocalInputSource() throws IOException { Path filePath = getResourcePath("file_types/pdf/multipage_cut-3.pdf"); String encodedFile = Base64.encodeBase64String(Files.readAllBytes(filePath)); - LocalInputSource localInputSource = new LocalInputSource( - encodedFile, - "multipage_cut-3.pdf" - ); + LocalInputSource localInputSource = new LocalInputSource(encodedFile, "multipage_cut-3.pdf"); assertMultipagePDF(localInputSource, filePath); } @@ -70,10 +67,7 @@ void loadPDF_withBase64Encoded_mustReturnAValidLocalInputSource() throws IOExcep void loadPDF__withoutText_mustNotDetectSourceText() throws MindeeException, IOException { Path filePath = getV1ResourcePath("products/invoice_splitter/default_sample.pdf"); String encodedFile = Base64.encodeBase64String(Files.readAllBytes(filePath)); - LocalInputSource localInputSource = new LocalInputSource( - encodedFile, - "default_sample.pdf" - ); + LocalInputSource localInputSource = new LocalInputSource(encodedFile, "default_sample.pdf"); Assertions.assertNotNull(localInputSource); Assertions.assertTrue(localInputSource.isPdf()); Assertions.assertFalse(localInputSource.hasSourceText()); @@ -105,8 +99,8 @@ void loadImage_withFile_mustReturnAValidLocalInputSource() throws IOException { void loadImage_withInputStream_mustReturnAValidLocalInputSource() throws IOException { Path filePath = getResourcePath("file_types/receipt.jpg"); LocalInputSource localInputSource = new LocalInputSource( - Files.newInputStream(filePath), - "receipt.jpg" + Files.newInputStream(filePath), + "receipt.jpg" ); assertImage(localInputSource, filePath); } @@ -115,8 +109,8 @@ void loadImage_withInputStream_mustReturnAValidLocalInputSource() throws IOExcep void loadImage_withByteArray_mustReturnAValidLocalInputSource() throws IOException { Path filePath = getResourcePath("file_types/receipt.jpg"); LocalInputSource localInputSource = new LocalInputSource( - Files.readAllBytes(filePath), - "receipt.jpg" + Files.readAllBytes(filePath), + "receipt.jpg" ); assertImage(localInputSource, filePath); } @@ -125,10 +119,7 @@ void loadImage_withByteArray_mustReturnAValidLocalInputSource() throws IOExcepti void loadImage_withBase64Encoded_mustReturnAValidLocalInputSource() throws IOException { Path filePath = getResourcePath("file_types/receipt.jpg"); String encodedFile = Base64.encodeBase64String(Files.readAllBytes(filePath)); - LocalInputSource localInputSource = new LocalInputSource( - encodedFile, - "receipt.jpg" - ); + LocalInputSource localInputSource = new LocalInputSource(encodedFile, "receipt.jpg"); assertImage(localInputSource, filePath); } diff --git a/src/test/java/com/mindee/input/LocalResponseV1Test.java b/src/test/java/com/mindee/input/LocalResponseV1Test.java index a17bfa944..cef89b839 100644 --- a/src/test/java/com/mindee/input/LocalResponseV1Test.java +++ b/src/test/java/com/mindee/input/LocalResponseV1Test.java @@ -9,7 +9,6 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; - public class LocalResponseV1Test { /** * Fake secret key. @@ -30,9 +29,10 @@ public class LocalResponseV1Test { void loadDocument_withFile_mustReturnValidLocalResponse() throws IOException { LocalResponse localResponse = new LocalResponse(new File(this.filePath.toString())); Assertions.assertNotNull(localResponse.getFile()); - Assertions.assertFalse(localResponse.isValidHmacSignature( - this.secretKey, "invalid signature is invalid") - ); + Assertions + .assertFalse( + localResponse.isValidHmacSignature(this.secretKey, "invalid signature is invalid") + ); Assertions.assertEquals(this.signature, localResponse.getHmacSignature(this.secretKey)); Assertions.assertTrue(localResponse.isValidHmacSignature(this.secretKey, this.signature)); } @@ -41,20 +41,20 @@ void loadDocument_withFile_mustReturnValidLocalResponse() throws IOException { void loadDocument_withString_mustReturnValidLocalResponse() { LocalResponse localResponse = new LocalResponse("{'some': 'json', 'with': 'data'}"); Assertions.assertNotNull(localResponse.getFile()); - Assertions.assertFalse(localResponse.isValidHmacSignature( - this.secretKey, "invalid signature is invalid") - ); + Assertions + .assertFalse( + localResponse.isValidHmacSignature(this.secretKey, "invalid signature is invalid") + ); } @Test void loadDocument_withInputStream_mustReturnValidLocalResponse() throws IOException { - LocalResponse localResponse = new LocalResponse( - Files.newInputStream(this.filePath) - ); + LocalResponse localResponse = new LocalResponse(Files.newInputStream(this.filePath)); Assertions.assertNotNull(localResponse.getFile()); - Assertions.assertFalse(localResponse.isValidHmacSignature( - this.secretKey, "invalid signature is invalid") - ); + Assertions + .assertFalse( + localResponse.isValidHmacSignature(this.secretKey, "invalid signature is invalid") + ); Assertions.assertEquals(this.signature, localResponse.getHmacSignature(this.secretKey)); Assertions.assertTrue(localResponse.isValidHmacSignature(this.secretKey, this.signature)); } diff --git a/src/test/java/com/mindee/input/LocalResponseV2Test.java b/src/test/java/com/mindee/input/LocalResponseV2Test.java index dbfbd7590..b33eab2d4 100644 --- a/src/test/java/com/mindee/input/LocalResponseV2Test.java +++ b/src/test/java/com/mindee/input/LocalResponseV2Test.java @@ -10,7 +10,6 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; - public class LocalResponseV2Test { /** * Fake secret key. @@ -29,9 +28,10 @@ public class LocalResponseV2Test { protected void assertLocalResponse(LocalResponse localResponse) { Assertions.assertNotNull(localResponse.getFile()); - Assertions.assertFalse(localResponse.isValidHmacSignature( - this.secretKey, "invalid signature is invalid") - ); + Assertions + .assertFalse( + localResponse.isValidHmacSignature(this.secretKey, "invalid signature is invalid") + ); Assertions.assertEquals(this.signature, localResponse.getHmacSignature(this.secretKey)); Assertions.assertTrue(localResponse.isValidHmacSignature(this.secretKey, this.signature)); InferenceResponse response = localResponse.deserializeResponse(InferenceResponse.class); @@ -49,16 +49,15 @@ void loadDocument_withFile_mustReturnValidLocalResponse() throws IOException { void loadDocument_withString_mustReturnValidLocalResponse() { LocalResponse localResponse = new LocalResponse("{'some': 'json', 'with': 'data'}"); Assertions.assertNotNull(localResponse.getFile()); - Assertions.assertFalse(localResponse.isValidHmacSignature( - this.secretKey, "invalid signature is invalid") - ); + Assertions + .assertFalse( + localResponse.isValidHmacSignature(this.secretKey, "invalid signature is invalid") + ); } @Test void loadDocument_withInputStream_mustReturnValidLocalResponse() throws IOException { - LocalResponse localResponse = new LocalResponse( - Files.newInputStream(this.filePath) - ); + LocalResponse localResponse = new LocalResponse(Files.newInputStream(this.filePath)); assertLocalResponse(localResponse); } } diff --git a/src/test/java/com/mindee/input/URLInputSourceIT.java b/src/test/java/com/mindee/input/URLInputSourceIT.java index 9f8ac7651..44bd772e1 100644 --- a/src/test/java/com/mindee/input/URLInputSourceIT.java +++ b/src/test/java/com/mindee/input/URLInputSourceIT.java @@ -20,9 +20,11 @@ static void clientSetUp() { @Test public void testURLInputSource_shouldSendApiCall() throws IOException { - URLInputSource remoteSource = URLInputSource.builder( + URLInputSource remoteSource = URLInputSource + .builder( "https://github.com/mindee/client-lib-test-data/blob/main/v1/products/invoice_splitter/invoice_5p.pdf?raw=true" - ).build(); + ) + .build(); remoteSource.fetchFile(); LocalInputSource localSource = remoteSource.toLocalInputSource(); assertTrue(localSource.getFilename().endsWith(".tmp")); diff --git a/src/test/java/com/mindee/input/URLInputSourceTest.java b/src/test/java/com/mindee/input/URLInputSourceTest.java index 9ae3a1e8f..9af0c2524 100644 --- a/src/test/java/com/mindee/input/URLInputSourceTest.java +++ b/src/test/java/com/mindee/input/URLInputSourceTest.java @@ -22,7 +22,6 @@ public void setUp() { urlInputSource = new TestableURLInputSource(TEST_URL); } - @AfterEach public void tearDown() { urlInputSource = null; @@ -47,7 +46,8 @@ void fetchFile_shouldThrowIOException_onFailedFetch() { } @Test - void fetchFile_shouldHandleRedirects() throws IOException {urlInputSource.setMockResponseCode(HttpURLConnection.HTTP_MOVED_TEMP); + void fetchFile_shouldHandleRedirects() throws IOException { + urlInputSource.setMockResponseCode(HttpURLConnection.HTTP_MOVED_TEMP); urlInputSource.setMockRedirectUrl("https://example.com/redirectedfile.pdf"); urlInputSource.setMockResponseCode(HttpURLConnection.HTTP_OK); @@ -84,7 +84,6 @@ void toLocalInputSource_shouldCreateLocalInputSource() throws IOException { urlInputSource.cleanup(); } - class TestableURLInputSource extends URLInputSource { @Setter @@ -97,7 +96,6 @@ public TestableURLInputSource(String url) { super(builder(url)); } - @Override protected HttpURLConnection createConnection(String urlString) throws IOException { HttpURLConnection mockConnection = mock(HttpURLConnection.class); diff --git a/src/test/java/com/mindee/parsing/common/AsyncPredictResponseTest.java b/src/test/java/com/mindee/parsing/common/AsyncPredictResponseTest.java index 6a899e1ac..83d1e5701 100644 --- a/src/test/java/com/mindee/parsing/common/AsyncPredictResponseTest.java +++ b/src/test/java/com/mindee/parsing/common/AsyncPredictResponseTest.java @@ -13,14 +13,15 @@ public class AsyncPredictResponseTest { - private AsyncPredictResponse loadAsyncResponse(Path filePath) throws IOException { + private AsyncPredictResponse loadAsyncResponse( + Path filePath + ) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - AsyncPredictResponse.class, - InvoiceSplitterV1.class - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(AsyncPredictResponse.class, InvoiceSplitterV1.class); return objectMapper.readValue(filePath.toFile(), type); } @@ -31,13 +32,13 @@ void whenIssuedTimeNonUTC_deserialized_mustConvertToUTCLocal() throws JsonProces ObjectMapper objectMapper = new ObjectMapper(); Job job = objectMapper.readValue(json, Job.class); - Assertions.assertEquals("2023-01-01T03:00",job.getIssuedAt().toString()); + Assertions.assertEquals("2023-01-01T03:00", job.getIssuedAt().toString()); } @Test void whenAsyncPost_returnsErrorForbidden_mustBeDeserialized() throws IOException { AsyncPredictResponse response = loadAsyncResponse( - getV1ResourcePath("async/post_fail_forbidden.json") + getV1ResourcePath("async/post_fail_forbidden.json") ); Assertions.assertNotNull(response); Assertions.assertEquals("failure", response.getApiRequest().getStatus()); @@ -54,7 +55,8 @@ void whenAsyncPost_returnsSuccess_mustBeDeserialized() throws IOException { Assertions.assertEquals("success", response.getApiRequest().getStatus()); Assertions.assertEquals(200, response.getApiRequest().getStatusCode()); Assertions.assertEquals("waiting", response.getJob().getStatus()); - Assertions.assertEquals("2023-02-16T12:33:49.602947", response.getJob().getIssuedAt().toString()); + Assertions + .assertEquals("2023-02-16T12:33:49.602947", response.getJob().getIssuedAt().toString()); Assertions.assertNull(response.getJob().getAvailableAt()); Assertions.assertFalse(response.getDocument().isPresent()); } @@ -62,12 +64,13 @@ void whenAsyncPost_returnsSuccess_mustBeDeserialized() throws IOException { @Test void whenAsyncGet_returnsProcessing_mustBeDeserialized() throws IOException { AsyncPredictResponse response = loadAsyncResponse( - getV1ResourcePath("async/get_processing.json") + getV1ResourcePath("async/get_processing.json") ); Assertions.assertNotNull(response); Assertions.assertEquals("success", response.getApiRequest().getStatus()); Assertions.assertEquals("processing", response.getJob().getStatus()); - Assertions.assertEquals("2023-03-16T12:33:49.602947", response.getJob().getIssuedAt().toString()); + Assertions + .assertEquals("2023-03-16T12:33:49.602947", response.getJob().getIssuedAt().toString()); Assertions.assertNull(response.getJob().getAvailableAt()); Assertions.assertFalse(response.getDocument().isPresent()); } @@ -75,13 +78,15 @@ void whenAsyncGet_returnsProcessing_mustBeDeserialized() throws IOException { @Test void whenAsyncGet_returnsCompleted_mustBeDeserialized() throws IOException { AsyncPredictResponse response = loadAsyncResponse( - getV1ResourcePath("async/get_completed.json") + getV1ResourcePath("async/get_completed.json") ); Assertions.assertNotNull(response); Assertions.assertEquals("success", response.getApiRequest().getStatus()); Assertions.assertEquals("completed", response.getJob().getStatus()); - Assertions.assertEquals("2023-03-21T13:52:56.326107", response.getJob().getIssuedAt().toString()); - Assertions.assertEquals("2023-03-21T13:53:00.990339", response.getJob().getAvailableAt().toString()); + Assertions + .assertEquals("2023-03-21T13:52:56.326107", response.getJob().getIssuedAt().toString()); + Assertions + .assertEquals("2023-03-21T13:53:00.990339", response.getJob().getAvailableAt().toString()); Assertions.assertTrue(response.getDocument().isPresent()); Assertions.assertEquals(2, response.getDocumentObj().getNPages()); } @@ -96,8 +101,10 @@ void whenAsyncGet_returnsJobFailed_mustBeDeserialized() throws IOException { Assertions.assertEquals(200, response.getApiRequest().getStatusCode()); Assertions.assertEquals("failed", response.getJob().getStatus()); Assertions.assertEquals("ServerError", response.getJob().getError().getCode()); - Assertions.assertEquals("2024-02-20T10:31:06.878599", response.getJob().getIssuedAt().toString()); - Assertions.assertEquals("2024-02-20T10:31:06.878599", response.getJob().getAvailableAt().toString()); + Assertions + .assertEquals("2024-02-20T10:31:06.878599", response.getJob().getIssuedAt().toString()); + Assertions + .assertEquals("2024-02-20T10:31:06.878599", response.getJob().getAvailableAt().toString()); Assertions.assertFalse(response.getDocument().isPresent()); } } diff --git a/src/test/java/com/mindee/parsing/common/CropperTest.java b/src/test/java/com/mindee/parsing/common/CropperTest.java index 0eb8083d7..48a553bf4 100644 --- a/src/test/java/com/mindee/parsing/common/CropperTest.java +++ b/src/test/java/com/mindee/parsing/common/CropperTest.java @@ -18,12 +18,11 @@ private List> loadResult() throws IOException { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - ReceiptV5.class); - PredictResponse prediction = objectMapper.readValue( - getV1ResourcePath("extras/cropper/complete.json").toFile(), - type); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, ReceiptV5.class); + PredictResponse prediction = objectMapper + .readValue(getV1ResourcePath("extras/cropper/complete.json").toFile(), type); return prediction.getDocument().getInference().getPages(); } diff --git a/src/test/java/com/mindee/parsing/common/ErrorTest.java b/src/test/java/com/mindee/parsing/common/ErrorTest.java index c0d206f3b..16915947e 100644 --- a/src/test/java/com/mindee/parsing/common/ErrorTest.java +++ b/src/test/java/com/mindee/parsing/common/ErrorTest.java @@ -15,15 +15,15 @@ void given_details_as_object_mustBeDeserialized() throws IOException { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - Error error = objectMapper.readValue( + Error error = objectMapper + .readValue( getV1ResourcePath("errors/with_object_response_in_detail.json").toFile(), - Error.class); + Error.class + ); Assertions.assertNotNull(error); Assertions.assertNotNull(error.getDetails()); - Assertions.assertEquals( - "{\"document\":[\"error message\"]}", - error.getDetails().toString()); + Assertions.assertEquals("{\"document\":[\"error message\"]}", error.getDetails().toString()); } @Test @@ -32,9 +32,11 @@ void given_details_as_string_mustBeDeserialized() throws IOException { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - Error error = objectMapper.readValue( + Error error = objectMapper + .readValue( getV1ResourcePath("errors/with_string_response_in_detail.json").toFile(), - Error.class); + Error.class + ); Assertions.assertNotNull(error); Assertions.assertNotNull(error.getDetails()); diff --git a/src/test/java/com/mindee/parsing/common/FullTextOcrTest.java b/src/test/java/com/mindee/parsing/common/FullTextOcrTest.java index 4ab295b49..cf8d1f24e 100644 --- a/src/test/java/com/mindee/parsing/common/FullTextOcrTest.java +++ b/src/test/java/com/mindee/parsing/common/FullTextOcrTest.java @@ -17,12 +17,11 @@ private Inference loadInfe ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - AsyncPredictResponse.class, - InternationalIdV2.class); - AsyncPredictResponse prediction = objectMapper.readValue( - getV1ResourcePath("extras/full_text_ocr/complete.json").toFile(), - type); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(AsyncPredictResponse.class, InternationalIdV2.class); + AsyncPredictResponse prediction = objectMapper + .readValue(getV1ResourcePath("extras/full_text_ocr/complete.json").toFile(), type); return prediction.getDocumentObj().getInference(); } @@ -31,21 +30,19 @@ private List> loadPages() throws IOException { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - AsyncPredictResponse.class, - InternationalIdV2.class); - AsyncPredictResponse prediction = objectMapper.readValue( - getV1ResourcePath("extras/full_text_ocr/complete.json").toFile(), - type); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(AsyncPredictResponse.class, InternationalIdV2.class); + AsyncPredictResponse prediction = objectMapper + .readValue(getV1ResourcePath("extras/full_text_ocr/complete.json").toFile(), type); return prediction.getDocumentObj().getInference().getPages(); } @Test void should_GetFullTextOcrResult() throws IOException { - List expectedText = Files.readAllLines( - getV1ResourcePath("extras/full_text_ocr/full_text_ocr.txt") - ); + List expectedText = Files + .readAllLines(getV1ResourcePath("extras/full_text_ocr/full_text_ocr.txt")); List> pages = loadPages(); Inference inference = loadInference(); String fullTextOcr = inference.getExtras().getFullTextOcr(); diff --git a/src/test/java/com/mindee/parsing/common/OcrTest.java b/src/test/java/com/mindee/parsing/common/OcrTest.java index bd2298a86..ea21a0e90 100644 --- a/src/test/java/com/mindee/parsing/common/OcrTest.java +++ b/src/test/java/com/mindee/parsing/common/OcrTest.java @@ -19,12 +19,11 @@ private Ocr loadResult() throws IOException { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - ReceiptV5.class); - PredictResponse prediction = objectMapper.readValue( - getV1ResourcePath("extras/ocr/complete.json").toFile(), - type); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, ReceiptV5.class); + PredictResponse prediction = objectMapper + .readValue(getV1ResourcePath("extras/ocr/complete.json").toFile(), type); return prediction.getDocument().getOcr(); } @@ -51,11 +50,10 @@ void whenDeserializedToString_shouldBeOrdered() throws IOException { Ocr ocr = loadResult(); - List expectedLines = Files.readAllLines( - getV1ResourcePath("extras/ocr/ocr.txt") - ); + List expectedLines = Files.readAllLines(getV1ResourcePath("extras/ocr/ocr.txt")); String expectedSummary = String.join(String.format("%n"), expectedLines); - Assertions.assertEquals(expectedSummary, ocr.toString(), "Should match expected string exactly."); + Assertions + .assertEquals(expectedSummary, ocr.toString(), "Should match expected string exactly."); } } diff --git a/src/test/java/com/mindee/parsing/custom/lineitems/FakeListField.java b/src/test/java/com/mindee/parsing/custom/lineitems/FakeListField.java index 8b1357a83..4113c3be2 100644 --- a/src/test/java/com/mindee/parsing/custom/lineitems/FakeListField.java +++ b/src/test/java/com/mindee/parsing/custom/lineitems/FakeListField.java @@ -14,158 +14,222 @@ private FakeListField() { static Map get2completeLines1halfLine() { Map fakes = new HashMap<>(); - fakes.put( - "birthDates", - new ListField( - 1.0, - Arrays.asList( - new ListFieldValue( - "1986-10-23", - 1.0, - new Polygon( - Arrays.asList( - new Point(0.818, 0.398), - new Point(0.902, 0.398), - new Point(0.902, 0.406), - new Point(0.818, 0.406)))), - new ListFieldValue( - "2012-02-13", - 1.0, - new Polygon( - Arrays.asList( - new Point(0.819, 0.442), - new Point(0.902, 0.442), - new Point(0.902, 0.451), - new Point(0.819, 0.451)))), - new ListFieldValue( - "1895-02-28", - 1.0, - new Polygon( - Arrays.asList( - new Point(0.819, 0.462), - new Point(0.902, 0.462), - new Point(0.902, 0.471), - new Point(0.819, 0.471)))) - )) - ); - fakes.put( - "names", - new ListField( - 1.0, - Arrays.asList( - new ListFieldValue( - "Kevin", - 1.0, - new Polygon( - Arrays.asList( - new Point(0.082, 0.398), - new Point(0.144, 0.398), - new Point(0.144, 0.407), - new Point(0.082, 0.407)))), - new ListFieldValue( - "Mindee", - 1.0, - new Polygon( - Arrays.asList( - new Point(0.152, 0.398), - new Point(0.222, 0.398), - new Point(0.222, 0.407), - new Point(0.152, 0.407)))), - new ListFieldValue( - "Ianaré", - 1.0, - new Polygon( - Arrays.asList( - new Point(0.081, 0.442), - new Point(0.15, 0.442), - new Point(0.15, 0.451), - new Point(0.081, 0.451)))), - new ListFieldValue( - "Mindee", - 1.0, - new Polygon( - Arrays.asList( - new Point(0.157, 0.442), - new Point(0.26, 0.442), - new Point(0.26, 0.451), - new Point(0.157, 0.451)))) - )) - ); + fakes + .put( + "birthDates", + new ListField( + 1.0, + Arrays + .asList( + new ListFieldValue( + "1986-10-23", + 1.0, + new Polygon( + Arrays + .asList( + new Point(0.818, 0.398), + new Point(0.902, 0.398), + new Point(0.902, 0.406), + new Point(0.818, 0.406) + ) + ) + ), + new ListFieldValue( + "2012-02-13", + 1.0, + new Polygon( + Arrays + .asList( + new Point(0.819, 0.442), + new Point(0.902, 0.442), + new Point(0.902, 0.451), + new Point(0.819, 0.451) + ) + ) + ), + new ListFieldValue( + "1895-02-28", + 1.0, + new Polygon( + Arrays + .asList( + new Point(0.819, 0.462), + new Point(0.902, 0.462), + new Point(0.902, 0.471), + new Point(0.819, 0.471) + ) + ) + ) + ) + ) + ); + fakes + .put( + "names", + new ListField( + 1.0, + Arrays + .asList( + new ListFieldValue( + "Kevin", + 1.0, + new Polygon( + Arrays + .asList( + new Point(0.082, 0.398), + new Point(0.144, 0.398), + new Point(0.144, 0.407), + new Point(0.082, 0.407) + ) + ) + ), + new ListFieldValue( + "Mindee", + 1.0, + new Polygon( + Arrays + .asList( + new Point(0.152, 0.398), + new Point(0.222, 0.398), + new Point(0.222, 0.407), + new Point(0.152, 0.407) + ) + ) + ), + new ListFieldValue( + "Ianaré", + 1.0, + new Polygon( + Arrays + .asList( + new Point(0.081, 0.442), + new Point(0.15, 0.442), + new Point(0.15, 0.451), + new Point(0.081, 0.451) + ) + ) + ), + new ListFieldValue( + "Mindee", + 1.0, + new Polygon( + Arrays + .asList( + new Point(0.157, 0.442), + new Point(0.26, 0.442), + new Point(0.26, 0.451), + new Point(0.157, 0.451) + ) + ) + ) + ) + ) + ); return fakes; } static Map getWith2ValuesByExpectedLines() { Map fakes = new HashMap<>(); - fakes.put( - "birthDates", - new ListField( - 1.0, - Arrays.asList( - new ListFieldValue( - "1986-10-23", - 1.0, - new Polygon( - Arrays.asList( - new Point(0.818, 0.398), - new Point(0.902, 0.398), - new Point(0.902, 0.406), - new Point(0.818, 0.406)))), - new ListFieldValue( - "2012-02-13", - 1.0, - new Polygon( - Arrays.asList( - new Point(0.819, 0.442), - new Point(0.902, 0.442), - new Point(0.902, 0.451), - new Point(0.819, 0.451)))) - )) - ); + fakes + .put( + "birthDates", + new ListField( + 1.0, + Arrays + .asList( + new ListFieldValue( + "1986-10-23", + 1.0, + new Polygon( + Arrays + .asList( + new Point(0.818, 0.398), + new Point(0.902, 0.398), + new Point(0.902, 0.406), + new Point(0.818, 0.406) + ) + ) + ), + new ListFieldValue( + "2012-02-13", + 1.0, + new Polygon( + Arrays + .asList( + new Point(0.819, 0.442), + new Point(0.902, 0.442), + new Point(0.902, 0.451), + new Point(0.819, 0.451) + ) + ) + ) + ) + ) + ); - fakes.put( - "names", - new ListField( - 1.0, - Arrays.asList( - new ListFieldValue( + fakes + .put( + "names", + new ListField( + 1.0, + Arrays + .asList( + new ListFieldValue( "Kevin", 1.0, new Polygon( - Arrays.asList( - new Point(0.082, 0.398), - new Point(0.144, 0.398), - new Point(0.144, 0.407), - new Point(0.082, 0.407)))), - new ListFieldValue( + Arrays + .asList( + new Point(0.082, 0.398), + new Point(0.144, 0.398), + new Point(0.144, 0.407), + new Point(0.082, 0.407) + ) + ) + ), + new ListFieldValue( "Mindee", 1.0, new Polygon( - Arrays.asList( - new Point(0.152, 0.398), - new Point(0.222, 0.398), - new Point(0.222, 0.407), - new Point(0.152, 0.407)))), - new ListFieldValue( + Arrays + .asList( + new Point(0.152, 0.398), + new Point(0.222, 0.398), + new Point(0.222, 0.407), + new Point(0.152, 0.407) + ) + ) + ), + new ListFieldValue( "Ianaré", 1.0, new Polygon( - Arrays.asList( - new Point(0.081, 0.442), - new Point(0.15, 0.442), - new Point(0.15, 0.451), - new Point(0.081, 0.451)))), - new ListFieldValue( + Arrays + .asList( + new Point(0.081, 0.442), + new Point(0.15, 0.442), + new Point(0.15, 0.451), + new Point(0.081, 0.451) + ) + ) + ), + new ListFieldValue( "Mindee", 1.0, new Polygon( - Arrays.asList( - new Point(0.157, 0.442), - new Point(0.26, 0.442), - new Point(0.26, 0.451), - new Point(0.157, 0.451)))) - )) - ); + Arrays + .asList( + new Point(0.157, 0.442), + new Point(0.26, 0.442), + new Point(0.26, 0.451), + new Point(0.157, 0.451) + ) + ) + ) + ) + ) + ); return fakes; } @@ -173,252 +237,353 @@ static Map getWith2ValuesByExpectedLines() { static Map getWith1FieldValueForTheLastLine() { Map fakes = new HashMap<>(); - fakes.put( - "birthDates", - new ListField( - 1.0, - Arrays.asList( - new ListFieldValue( + fakes + .put( + "birthDates", + new ListField( + 1.0, + Arrays + .asList( + new ListFieldValue( "1986-10-23", 1.0, new Polygon( - Arrays.asList( - new Point(0.818, 0.398), - new Point(0.902, 0.398), - new Point(0.902, 0.406), - new Point(0.818, 0.406)))), - new ListFieldValue( + Arrays + .asList( + new Point(0.818, 0.398), + new Point(0.902, 0.398), + new Point(0.902, 0.406), + new Point(0.818, 0.406) + ) + ) + ), + new ListFieldValue( "2012-02-13", 1.0, new Polygon( - Arrays.asList( - new Point(0.819, 0.442), - new Point(0.902, 0.442), - new Point(0.902, 0.451), - new Point(0.819, 0.451)))) - )) - ); + Arrays + .asList( + new Point(0.819, 0.442), + new Point(0.902, 0.442), + new Point(0.902, 0.451), + new Point(0.819, 0.451) + ) + ) + ) + ) + ) + ); - fakes.put( - "names", - new ListField( - 1.0, - Arrays.asList( - new ListFieldValue( + fakes + .put( + "names", + new ListField( + 1.0, + Arrays + .asList( + new ListFieldValue( "Kevin", 1.0, new Polygon( - Arrays.asList( - new Point(0.082, 0.398), - new Point(0.144, 0.398), - new Point(0.144, 0.407), - new Point(0.082, 0.407)))), - new ListFieldValue( + Arrays + .asList( + new Point(0.082, 0.398), + new Point(0.144, 0.398), + new Point(0.144, 0.407), + new Point(0.082, 0.407) + ) + ) + ), + new ListFieldValue( "Mindee", - 1.0, - new Polygon( - Arrays.asList( - new Point(0.152, 0.398), - new Point(0.222, 0.398), - new Point(0.222, 0.407), - new Point(0.152, 0.407)))), - new ListFieldValue( + 1.0, + new Polygon( + Arrays + .asList( + new Point(0.152, 0.398), + new Point(0.222, 0.398), + new Point(0.222, 0.407), + new Point(0.152, 0.407) + ) + ) + ), + new ListFieldValue( "Ianaré", - 1.0, - new Polygon( - Arrays.asList( - new Point(0.081, 0.442), - new Point(0.15, 0.442), - new Point(0.15, 0.451), - new Point(0.081, 0.451)))), - new ListFieldValue( + 1.0, + new Polygon( + Arrays + .asList( + new Point(0.081, 0.442), + new Point(0.15, 0.442), + new Point(0.15, 0.451), + new Point(0.081, 0.451) + ) + ) + ), + new ListFieldValue( "Mindee", - 1.0, - new Polygon( - Arrays.asList( - new Point(0.157, 0.442), - new Point(0.26, 0.442), - new Point(0.26, 0.451), - new Point(0.157, 0.451)))), - new ListFieldValue( + 1.0, + new Polygon( + Arrays + .asList( + new Point(0.157, 0.442), + new Point(0.26, 0.442), + new Point(0.26, 0.451), + new Point(0.157, 0.451) + ) + ) + ), + new ListFieldValue( "Bob", - 1.0, - new Polygon( - Arrays.asList( - new Point(0.082, 0.486), - new Point(0.151, 0.486), - new Point(0.151, 0.495), - new Point(0.082, 0.495)))) - )) - ); + 1.0, + new Polygon( + Arrays + .asList( + new Point(0.082, 0.486), + new Point(0.151, 0.486), + new Point(0.151, 0.495), + new Point(0.082, 0.495) + ) + ) + ) + ) + ) + ); return fakes; } static Map getWith1ExpectedLines() { Map fakes = new HashMap<>(); - fakes.put( - "birthDates", - new ListField( - 1.0, - Arrays.asList( - new ListFieldValue( - "1986-10-23", - 1.0, - new Polygon( - Arrays.asList( - new Point(0.818, 0.398), - new Point(0.902, 0.398), - new Point(0.902, 0.406), - new Point(0.818, 0.406)))) - )) - ); - fakes.put( - "names", - new ListField( - 1.0, - Arrays.asList( - new ListFieldValue( + fakes + .put( + "birthDates", + new ListField( + 1.0, + Arrays + .asList( + new ListFieldValue( + "1986-10-23", + 1.0, + new Polygon( + Arrays + .asList( + new Point(0.818, 0.398), + new Point(0.902, 0.398), + new Point(0.902, 0.406), + new Point(0.818, 0.406) + ) + ) + ) + ) + ) + ); + fakes + .put( + "names", + new ListField( + 1.0, + Arrays + .asList( + new ListFieldValue( "Kevin", 1.0, new Polygon( - Arrays.asList( - new Point(0.082, 0.398), - new Point(0.144, 0.398), - new Point(0.144, 0.407), - new Point(0.082, 0.407)))), - new ListFieldValue( + Arrays + .asList( + new Point(0.082, 0.398), + new Point(0.144, 0.398), + new Point(0.144, 0.407), + new Point(0.082, 0.407) + ) + ) + ), + new ListFieldValue( "Mindee", 1.0, new Polygon( - Arrays.asList( - new Point(0.152, 0.398), - new Point(0.222, 0.398), - new Point(0.222, 0.407), - new Point(0.152, 0.407)))) - )) - ); + Arrays + .asList( + new Point(0.152, 0.398), + new Point(0.222, 0.398), + new Point(0.222, 0.407), + new Point(0.152, 0.407) + ) + ) + ) + ) + ) + ); return fakes; } static Map getWithPolygonsNotExactlyOnTheSameAxis() { Map fakes = new HashMap<>(); - fakes.put( - "birthDates", - new ListField( - 1.0, - Arrays.asList( - new ListFieldValue( + fakes + .put( + "birthDates", + new ListField( + 1.0, + Arrays + .asList( + new ListFieldValue( "1986-10-23", 1.0, new Polygon( - Arrays.asList( - new Point(0.576, 0.401), - new Point(0.649, 0.401), - new Point(0.649, 0.408), - new Point(0.576, 0.408)))), - new ListFieldValue( + Arrays + .asList( + new Point(0.576, 0.401), + new Point(0.649, 0.401), + new Point(0.649, 0.408), + new Point(0.576, 0.408) + ) + ) + ), + new ListFieldValue( "2012-02-13", 1.0, new Polygon( - Arrays.asList( - new Point(0.581, 0.45), - new Point(0.656, 0.45), - new Point(0.656, 0.458), - new Point(0.581, 0.458)))) - )) - ); - fakes.put( - "names", - new ListField( - 1.0, - Arrays.asList( - new ListFieldValue( + Arrays + .asList( + new Point(0.581, 0.45), + new Point(0.656, 0.45), + new Point(0.656, 0.458), + new Point(0.581, 0.458) + ) + ) + ) + ) + ) + ); + fakes + .put( + "names", + new ListField( + 1.0, + Arrays + .asList( + new ListFieldValue( "Kevin", 1.0, new Polygon( - Arrays.asList( - new Point(0.119, 0.4), - new Point(0.179, 0.4), - new Point(0.178, 0.41), - new Point(0.119, 0.409)))), - new ListFieldValue( + Arrays + .asList( + new Point(0.119, 0.4), + new Point(0.179, 0.4), + new Point(0.178, 0.41), + new Point(0.119, 0.409) + ) + ) + ), + new ListFieldValue( "Mindee", - 1.0, - new Polygon( - Arrays.asList( - new Point(0.185, 0.401), - new Point(0.232, 0.401), - new Point(0.232, 0.41), - new Point(0.184, 0.409)))), - new ListFieldValue( + 1.0, + new Polygon( + Arrays + .asList( + new Point(0.185, 0.401), + new Point(0.232, 0.401), + new Point(0.232, 0.41), + new Point(0.184, 0.409) + ) + ) + ), + new ListFieldValue( "Ianaré", - 1.0, - new Polygon( - Arrays.asList( - new Point(0.118, 0.45), - new Point(0.169, 0.451), - new Point(0.169, 0.458), - new Point(0.117, 0.457)))) - )) - ); + 1.0, + new Polygon( + Arrays + .asList( + new Point(0.118, 0.45), + new Point(0.169, 0.451), + new Point(0.169, 0.458), + new Point(0.117, 0.457) + ) + ) + ) + ) + ) + ); return fakes; } static Map getSampleWichRender2LinesInsteadOfOne() { Map fakes = new HashMap<>(); - fakes.put( - "names", - new ListField( - 1.0, - Arrays.asList( - new ListFieldValue( + fakes + .put( + "names", + new ListField( + 1.0, + Arrays + .asList( + new ListFieldValue( "A", 1.0, new Polygon( - Arrays.asList( - new Point(0.075, 0.42), - new Point(0.141, 0.42), - new Point(0.141, 0.428), - new Point(0.075, 0.428)))), - new ListFieldValue( + Arrays + .asList( + new Point(0.075, 0.42), + new Point(0.141, 0.42), + new Point(0.141, 0.428), + new Point(0.075, 0.428) + ) + ) + ), + new ListFieldValue( "B", - 1.0, - new Polygon( - Arrays.asList( - new Point(0.148, 0.42), - new Point(0.198, 0.42), - new Point(0.198, 0.428), - new Point(0.148, 0.428)))), - new ListFieldValue( + 1.0, + new Polygon( + Arrays + .asList( + new Point(0.148, 0.42), + new Point(0.198, 0.42), + new Point(0.198, 0.428), + new Point(0.148, 0.428) + ) + ) + ), + new ListFieldValue( "C", - 1.0, - new Polygon( - Arrays.asList( - new Point(0.2, 0.42), - new Point(0.204, 0.42), - new Point(0.204, 0.428), - new Point(0.2, 0.428)))), - new ListFieldValue( + 1.0, + new Polygon( + Arrays + .asList( + new Point(0.2, 0.42), + new Point(0.204, 0.42), + new Point(0.204, 0.428), + new Point(0.2, 0.428) + ) + ) + ), + new ListFieldValue( "D", - 1.0, - new Polygon( - Arrays.asList( - new Point(0.206, 0.42), - new Point(0.257, 0.42), - new Point(0.257, 0.428), - new Point(0.206, 0.428)))), - new ListFieldValue( + 1.0, + new Polygon( + Arrays + .asList( + new Point(0.206, 0.42), + new Point(0.257, 0.42), + new Point(0.257, 0.428), + new Point(0.206, 0.428) + ) + ) + ), + new ListFieldValue( "E", - 1.0, - new Polygon( - Arrays.asList( - new Point(0.263, 0.42), - new Point(0.33, 0.42), - new Point(0.33, 0.428), - new Point(0.263, 0.428)))) - )) - ); + 1.0, + new Polygon( + Arrays + .asList( + new Point(0.263, 0.42), + new Point(0.33, 0.42), + new Point(0.33, 0.428), + new Point(0.263, 0.428) + ) + ) + ) + ) + ) + ); return fakes; } } diff --git a/src/test/java/com/mindee/parsing/custom/lineitems/LineGeneratorTest.java b/src/test/java/com/mindee/parsing/custom/lineitems/LineGeneratorTest.java index f340e1393..346b0bf68 100644 --- a/src/test/java/com/mindee/parsing/custom/lineitems/LineGeneratorTest.java +++ b/src/test/java/com/mindee/parsing/custom/lineitems/LineGeneratorTest.java @@ -10,80 +10,69 @@ class LineGeneratorTest { - private static final List anchors = Collections.singletonList( - new Anchor("names", 0.01d) - ); + private static final List anchors = Collections.singletonList(new Anchor("names", 0.01d)); @Test void prepareLinesWith2ValuesOnEachLineWithPolygonValuesOnExactlyTheSameAxis() { - Collection lines = LineGenerator.prepareLines( - FakeListField.getWith2ValuesByExpectedLines(), - anchors - ).getLines(); + Collection lines = LineGenerator + .prepareLines(FakeListField.getWith2ValuesByExpectedLines(), anchors) + .getLines(); Assertions.assertEquals(2, lines.size()); } @Test void prepareLinesWhenAnchorHasMoreLines() { - Collection lines = LineGenerator.prepareLines( - FakeListField.get2completeLines1halfLine(), - Collections.singletonList(new Anchor("birthDates")) - ).getLines(); + Collection lines = LineGenerator + .prepareLines( + FakeListField.get2completeLines1halfLine(), + Collections.singletonList(new Anchor("birthDates")) + ) + .getLines(); Assertions.assertEquals(3, lines.size()); } @Test void prepareLinesWithTwoAnchors() { - PreparedLines preparedLines = LineGenerator.prepareLines( - FakeListField.get2completeLines1halfLine(), - Arrays.asList( - new Anchor("names"), - new Anchor("birthDates") - ) - ); + PreparedLines preparedLines = LineGenerator + .prepareLines( + FakeListField.get2completeLines1halfLine(), + Arrays.asList(new Anchor("names"), new Anchor("birthDates")) + ); Assertions.assertEquals("birthDates", preparedLines.getAnchor().getName()); Assertions.assertEquals(3, preparedLines.getLines().size()); } @Test void prepareLinesWith1FieldValueForTheLastLine() { - Collection lines = LineGenerator.prepareLines( - FakeListField.getWith1FieldValueForTheLastLine(), - anchors - ).getLines(); + Collection lines = LineGenerator + .prepareLines(FakeListField.getWith1FieldValueForTheLastLine(), anchors) + .getLines(); Assertions.assertEquals(3, lines.size()); } @Test void prepareLinesWith1ExpectedLine() { - Collection table = LineGenerator.prepareLines( - FakeListField.getWith1ExpectedLines(), - anchors - ).getLines(); + Collection table = LineGenerator + .prepareLines(FakeListField.getWith1ExpectedLines(), anchors) + .getLines(); Assertions.assertEquals(1, table.size()); } @Test void prepareLinesWithPolygonsNotExactlyOnTheSameAxis() { - List anchors = Collections.singletonList( - new Anchor("names", 0.005d) - ); - Collection table = LineGenerator.prepareLines( - FakeListField.getWithPolygonsNotExactlyOnTheSameAxis(), - anchors - ).getLines(); + List anchors = Collections.singletonList(new Anchor("names", 0.005d)); + Collection table = LineGenerator + .prepareLines(FakeListField.getWithPolygonsNotExactlyOnTheSameAxis(), anchors) + .getLines(); Assertions.assertEquals(2, table.size()); } @Test void prepareLinesWhichRender2LinesInsteadOfOne() { - List anchors = Collections.singletonList( - new Anchor("names", 0.0d) - ); - Collection table = LineGenerator.prepareLines( - FakeListField.getSampleWichRender2LinesInsteadOfOne(), - anchors - ).getLines(); + List anchors = Collections.singletonList(new Anchor("names", 0.0d)); + Collection table = LineGenerator + .prepareLines(FakeListField.getSampleWichRender2LinesInsteadOfOne(), anchors) + .getLines(); Assertions.assertEquals(1, table.size()); } diff --git a/src/test/java/com/mindee/parsing/standard/DateFieldTest.java b/src/test/java/com/mindee/parsing/standard/DateFieldTest.java index 5303b545a..ec2667a84 100644 --- a/src/test/java/com/mindee/parsing/standard/DateFieldTest.java +++ b/src/test/java/com/mindee/parsing/standard/DateFieldTest.java @@ -11,19 +11,21 @@ public class DateFieldTest { @Test void testConstructor_mustCreate() { - DateField date = - new DateField( - LocalDate.parse("2018-04-01"), - 0.1, - new Polygon(Arrays.asList( - new Point(0.016, 0.707), - new Point(0.414, 0.707), - new Point(0.414, 0.831), - new Point(0.016, 0.831) - )), - 0, - true - ); + DateField date = new DateField( + LocalDate.parse("2018-04-01"), + 0.1, + new Polygon( + Arrays + .asList( + new Point(0.016, 0.707), + new Point(0.414, 0.707), + new Point(0.414, 0.831), + new Point(0.016, 0.831) + ) + ), + 0, + true + ); Assertions.assertEquals("2018-04-01", date.getValue().toString()); Assertions.assertTrue(date.getIsComputed()); diff --git a/src/test/java/com/mindee/parsing/v2/InferenceTest.java b/src/test/java/com/mindee/parsing/v2/InferenceTest.java index 24222238b..10f5319a8 100644 --- a/src/test/java/com/mindee/parsing/v2/InferenceTest.java +++ b/src/test/java/com/mindee/parsing/v2/InferenceTest.java @@ -32,7 +32,6 @@ private InferenceResponse loadInference(String filePath) throws IOException { return localResponse.deserializeResponse(InferenceResponse.class); } - @Nested @DisplayName("Inference on blank file") class BlankPredictionTest { @@ -95,7 +94,11 @@ void asyncPredict_whenComplete_mustExposeAllProperties() throws IOException { InferenceResponse response = loadInference("products/financial_document/complete.json"); Inference inference = response.getInference(); assertNotNull(inference, "Inference must not be null"); - assertEquals("12345678-1234-1234-1234-123456789abc", inference.getId(), "Inference ID mismatch"); + assertEquals( + "12345678-1234-1234-1234-123456789abc", + inference.getId(), + "Inference ID mismatch" + ); InferenceModel model = inference.getModel(); assertNotNull(model, "Model must not be null"); @@ -180,8 +183,10 @@ void deepNestedFields_mustExposeCorrectTypes() throws IOException { assertNotNull(items.get(0).getObjectField()); ObjectField firstItem = items.get(0).getObjectField(); - SimpleField deepSimple = firstItem.getFields() - .get("sub_object_object_sub_object_list_simple").getSimpleField(); + SimpleField deepSimple = firstItem + .getFields() + .get("sub_object_object_sub_object_list_simple") + .getSimpleField(); assertEquals("value_9", deepSimple.getValue()); } } @@ -307,8 +312,8 @@ void standardFieldTypes_mustExposeObjectListFieldValues() throws IOException { assertEquals(2, dynamicItems.size()); ObjectField firstDynamicItem = dynamicItems.get(0).getObjectField(); assertEquals( - FieldConfidence.Low, - firstDynamicItem.getFields().get("subfield_1").getSimpleField().getConfidence() + FieldConfidence.Low, + firstDynamicItem.getFields().get("subfield_1").getSimpleField().getConfidence() ); for (DynamicField item : dynamicItems) { ObjectField itemField = item.getObjectField(); @@ -321,8 +326,8 @@ void standardFieldTypes_mustExposeObjectListFieldValues() throws IOException { assertEquals(2, objectItems.size()); ObjectField firstObjectItem = objectItems.get(0); assertEquals( - FieldConfidence.Low, - firstObjectItem.getSimpleFields().get("subfield_1").getConfidence() + FieldConfidence.Low, + firstObjectItem.getSimpleFields().get("subfield_1").getConfidence() ); for (ObjectField itemField : objectItems) { assertNotNull(itemField); @@ -332,9 +337,9 @@ void standardFieldTypes_mustExposeObjectListFieldValues() throws IOException { SimpleField itemSubfield1 = itemSubFields.getSimpleField("subfield_1"); assertInstanceOf(String.class, itemSubfield1.getValue()); for (Map.Entry entry : itemFields.entrySet()) { - String fieldName = entry.getKey(); - SimpleField subfield = entry.getValue(); - testObjectSubFieldSimpleString(fieldName, subfield); + String fieldName = entry.getKey(); + SimpleField subfield = entry.getValue(); + testObjectSubFieldSimpleString(fieldName, subfield); } } @@ -385,30 +390,30 @@ void standardFieldTypes_getWithGenerics() throws IOException { InferenceFields fields = inference.getResult().getFields(); assertEquals( - fields.get("field_simple_bool").getSimpleField(), - fields.get("field_simple_bool").getField(SimpleField.class) + fields.get("field_simple_bool").getSimpleField(), + fields.get("field_simple_bool").getField(SimpleField.class) ); assertEquals( - fields.get("field_simple_bool").getSimpleField(), - fields.getSimpleField("field_simple_bool") + fields.get("field_simple_bool").getSimpleField(), + fields.getSimpleField("field_simple_bool") ); assertEquals( - fields.get("field_simple_list").getListField(), - fields.get("field_simple_list").getField(ListField.class) + fields.get("field_simple_list").getListField(), + fields.get("field_simple_list").getField(ListField.class) ); assertEquals( - fields.get("field_simple_list").getListField(), - fields.getListField("field_simple_list") + fields.get("field_simple_list").getListField(), + fields.getListField("field_simple_list") ); assertEquals( - fields.get("field_object").getObjectField(), - fields.get("field_object").getField(ObjectField.class) + fields.get("field_object").getObjectField(), + fields.get("field_object").getField(ObjectField.class) ); assertEquals( - fields.get("field_object").getObjectField(), - fields.getObjectField("field_object") + fields.get("field_object").getObjectField(), + fields.getObjectField("field_object") ); } @@ -549,10 +554,7 @@ void textContext_mustBePresentAndTrue() throws IOException { Inference inference = resp.getInference(); assertNotNull(inference); InferenceFields fields = inference.getResult().getFields(); - assertEquals( - "a test value", - fields.get("test_replace").getSimpleField().getStringValue() - ); + assertEquals("a test value", fields.get("test_replace").getSimpleField().getStringValue()); assertTrue(inference.getActiveOptions().getDataSchema().getReplace()); } diff --git a/src/test/java/com/mindee/pdf/PDFUtilsTest.java b/src/test/java/com/mindee/pdf/PDFUtilsTest.java index 4c12aa837..cf78023bb 100644 --- a/src/test/java/com/mindee/pdf/PDFUtilsTest.java +++ b/src/test/java/com/mindee/pdf/PDFUtilsTest.java @@ -18,7 +18,6 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; - public class PDFUtilsTest { @Test @@ -38,8 +37,7 @@ public void givenADocument_whenPageCounted_thenReturnsCorrectPageCount() throws } @Test - public void givenADocumentAndListOfPages_whenMerged_thenReturnsCorrectDocument() - throws IOException { + public void givenADocumentAndListOfPages_whenMerged_thenReturnsCorrectDocument() throws IOException { Path original = Paths.get("src/test/resources/file_types/pdf/multipage.pdf"); Path copied = Paths.get("src/test/resources/output/fileToTest.pdf"); Files.copy(original, copied, StandardCopyOption.REPLACE_EXISTING); @@ -76,24 +74,32 @@ public void givenAnEmptyDocument_whenEmptyChecked_shouldReturnTrue() throws IOEx @Test public void shouldConvertAllPagesToJpg() throws IOException { - List pdfPageImages = PDFUtils.pdfToImages( - "src/test/resources/file_types/pdf/multipage_cut-2.pdf" - ); + List pdfPageImages = PDFUtils + .pdfToImages("src/test/resources/file_types/pdf/multipage_cut-2.pdf"); for (PdfPageImage pdfPageImage : pdfPageImages) { Assertions.assertNotNull(pdfPageImage.getImage()); - Assertions.assertEquals(pdfPageImage.asInputSource().getFilename(), pdfPageImage.getFilename()); + Assertions + .assertEquals(pdfPageImage.asInputSource().getFilename(), pdfPageImage.getFilename()); pdfPageImage.writeToFile("src/test/resources/output/"); - Assertions.assertTrue(Files.exists(Paths.get("src/test/resources/output/" + pdfPageImage.getFilename()))); + Assertions + .assertTrue( + Files.exists(Paths.get("src/test/resources/output/" + pdfPageImage.getFilename())) + ); } } @Test public void shouldConvertSinglePageToJpg() throws IOException { - LocalInputSource source = new LocalInputSource("src/test/resources/file_types/pdf/multipage.pdf"); + LocalInputSource source = new LocalInputSource( + "src/test/resources/file_types/pdf/multipage.pdf" + ); PdfPageImage pdfPageImage = PDFUtils.pdfPageToImage(source, 3); Assertions.assertNotNull(pdfPageImage.getImage()); Assertions.assertEquals(pdfPageImage.asInputSource().getFilename(), pdfPageImage.getFilename()); pdfPageImage.writeToFile("src/test/resources/output/"); - Assertions.assertTrue(Files.exists(Paths.get("src/test/resources/output/" + pdfPageImage.getFilename()))); + Assertions + .assertTrue( + Files.exists(Paths.get("src/test/resources/output/" + pdfPageImage.getFilename())) + ); } } diff --git a/src/test/java/com/mindee/pdf/PdfOperationTest.java b/src/test/java/com/mindee/pdf/PdfOperationTest.java index 9a5ba2fa7..5ed8d32dc 100644 --- a/src/test/java/com/mindee/pdf/PdfOperationTest.java +++ b/src/test/java/com/mindee/pdf/PdfOperationTest.java @@ -12,23 +12,19 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; - public class PdfOperationTest { private final PdfOperation pdfOperation = new PdfBoxApi(); @Test - public void givenADocumentAndPageToKeep_whenSplit_thenReturnsOnlyKeptPage() - throws IOException { + public void givenADocumentAndPageToKeep_whenSplit_thenReturnsOnlyKeptPage() throws IOException { PageOptions pageOptions = new PageOptions.Builder() - .pageIndexes(new Integer[]{ 2 }) - .operation(PageOptionsOperation.KEEP_ONLY) - .build(); + .pageIndexes(new Integer[] { 2 }) + .operation(PageOptionsOperation.KEEP_ONLY) + .build(); - byte[] fileBytes = Files.readAllBytes( - getResourcePath("file_types/pdf/multipage.pdf") - ); + byte[] fileBytes = Files.readAllBytes(getResourcePath("file_types/pdf/multipage.pdf")); SplitQuery splitQuery = new SplitQuery(fileBytes, pageOptions); SplitPdf splitPdf = pdfOperation.split(splitQuery); @@ -38,21 +34,20 @@ public void givenADocumentAndPageToKeep_whenSplit_thenReturnsOnlyKeptPage() } @Test - public void givenADocumentAndListOfPagesToKeep_whenSplit_thenReturnsOnlyKeptPages() - throws IOException { + public void givenADocumentAndListOfPagesToKeep_whenSplit_thenReturnsOnlyKeptPages() throws IOException { List pageNumbersToKeep = new ArrayList<>(); pageNumbersToKeep.add(0); pageNumbersToKeep.add(1); PageOptions pageOptions = new PageOptions.Builder() - .pageIndexes(pageNumbersToKeep) - .operation(PageOptionsOperation.KEEP_ONLY) - .build(); + .pageIndexes(pageNumbersToKeep) + .operation(PageOptionsOperation.KEEP_ONLY) + .build(); SplitQuery splitQuery = new SplitQuery( - Files.readAllBytes(getResourcePath("file_types/pdf/multipage.pdf")), - pageOptions + Files.readAllBytes(getResourcePath("file_types/pdf/multipage.pdf")), + pageOptions ); SplitPdf splitPdf = pdfOperation.split(splitQuery); @@ -62,17 +57,16 @@ public void givenADocumentAndListOfPagesToKeep_whenSplit_thenReturnsOnlyKeptPage } @Test - public void givenADocumentAndListOfPagesToRemove_whenSplit_thenReturnsOnlyNotRemovedPages() - throws IOException { + public void givenADocumentAndListOfPagesToRemove_whenSplit_thenReturnsOnlyNotRemovedPages() throws IOException { PageOptions pageOptions = new PageOptions.Builder() - .pageIndexes(new Integer[]{ 0,1,2 }) - .operation(PageOptionsOperation.REMOVE) - .build(); + .pageIndexes(new Integer[] { 0, 1, 2 }) + .operation(PageOptionsOperation.REMOVE) + .build(); SplitQuery splitQuery = new SplitQuery( - Files.readAllBytes(getResourcePath("file_types/pdf/multipage.pdf")), - pageOptions + Files.readAllBytes(getResourcePath("file_types/pdf/multipage.pdf")), + pageOptions ); SplitPdf splitPdf = pdfOperation.split(splitQuery); @@ -82,37 +76,33 @@ public void givenADocumentAndListOfPagesToRemove_whenSplit_thenReturnsOnlyNotRem } @Test - public void givenADocumentOtherThantAPdf_whenSplit_mustFail() - throws IOException { + public void givenADocumentOtherThantAPdf_whenSplit_mustFail() throws IOException { PageOptions pageOptions = new PageOptions.Builder() - .pageIndexes(new Integer[]{ 1,2,3 }) - .operation(PageOptionsOperation.REMOVE) - .build(); + .pageIndexes(new Integer[] { 1, 2, 3 }) + .operation(PageOptionsOperation.REMOVE) + .build(); SplitQuery splitQuery = new SplitQuery( - Files.readAllBytes(getResourcePath("file_types/receipt.jpg")), - pageOptions + Files.readAllBytes(getResourcePath("file_types/receipt.jpg")), + pageOptions ); - Assertions.assertThrows( - MindeeException.class, - () -> pdfOperation.split(splitQuery)); + Assertions.assertThrows(MindeeException.class, () -> pdfOperation.split(splitQuery)); } @Test - public void givenADocumentAndListPagesToRemoveAndMinPagesCondition_whenSplit_mustNotRemovePages() - throws IOException { + public void givenADocumentAndListPagesToRemoveAndMinPagesCondition_whenSplit_mustNotRemovePages() throws IOException { PageOptions pageOptions = new PageOptions.Builder() - .pageIndexes(new Integer[]{ 0 }) - .operation(PageOptionsOperation.REMOVE) - .onMinPages(5) - .build(); + .pageIndexes(new Integer[] { 0 }) + .operation(PageOptionsOperation.REMOVE) + .onMinPages(5) + .build(); SplitQuery splitQuery = new SplitQuery( - Files.readAllBytes(getResourcePath("file_types/pdf/multipage_cut-2.pdf")), - pageOptions + Files.readAllBytes(getResourcePath("file_types/pdf/multipage_cut-2.pdf")), + pageOptions ); SplitPdf splitPdf = pdfOperation.split(splitQuery); @@ -122,17 +112,16 @@ public void givenADocumentAndListPagesToRemoveAndMinPagesCondition_whenSplit_mus } @Test - public void givenADocumentAndNegativeListPagesToKeep_whenSplit_thenReturnsOnlyKeptPages() - throws IOException { + public void givenADocumentAndNegativeListPagesToKeep_whenSplit_thenReturnsOnlyKeptPages() throws IOException { PageOptions pageOptions = new PageOptions.Builder() - .pageIndexes(new Integer[]{ 0,-2,-1 }) - .operation(PageOptionsOperation.KEEP_ONLY) - .build(); + .pageIndexes(new Integer[] { 0, -2, -1 }) + .operation(PageOptionsOperation.KEEP_ONLY) + .build(); SplitQuery splitQuery = new SplitQuery( - Files.readAllBytes(getResourcePath("file_types/pdf/multipage.pdf")), - pageOptions + Files.readAllBytes(getResourcePath("file_types/pdf/multipage.pdf")), + pageOptions ); SplitPdf splitPdf = pdfOperation.split(splitQuery); diff --git a/src/test/java/com/mindee/product/barcodereader/BarcodeReaderV1Test.java b/src/test/java/com/mindee/product/barcodereader/BarcodeReaderV1Test.java index a772a9432..794481672 100644 --- a/src/test/java/com/mindee/product/barcodereader/BarcodeReaderV1Test.java +++ b/src/test/java/com/mindee/product/barcodereader/BarcodeReaderV1Test.java @@ -21,14 +21,14 @@ protected PredictResponse getPrediction(String name) throws IOE ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - BarcodeReaderV1.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/barcode_reader/response_v1/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, BarcodeReaderV1.class); + return objectMapper + .readValue( + new File(getV1ResourcePathString("products/barcode_reader/response_v1/" + name + ".json")), + type + ); } @Test @@ -44,8 +44,8 @@ void whenCompleteDeserialized_mustHaveValidDocumentSummary() throws IOException PredictResponse response = getPrediction("complete"); Document doc = response.getDocument(); assertStringEqualsFile( - doc.toString(), - getV1ResourcePathString("products/barcode_reader/response_v1/summary_full.rst") + doc.toString(), + getV1ResourcePathString("products/barcode_reader/response_v1/summary_full.rst") ); } diff --git a/src/test/java/com/mindee/product/billoflading/BillOfLadingV1Test.java b/src/test/java/com/mindee/product/billoflading/BillOfLadingV1Test.java index 17aa9125b..4e1673e8f 100644 --- a/src/test/java/com/mindee/product/billoflading/BillOfLadingV1Test.java +++ b/src/test/java/com/mindee/product/billoflading/BillOfLadingV1Test.java @@ -21,14 +21,14 @@ protected PredictResponse getPrediction(String name) throws IOEx ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - BillOfLadingV1.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/bill_of_lading/response_v1/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, BillOfLadingV1.class); + return objectMapper + .readValue( + new File(getV1ResourcePathString("products/bill_of_lading/response_v1/" + name + ".json")), + type + ); } @Test @@ -64,8 +64,8 @@ void whenCompleteDeserialized_mustHaveValidDocumentSummary() throws IOException PredictResponse response = getPrediction("complete"); Document doc = response.getDocument(); assertStringEqualsFile( - doc.toString(), - getV1ResourcePathString("products/bill_of_lading/response_v1/summary_full.rst") + doc.toString(), + getV1ResourcePathString("products/bill_of_lading/response_v1/summary_full.rst") ); } diff --git a/src/test/java/com/mindee/product/businesscard/BusinessCardV1Test.java b/src/test/java/com/mindee/product/businesscard/BusinessCardV1Test.java index 6ac2b8bf2..0bfe0e100 100644 --- a/src/test/java/com/mindee/product/businesscard/BusinessCardV1Test.java +++ b/src/test/java/com/mindee/product/businesscard/BusinessCardV1Test.java @@ -21,14 +21,14 @@ protected PredictResponse getPrediction(String name) throws IOEx ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - BusinessCardV1.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/business_card/response_v1/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, BusinessCardV1.class); + return objectMapper + .readValue( + new File(getV1ResourcePathString("products/business_card/response_v1/" + name + ".json")), + type + ); } @Test @@ -53,8 +53,8 @@ void whenCompleteDeserialized_mustHaveValidDocumentSummary() throws IOException PredictResponse response = getPrediction("complete"); Document doc = response.getDocument(); assertStringEqualsFile( - doc.toString(), - getV1ResourcePathString("products/business_card/response_v1/summary_full.rst") + doc.toString(), + getV1ResourcePathString("products/business_card/response_v1/summary_full.rst") ); } diff --git a/src/test/java/com/mindee/product/cropper/CropperV1Test.java b/src/test/java/com/mindee/product/cropper/CropperV1Test.java index cae31c929..d6a8a7b31 100644 --- a/src/test/java/com/mindee/product/cropper/CropperV1Test.java +++ b/src/test/java/com/mindee/product/cropper/CropperV1Test.java @@ -22,20 +22,25 @@ protected PredictResponse getPrediction(String name) throws IOExcepti ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - CropperV1.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/cropper/response_v1/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, CropperV1.class); + return objectMapper + .readValue( + new File(getV1ResourcePathString("products/cropper/response_v1/" + name + ".json")), + type + ); } @Test void whenEmptyDeserialized_mustHaveValidProperties() throws IOException { PredictResponse response = getPrediction("empty"); - CropperV1Page pagePrediction = response.getDocument().getInference().getPages().get(0).getPrediction(); + CropperV1Page pagePrediction = response + .getDocument() + .getInference() + .getPages() + .get(0) + .getPrediction(); Assertions.assertTrue(pagePrediction.getCropping().isEmpty()); } @@ -44,8 +49,8 @@ void whenCompleteDeserialized_mustHaveValidDocumentSummary() throws IOException PredictResponse response = getPrediction("complete"); Document doc = response.getDocument(); assertStringEqualsFile( - doc.toString(), - getV1ResourcePathString("products/cropper/response_v1/summary_full.rst") + doc.toString(), + getV1ResourcePathString("products/cropper/response_v1/summary_full.rst") ); } @@ -54,8 +59,8 @@ void whenCompleteDeserialized_mustHaveValidPage0Summary() throws IOException { PredictResponse response = getPrediction("complete"); Page page = response.getDocument().getInference().getPages().get(0); assertStringEqualsFile( - page.toString(), - getV1ResourcePathString("products/cropper/response_v1/summary_page0.rst") + page.toString(), + getV1ResourcePathString("products/cropper/response_v1/summary_page0.rst") ); } } diff --git a/src/test/java/com/mindee/product/custom/CustomV1Test.java b/src/test/java/com/mindee/product/custom/CustomV1Test.java index d648d1d5c..88d08ecff 100644 --- a/src/test/java/com/mindee/product/custom/CustomV1Test.java +++ b/src/test/java/com/mindee/product/custom/CustomV1Test.java @@ -22,14 +22,14 @@ protected PredictResponse getPrediction(String name) throws IOExceptio ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - CustomV1.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/custom/response_v1/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, CustomV1.class); + return objectMapper + .readValue( + new File(getV1ResourcePathString("products/custom/response_v1/" + name + ".json")), + type + ); } @Test diff --git a/src/test/java/com/mindee/product/custom/CustomV1WithLineItemsTest.java b/src/test/java/com/mindee/product/custom/CustomV1WithLineItemsTest.java index a38ebe922..b404e2e25 100644 --- a/src/test/java/com/mindee/product/custom/CustomV1WithLineItemsTest.java +++ b/src/test/java/com/mindee/product/custom/CustomV1WithLineItemsTest.java @@ -23,17 +23,29 @@ void givenACustomDocument_expected_3_lines() throws IOException { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType(PredictResponse.class, - CustomV1.class); - PredictResponse response = objectMapper.readValue( - new File(getV1ResourcePathString("products/custom/response_v1/line_items/single_table_01.json")), - type); - - LineItems lineItems = LineItemsGenerator.generate( - Arrays.asList("beneficiary_birth_date", "beneficiary_number", "beneficiary_name", "beneficiary_rank"), - response.getDocument().getInference().getPrediction().getFields(), - new Anchor("beneficiary_name", 0.011d) - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, CustomV1.class); + PredictResponse response = objectMapper + .readValue( + new File( + getV1ResourcePathString("products/custom/response_v1/line_items/single_table_01.json") + ), + type + ); + + LineItems lineItems = LineItemsGenerator + .generate( + Arrays + .asList( + "beneficiary_birth_date", + "beneficiary_number", + "beneficiary_name", + "beneficiary_rank" + ), + response.getDocument().getInference().getPrediction().getFields(), + new Anchor("beneficiary_name", 0.011d) + ); Assertions.assertNotNull(lineItems); Assertions.assertEquals(3, lineItems.getRows().size()); @@ -47,13 +59,16 @@ void givenACustomDocument_expected_3_lines() throws IOException { Assertions.assertTrue(line1.getFields().containsKey("beneficiary_number")); Assertions.assertTrue(line1.getFields().containsKey("beneficiary_name")); Assertions.assertTrue(line1.getFields().containsKey("beneficiary_rank")); - Assertions.assertEquals("1970-11-11", line1.getFields().get("beneficiary_birth_date").getValue()); + Assertions + .assertEquals("1970-11-11", line1.getFields().get("beneficiary_birth_date").getValue()); Assertions.assertEquals("1", line1.getFields().get("beneficiary_rank").getValue()); Line line2 = lineItems.getRows().get(1); - Assertions.assertEquals("2010-07-18", line2.getFields().get("beneficiary_birth_date").getValue()); + Assertions + .assertEquals("2010-07-18", line2.getFields().get("beneficiary_birth_date").getValue()); Assertions.assertEquals("2", line2.getFields().get("beneficiary_rank").getValue()); Line line3 = lineItems.getRows().get(2); - Assertions.assertEquals("2015-07-05", line3.getFields().get("beneficiary_birth_date").getValue()); + Assertions + .assertEquals("2015-07-05", line3.getFields().get("beneficiary_birth_date").getValue()); Assertions.assertEquals("3", line3.getFields().get("beneficiary_rank").getValue()); } } diff --git a/src/test/java/com/mindee/product/deliverynote/DeliveryNoteV1Test.java b/src/test/java/com/mindee/product/deliverynote/DeliveryNoteV1Test.java index c2a4a2c0d..573ce2f7b 100644 --- a/src/test/java/com/mindee/product/deliverynote/DeliveryNoteV1Test.java +++ b/src/test/java/com/mindee/product/deliverynote/DeliveryNoteV1Test.java @@ -21,14 +21,14 @@ protected PredictResponse getPrediction(String name) throws IOEx ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - DeliveryNoteV1.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/delivery_notes/response_v1/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, DeliveryNoteV1.class); + return objectMapper + .readValue( + new File(getV1ResourcePathString("products/delivery_notes/response_v1/" + name + ".json")), + type + ); } @Test @@ -49,8 +49,8 @@ void whenCompleteDeserialized_mustHaveValidDocumentSummary() throws IOException PredictResponse response = getPrediction("complete"); Document doc = response.getDocument(); assertStringEqualsFile( - doc.toString(), - getV1ResourcePathString("products/delivery_notes/response_v1/summary_full.rst") + doc.toString(), + getV1ResourcePathString("products/delivery_notes/response_v1/summary_full.rst") ); } diff --git a/src/test/java/com/mindee/product/driverlicense/DriverLicenseV1Test.java b/src/test/java/com/mindee/product/driverlicense/DriverLicenseV1Test.java index 27a00c36e..97c2b14ac 100644 --- a/src/test/java/com/mindee/product/driverlicense/DriverLicenseV1Test.java +++ b/src/test/java/com/mindee/product/driverlicense/DriverLicenseV1Test.java @@ -21,14 +21,14 @@ protected PredictResponse getPrediction(String name) throws IOE ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - DriverLicenseV1.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/driver_license/response_v1/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, DriverLicenseV1.class); + return objectMapper + .readValue( + new File(getV1ResourcePathString("products/driver_license/response_v1/" + name + ".json")), + type + ); } @Test @@ -55,8 +55,8 @@ void whenCompleteDeserialized_mustHaveValidDocumentSummary() throws IOException PredictResponse response = getPrediction("complete"); Document doc = response.getDocument(); assertStringEqualsFile( - doc.toString(), - getV1ResourcePathString("products/driver_license/response_v1/summary_full.rst") + doc.toString(), + getV1ResourcePathString("products/driver_license/response_v1/summary_full.rst") ); } diff --git a/src/test/java/com/mindee/product/financialdocument/FinancialDocumentV1Test.java b/src/test/java/com/mindee/product/financialdocument/FinancialDocumentV1Test.java index 8cf754a66..87eb7df0f 100644 --- a/src/test/java/com/mindee/product/financialdocument/FinancialDocumentV1Test.java +++ b/src/test/java/com/mindee/product/financialdocument/FinancialDocumentV1Test.java @@ -22,15 +22,22 @@ void givenFinancialV1_withInvoice_whenDeserialized_MustHaveAValidSummary() throw ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType(PredictResponse.class, - FinancialDocumentV1.class); - PredictResponse prediction = objectMapper.readValue( - new File(getV1ResourcePathString("products/financial_document/response_v1/complete_invoice.json")), - type); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, FinancialDocumentV1.class); + PredictResponse prediction = objectMapper + .readValue( + new File( + getV1ResourcePathString("products/financial_document/response_v1/complete_invoice.json") + ), + type + ); String[] actualLines = prediction.getDocument().toString().split(System.lineSeparator()); List expectedLines = Files - .readAllLines(getV1ResourcePath("products/financial_document/response_v1/summary_full_invoice.rst")); + .readAllLines( + getV1ResourcePath("products/financial_document/response_v1/summary_full_invoice.rst") + ); String expectedSummary = String.join(String.format("%n"), expectedLines); String actualSummary = String.join(String.format("%n"), actualLines); @@ -43,18 +50,28 @@ void givenFinancialV1_withInvoice_firstPage_MustHaveAValidSummary() throws IOExc ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType(PredictResponse.class, - FinancialDocumentV1.class); - PredictResponse prediction = objectMapper.readValue( - new File(getV1ResourcePathString("products/financial_document/response_v1/complete_invoice.json")), - type); - - String[] actualLines = prediction.getDocument().getInference() + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, FinancialDocumentV1.class); + PredictResponse prediction = objectMapper + .readValue( + new File( + getV1ResourcePathString("products/financial_document/response_v1/complete_invoice.json") + ), + type + ); + + String[] actualLines = prediction + .getDocument() + .getInference() .getPages() - .get(0).toString().split(System.lineSeparator()); - List expectedLines = Files.readAllLines( + .get(0) + .toString() + .split(System.lineSeparator()); + List expectedLines = Files + .readAllLines( getV1ResourcePath("products/financial_document/response_v1/summary_page0_invoice.rst") - ); + ); String expectedSummary = String.join(String.format("%n"), expectedLines); String actualSummary = String.join(String.format("%n"), actualLines); @@ -67,15 +84,22 @@ void givenFinancialV1_withReceipt_whenDeserialized_MustHaveAValidSummary() throw ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType(PredictResponse.class, - FinancialDocumentV1.class); - PredictResponse prediction = objectMapper.readValue( - new File(getV1ResourcePathString("products/financial_document/response_v1/complete_receipt.json")), - type); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, FinancialDocumentV1.class); + PredictResponse prediction = objectMapper + .readValue( + new File( + getV1ResourcePathString("products/financial_document/response_v1/complete_receipt.json") + ), + type + ); String[] actualLines = prediction.getDocument().toString().split(System.lineSeparator()); List expectedLines = Files - .readAllLines(getV1ResourcePath("products/financial_document/response_v1/summary_full_receipt.rst")); + .readAllLines( + getV1ResourcePath("products/financial_document/response_v1/summary_full_receipt.rst") + ); String expectedSummary = String.join(String.format("%n"), expectedLines); String actualSummary = String.join(String.format("%n"), actualLines); @@ -88,32 +112,47 @@ void givenFinancialV1_withReceipt_firstPage_MustHaveAValidSummary() throws IOExc ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType(PredictResponse.class, - FinancialDocumentV1.class); - PredictResponse prediction = objectMapper.readValue( - new File(getV1ResourcePathString("products/financial_document/response_v1/complete_receipt.json")), - type); - - String[] actualLines = prediction.getDocument().getInference() + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, FinancialDocumentV1.class); + PredictResponse prediction = objectMapper + .readValue( + new File( + getV1ResourcePathString("products/financial_document/response_v1/complete_receipt.json") + ), + type + ); + + String[] actualLines = prediction + .getDocument() + .getInference() .getPages() - .get(0).toString().split(System.lineSeparator()); + .get(0) + .toString() + .split(System.lineSeparator()); List expectedLines = Files - .readAllLines(getV1ResourcePath("products/financial_document/response_v1/summary_page0_receipt.rst")); + .readAllLines( + getV1ResourcePath("products/financial_document/response_v1/summary_page0_receipt.rst") + ); String expectedSummary = String.join(String.format("%n"), expectedLines); String actualSummary = String.join(String.format("%n"), actualLines); Assertions.assertEquals(expectedSummary, actualSummary); } + @Test void givenFinancialV1_withEmptyDocument_whenDeserialized_MustHaveExpectedValues() throws IOException { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType(PredictResponse.class, - FinancialDocumentV1.class); - PredictResponse response = objectMapper.readValue( + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, FinancialDocumentV1.class); + PredictResponse response = objectMapper + .readValue( new File(getV1ResourcePathString("products/financial_document/response_v1/empty.json")), - type); + type + ); Document doc = response.getDocument(); FinancialDocumentV1Document prediction = doc.getInference().getPrediction(); diff --git a/src/test/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV1Test.java b/src/test/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV1Test.java index 27259de9f..7423551b8 100644 --- a/src/test/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV1Test.java +++ b/src/test/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV1Test.java @@ -21,20 +21,25 @@ protected PredictResponse getPrediction(String name) throw ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - BankAccountDetailsV1.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/bank_account_details/response_v1/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, BankAccountDetailsV1.class); + return objectMapper + .readValue( + new File( + getV1ResourcePathString("products/bank_account_details/response_v1/" + name + ".json") + ), + type + ); } @Test void whenEmptyDeserialized_mustHaveValidProperties() throws IOException { PredictResponse response = getPrediction("empty"); - BankAccountDetailsV1Document docPrediction = response.getDocument().getInference().getPrediction(); + BankAccountDetailsV1Document docPrediction = response + .getDocument() + .getInference() + .getPrediction(); Assertions.assertNull(docPrediction.getIban().getValue()); Assertions.assertNull(docPrediction.getAccountHolderName().getValue()); Assertions.assertNull(docPrediction.getSwift().getValue()); @@ -45,8 +50,8 @@ void whenCompleteDeserialized_mustHaveValidDocumentSummary() throws IOException PredictResponse response = getPrediction("complete"); Document doc = response.getDocument(); assertStringEqualsFile( - doc.toString(), - getV1ResourcePathString("products/bank_account_details/response_v1/summary_full.rst") + doc.toString(), + getV1ResourcePathString("products/bank_account_details/response_v1/summary_full.rst") ); } diff --git a/src/test/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV2Test.java b/src/test/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV2Test.java index 8ae2bb096..7b73f8df2 100644 --- a/src/test/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV2Test.java +++ b/src/test/java/com/mindee/product/fr/bankaccountdetails/BankAccountDetailsV2Test.java @@ -21,20 +21,25 @@ protected PredictResponse getPrediction(String name) throw ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - BankAccountDetailsV2.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/bank_account_details/response_v2/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, BankAccountDetailsV2.class); + return objectMapper + .readValue( + new File( + getV1ResourcePathString("products/bank_account_details/response_v2/" + name + ".json") + ), + type + ); } @Test void whenEmptyDeserialized_mustHaveValidProperties() throws IOException { PredictResponse response = getPrediction("empty"); - BankAccountDetailsV2Document docPrediction = response.getDocument().getInference().getPrediction(); + BankAccountDetailsV2Document docPrediction = response + .getDocument() + .getInference() + .getPrediction(); Assertions.assertNull(docPrediction.getAccountHoldersNames().getValue()); Assertions.assertNull(docPrediction.getBban().getBbanBankCode()); Assertions.assertNull(docPrediction.getBban().getBbanBranchCode()); @@ -49,8 +54,8 @@ void whenCompleteDeserialized_mustHaveValidDocumentSummary() throws IOException PredictResponse response = getPrediction("complete"); Document doc = response.getDocument(); assertStringEqualsFile( - doc.toString(), - getV1ResourcePathString("products/bank_account_details/response_v2/summary_full.rst") + doc.toString(), + getV1ResourcePathString("products/bank_account_details/response_v2/summary_full.rst") ); } diff --git a/src/test/java/com/mindee/product/fr/cartegrise/CarteGriseV1Test.java b/src/test/java/com/mindee/product/fr/cartegrise/CarteGriseV1Test.java index b22a9c540..146477982 100644 --- a/src/test/java/com/mindee/product/fr/cartegrise/CarteGriseV1Test.java +++ b/src/test/java/com/mindee/product/fr/cartegrise/CarteGriseV1Test.java @@ -21,14 +21,14 @@ protected PredictResponse getPrediction(String name) throws IOExce ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - CarteGriseV1.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/carte_grise/response_v1/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, CarteGriseV1.class); + return objectMapper + .readValue( + new File(getV1ResourcePathString("products/carte_grise/response_v1/" + name + ".json")), + type + ); } @Test @@ -83,8 +83,8 @@ void whenCompleteDeserialized_mustHaveValidDocumentSummary() throws IOException PredictResponse response = getPrediction("complete"); Document doc = response.getDocument(); assertStringEqualsFile( - doc.toString(), - getV1ResourcePathString("products/carte_grise/response_v1/summary_full.rst") + doc.toString(), + getV1ResourcePathString("products/carte_grise/response_v1/summary_full.rst") ); } diff --git a/src/test/java/com/mindee/product/fr/energybill/EnergyBillV1Test.java b/src/test/java/com/mindee/product/fr/energybill/EnergyBillV1Test.java index e227ff368..5b3a7b6a8 100644 --- a/src/test/java/com/mindee/product/fr/energybill/EnergyBillV1Test.java +++ b/src/test/java/com/mindee/product/fr/energybill/EnergyBillV1Test.java @@ -21,14 +21,14 @@ protected PredictResponse getPrediction(String name) throws IOExce ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - EnergyBillV1.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/energy_bill_fra/response_v1/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, EnergyBillV1.class); + return objectMapper + .readValue( + new File(getV1ResourcePathString("products/energy_bill_fra/response_v1/" + name + ".json")), + type + ); } @Test @@ -60,8 +60,8 @@ void whenCompleteDeserialized_mustHaveValidDocumentSummary() throws IOException PredictResponse response = getPrediction("complete"); Document doc = response.getDocument(); assertStringEqualsFile( - doc.toString(), - getV1ResourcePathString("products/energy_bill_fra/response_v1/summary_full.rst") + doc.toString(), + getV1ResourcePathString("products/energy_bill_fra/response_v1/summary_full.rst") ); } diff --git a/src/test/java/com/mindee/product/fr/healthcard/HealthCardV1Test.java b/src/test/java/com/mindee/product/fr/healthcard/HealthCardV1Test.java index 7522ae35a..69e467478 100644 --- a/src/test/java/com/mindee/product/fr/healthcard/HealthCardV1Test.java +++ b/src/test/java/com/mindee/product/fr/healthcard/HealthCardV1Test.java @@ -21,14 +21,16 @@ protected PredictResponse getPrediction(String name) throws IOExce ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - HealthCardV1.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/french_healthcard/response_v1/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, HealthCardV1.class); + return objectMapper + .readValue( + new File( + getV1ResourcePathString("products/french_healthcard/response_v1/" + name + ".json") + ), + type + ); } @Test @@ -46,8 +48,8 @@ void whenCompleteDeserialized_mustHaveValidDocumentSummary() throws IOException PredictResponse response = getPrediction("complete"); Document doc = response.getDocument(); assertStringEqualsFile( - doc.toString(), - getV1ResourcePathString("products/french_healthcard/response_v1/summary_full.rst") + doc.toString(), + getV1ResourcePathString("products/french_healthcard/response_v1/summary_full.rst") ); } diff --git a/src/test/java/com/mindee/product/fr/idcard/IdCardV1Test.java b/src/test/java/com/mindee/product/fr/idcard/IdCardV1Test.java index 6d7bfd1ac..5669371e7 100644 --- a/src/test/java/com/mindee/product/fr/idcard/IdCardV1Test.java +++ b/src/test/java/com/mindee/product/fr/idcard/IdCardV1Test.java @@ -23,14 +23,14 @@ protected PredictResponse getPrediction(String name) throws IOExceptio ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - IdCardV1.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/idcard_fr/response_v1/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, IdCardV1.class); + return objectMapper + .readValue( + new File(getV1ResourcePathString("products/idcard_fr/response_v1/" + name + ".json")), + type + ); } @Test @@ -47,7 +47,12 @@ void whenEmptyDeserialized_mustHaveValidProperties() throws IOException { Assertions.assertNull(docPrediction.getGender().getValue()); Assertions.assertNull(docPrediction.getMrz1().getValue()); Assertions.assertNull(docPrediction.getMrz2().getValue()); - IdCardV1Page pagePrediction = response.getDocument().getInference().getPages().get(0).getPrediction(); + IdCardV1Page pagePrediction = response + .getDocument() + .getInference() + .getPages() + .get(0) + .getPrediction(); Assertions.assertInstanceOf(ClassificationField.class, pagePrediction.getDocumentSide()); } @@ -56,8 +61,8 @@ void whenCompleteDeserialized_mustHaveValidDocumentSummary() throws IOException PredictResponse response = getPrediction("complete"); Document doc = response.getDocument(); assertStringEqualsFile( - doc.toString(), - getV1ResourcePathString("products/idcard_fr/response_v1/summary_full.rst") + doc.toString(), + getV1ResourcePathString("products/idcard_fr/response_v1/summary_full.rst") ); } @@ -66,8 +71,8 @@ void whenCompleteDeserialized_mustHaveValidPage0Summary() throws IOException { PredictResponse response = getPrediction("complete"); Page page = response.getDocument().getInference().getPages().get(0); assertStringEqualsFile( - page.toString(), - getV1ResourcePathString("products/idcard_fr/response_v1/summary_page0.rst") + page.toString(), + getV1ResourcePathString("products/idcard_fr/response_v1/summary_page0.rst") ); } } diff --git a/src/test/java/com/mindee/product/fr/idcard/IdCardV2Test.java b/src/test/java/com/mindee/product/fr/idcard/IdCardV2Test.java index 787645565..a03abb0ac 100644 --- a/src/test/java/com/mindee/product/fr/idcard/IdCardV2Test.java +++ b/src/test/java/com/mindee/product/fr/idcard/IdCardV2Test.java @@ -23,14 +23,14 @@ protected PredictResponse getPrediction(String name) throws IOExceptio ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - IdCardV2.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/idcard_fr/response_v2/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, IdCardV2.class); + return objectMapper + .readValue( + new File(getV1ResourcePathString("products/idcard_fr/response_v2/" + name + ".json")), + type + ); } @Test @@ -52,7 +52,12 @@ void whenEmptyDeserialized_mustHaveValidProperties() throws IOException { Assertions.assertNull(docPrediction.getMrz3().getValue()); Assertions.assertNull(docPrediction.getIssueDate().getValue()); Assertions.assertNull(docPrediction.getAuthority().getValue()); - IdCardV2Page pagePrediction = response.getDocument().getInference().getPages().get(0).getPrediction(); + IdCardV2Page pagePrediction = response + .getDocument() + .getInference() + .getPages() + .get(0) + .getPrediction(); Assertions.assertInstanceOf(ClassificationField.class, pagePrediction.getDocumentType()); Assertions.assertInstanceOf(ClassificationField.class, pagePrediction.getDocumentSide()); } @@ -62,8 +67,8 @@ void whenCompleteDeserialized_mustHaveValidDocumentSummary() throws IOException PredictResponse response = getPrediction("complete"); Document doc = response.getDocument(); assertStringEqualsFile( - doc.toString(), - getV1ResourcePathString("products/idcard_fr/response_v2/summary_full.rst") + doc.toString(), + getV1ResourcePathString("products/idcard_fr/response_v2/summary_full.rst") ); } @@ -72,8 +77,8 @@ void whenCompleteDeserialized_mustHaveValidPage0Summary() throws IOException { PredictResponse response = getPrediction("complete"); Page page = response.getDocument().getInference().getPages().get(0); assertStringEqualsFile( - page.toString(), - getV1ResourcePathString("products/idcard_fr/response_v2/summary_page0.rst") + page.toString(), + getV1ResourcePathString("products/idcard_fr/response_v2/summary_page0.rst") ); } } diff --git a/src/test/java/com/mindee/product/fr/payslip/PayslipV2Test.java b/src/test/java/com/mindee/product/fr/payslip/PayslipV2Test.java index ca315b66d..691047509 100644 --- a/src/test/java/com/mindee/product/fr/payslip/PayslipV2Test.java +++ b/src/test/java/com/mindee/product/fr/payslip/PayslipV2Test.java @@ -21,14 +21,14 @@ protected PredictResponse getPrediction(String name) throws IOExcepti ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - PayslipV2.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/payslip_fra/response_v2/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, PayslipV2.class); + return objectMapper + .readValue( + new File(getV1ResourcePathString("products/payslip_fra/response_v2/" + name + ".json")), + type + ); } @Test @@ -84,8 +84,8 @@ void whenCompleteDeserialized_mustHaveValidDocumentSummary() throws IOException PredictResponse response = getPrediction("complete"); Document doc = response.getDocument(); assertStringEqualsFile( - doc.toString(), - getV1ResourcePathString("products/payslip_fra/response_v2/summary_full.rst") + doc.toString(), + getV1ResourcePathString("products/payslip_fra/response_v2/summary_full.rst") ); } diff --git a/src/test/java/com/mindee/product/fr/payslip/PayslipV3Test.java b/src/test/java/com/mindee/product/fr/payslip/PayslipV3Test.java index 75be04f97..a05071df1 100644 --- a/src/test/java/com/mindee/product/fr/payslip/PayslipV3Test.java +++ b/src/test/java/com/mindee/product/fr/payslip/PayslipV3Test.java @@ -21,14 +21,14 @@ protected PredictResponse getPrediction(String name) throws IOExcepti ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - PayslipV3.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/payslip_fra/response_v3/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, PayslipV3.class); + return objectMapper + .readValue( + new File(getV1ResourcePathString("products/payslip_fra/response_v3/" + name + ".json")), + type + ); } @Test @@ -83,8 +83,8 @@ void whenCompleteDeserialized_mustHaveValidDocumentSummary() throws IOException PredictResponse response = getPrediction("complete"); Document doc = response.getDocument(); assertStringEqualsFile( - doc.toString(), - getV1ResourcePathString("products/payslip_fra/response_v3/summary_full.rst") + doc.toString(), + getV1ResourcePathString("products/payslip_fra/response_v3/summary_full.rst") ); } diff --git a/src/test/java/com/mindee/product/generated/GeneratedV1Test.java b/src/test/java/com/mindee/product/generated/GeneratedV1Test.java index 812583ab8..13683ecf8 100644 --- a/src/test/java/com/mindee/product/generated/GeneratedV1Test.java +++ b/src/test/java/com/mindee/product/generated/GeneratedV1Test.java @@ -26,47 +26,51 @@ protected AsyncPredictResponse getAsyncPrediction(String name) thro ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - AsyncPredictResponse.class, - GeneratedV1.class - ); - return objectMapper.readValue( + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(AsyncPredictResponse.class, GeneratedV1.class); + return objectMapper + .readValue( new File(getV1ResourcePathString("products/generated/response_v1/" + name + ".json")), type - ); + ); } protected AsyncPredictResponse getUsMailPrediction() throws IOException { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - AsyncPredictResponse.class, - GeneratedV1.class - ); - return objectMapper.readValue( + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(AsyncPredictResponse.class, GeneratedV1.class); + return objectMapper + .readValue( new File(getV1ResourcePathString("products/us_mail/response_v3/complete.json")), type - ); + ); } protected PredictResponse getSyncPrediction(String name) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - GeneratedV1.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/generated/response_v1/" + name + "_invoice_v4.json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, GeneratedV1.class); + return objectMapper + .readValue( + new File( + getV1ResourcePathString("products/generated/response_v1/" + name + "_invoice_v4.json") + ), + type + ); } @Test void whenAsyncBadPolygonsDeserialized_mustHaveValidProperties() throws IOException { - AsyncPredictResponse response = getAsyncPrediction("bad_polygons_driver_license_v1"); + AsyncPredictResponse response = getAsyncPrediction( + "bad_polygons_driver_license_v1" + ); GeneratedV1Document docPrediction = response.getDocumentObj().getInference().getPrediction(); Map features = docPrediction.getFields(); @@ -90,7 +94,11 @@ void whenAsyncCompleteDeserialized_mustHaveValidProperties() throws IOException // Direct access to the hashmap Assertions.assertFalse(features.get("address").isList()); - Assertions.assertEquals("AVDA DE MADRID S-N MADRID MADRID", features.get("address").get(0).get("value")); + Assertions + .assertEquals( + "AVDA DE MADRID S-N MADRID MADRID", + features.get("address").get(0).get("value") + ); Assertions.assertFalse(features.get("birth_date").isList()); Assertions.assertEquals("1980-01-01", features.get("birth_date").get(0).get("value")); @@ -113,10 +121,7 @@ void whenAsyncCompleteDeserialized_mustHaveValidProperties() throws IOException // Access as a StringField without raw_value StringField addressField = features.get("address").asStringField(); - Assertions.assertEquals( - "AVDA DE MADRID S-N MADRID MADRID", - addressField.getValue() - ); + Assertions.assertEquals("AVDA DE MADRID S-N MADRID MADRID", addressField.getValue()); Assertions.assertNull(addressField.getRawValue()); Assertions.assertNull(addressField.getConfidence()); Assertions.assertNull(addressField.getPageId()); @@ -124,10 +129,7 @@ void whenAsyncCompleteDeserialized_mustHaveValidProperties() throws IOException // Access as a DateField DateField expiryDateField = features.get("expiry_date").asDateField(); - Assertions.assertEquals( - LocalDate.parse("2025-01-01"), - expiryDateField.getValue() - ); + Assertions.assertEquals(LocalDate.parse("2025-01-01"), expiryDateField.getValue()); } @Test @@ -157,92 +159,47 @@ void whenSyncCompleteDeserialized_mustHaveValidProperties() throws IOException { // Direct access to the hashmap GeneratedFeature customerName = features.get("customer_name"); Assertions.assertFalse(customerName.isList()); - Assertions.assertEquals( - "JIRO DOI", - customerName.get(0).get("value") - ); - Assertions.assertEquals( - "Jiro Doi", - customerName.get(0).get("raw_value") - ); - Assertions.assertEquals( - 0.87, - customerName.get(0).get("confidence") - ); - Assertions.assertEquals( - 1, - customerName.get(0).get("page_id") - ); - Assertions.assertEquals( - "Polygon with 4 points.", - customerName.get(0).getAsPolygon("polygon").toString() - ); + Assertions.assertEquals("JIRO DOI", customerName.get(0).get("value")); + Assertions.assertEquals("Jiro Doi", customerName.get(0).get("raw_value")); + Assertions.assertEquals(0.87, customerName.get(0).get("confidence")); + Assertions.assertEquals(1, customerName.get(0).get("page_id")); + Assertions + .assertEquals( + "Polygon with 4 points.", + customerName.get(0).getAsPolygon("polygon").toString() + ); // Access as a StringField with raw_value StringField customerNameField = customerName.asStringField(); - Assertions.assertEquals( - "JIRO DOI", - customerNameField.getValue() - ); - Assertions.assertEquals( - "Jiro Doi", - customerNameField.getRawValue() - ); - Assertions.assertEquals( - 0.87, - customerNameField.getConfidence() - ); - Assertions.assertEquals( - 1, - customerNameField.getPageId() - ); - Assertions.assertEquals( - "Polygon with 4 points.", - customerNameField.getPolygon().toString() - ); + Assertions.assertEquals("JIRO DOI", customerNameField.getValue()); + Assertions.assertEquals("Jiro Doi", customerNameField.getRawValue()); + Assertions.assertEquals(0.87, customerNameField.getConfidence()); + Assertions.assertEquals(1, customerNameField.getPageId()); + Assertions.assertEquals("Polygon with 4 points.", customerNameField.getPolygon().toString()); // Access as a StringField without raw_value StringField supplierAddressField = features.get("supplier_address").asStringField(); - Assertions.assertEquals( - "156 University Ave, Toronto ON, Canada M5H 2H7", - supplierAddressField.getValue() - ); - Assertions.assertNull( - supplierAddressField.getRawValue() - ); - Assertions.assertEquals( - 0.53, - supplierAddressField.getConfidence() - ); - Assertions.assertEquals( - 1, - supplierAddressField.getPageId() - ); - Assertions.assertEquals( - "Polygon with 4 points.", - supplierAddressField.getPolygon().toString() - ); + Assertions + .assertEquals( + "156 University Ave, Toronto ON, Canada M5H 2H7", + supplierAddressField.getValue() + ); + Assertions.assertNull(supplierAddressField.getRawValue()); + Assertions.assertEquals(0.53, supplierAddressField.getConfidence()); + Assertions.assertEquals(1, supplierAddressField.getPageId()); + Assertions.assertEquals("Polygon with 4 points.", supplierAddressField.getPolygon().toString()); // Access as an AmountField AmountField totalAmountField = features.get("total_amount").asAmountField(); - Assertions.assertEquals( - 587.95, - totalAmountField.getValue() - ); + Assertions.assertEquals(587.95, totalAmountField.getValue()); // Access as a DateField DateField dueDateField = features.get("due_date").asDateField(); - Assertions.assertEquals( - LocalDate.parse("2020-02-17"), - dueDateField.getValue() - ); + Assertions.assertEquals(LocalDate.parse("2020-02-17"), dueDateField.getValue()); // Access as a ClassificationField ClassificationField documentTypeField = features.get("document_type").asClassificationField(); - Assertions.assertEquals( - "INVOICE", - documentTypeField.getValue() - ); + Assertions.assertEquals("INVOICE", documentTypeField.getValue()); // Access line items GeneratedFeature lineItems = features.get("line_items"); @@ -268,8 +225,7 @@ void whenSyncEmptyDeserialized_mustHaveValidProperties() throws IOException { GeneratedFeature featureValue = featureEntry.getValue(); if (Objects.equals(featureEntry.getKey(), "document_type")) { Assertions.assertEquals("INVOICE", featureValue.get(0).get("value")); - } - else if (featureValue.isList()) { + } else if (featureValue.isList()) { Assertions.assertTrue(featureValue.isEmpty()); } else { Assertions.assertNull(featureValue.get(0).get("value")); diff --git a/src/test/java/com/mindee/product/ind/indianpassport/IndianPassportV1Test.java b/src/test/java/com/mindee/product/ind/indianpassport/IndianPassportV1Test.java index 63d180b8f..02c3b68d5 100644 --- a/src/test/java/com/mindee/product/ind/indianpassport/IndianPassportV1Test.java +++ b/src/test/java/com/mindee/product/ind/indianpassport/IndianPassportV1Test.java @@ -22,14 +22,14 @@ protected PredictResponse getPrediction(String name) throws IO ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - IndianPassportV1.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/ind_passport/response_v1/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, IndianPassportV1.class); + return objectMapper + .readValue( + new File(getV1ResourcePathString("products/ind_passport/response_v1/" + name + ".json")), + type + ); } @Test @@ -66,8 +66,8 @@ void whenCompleteDeserialized_mustHaveValidDocumentSummary() throws IOException PredictResponse response = getPrediction("complete"); Document doc = response.getDocument(); assertStringEqualsFile( - doc.toString(), - getV1ResourcePathString("products/ind_passport/response_v1/summary_full.rst") + doc.toString(), + getV1ResourcePathString("products/ind_passport/response_v1/summary_full.rst") ); } diff --git a/src/test/java/com/mindee/product/internationalid/InternationalIdV2Test.java b/src/test/java/com/mindee/product/internationalid/InternationalIdV2Test.java index 751de16da..5833c8d67 100644 --- a/src/test/java/com/mindee/product/internationalid/InternationalIdV2Test.java +++ b/src/test/java/com/mindee/product/internationalid/InternationalIdV2Test.java @@ -22,14 +22,16 @@ protected PredictResponse getPrediction(String name) throws I ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - InternationalIdV2.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/international_id/response_v2/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, InternationalIdV2.class); + return objectMapper + .readValue( + new File( + getV1ResourcePathString("products/international_id/response_v2/" + name + ".json") + ), + type + ); } @Test @@ -60,8 +62,8 @@ void whenCompleteDeserialized_mustHaveValidDocumentSummary() throws IOException PredictResponse response = getPrediction("complete"); Document doc = response.getDocument(); assertStringEqualsFile( - doc.toString(), - getV1ResourcePathString("products/international_id/response_v2/summary_full.rst") + doc.toString(), + getV1ResourcePathString("products/international_id/response_v2/summary_full.rst") ); } diff --git a/src/test/java/com/mindee/product/invoice/InvoiceV4Test.java b/src/test/java/com/mindee/product/invoice/InvoiceV4Test.java index 9cd811d06..9e4027f75 100644 --- a/src/test/java/com/mindee/product/invoice/InvoiceV4Test.java +++ b/src/test/java/com/mindee/product/invoice/InvoiceV4Test.java @@ -22,14 +22,14 @@ protected PredictResponse getPrediction(String name) throws IOExcepti ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - InvoiceV4.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/invoices/response_v4/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, InvoiceV4.class); + return objectMapper + .readValue( + new File(getV1ResourcePathString("products/invoices/response_v4/" + name + ".json")), + type + ); } @Test @@ -72,8 +72,8 @@ void whenCompleteDeserialized_mustHaveValidDocumentSummary() throws IOException PredictResponse response = getPrediction("complete"); Document doc = response.getDocument(); assertStringEqualsFile( - doc.toString(), - getV1ResourcePathString("products/invoices/response_v4/summary_full.rst") + doc.toString(), + getV1ResourcePathString("products/invoices/response_v4/summary_full.rst") ); } diff --git a/src/test/java/com/mindee/product/invoicesplitter/InvoiceSplitterV1Test.java b/src/test/java/com/mindee/product/invoicesplitter/InvoiceSplitterV1Test.java index efe8845fd..863f58dd8 100644 --- a/src/test/java/com/mindee/product/invoicesplitter/InvoiceSplitterV1Test.java +++ b/src/test/java/com/mindee/product/invoicesplitter/InvoiceSplitterV1Test.java @@ -21,14 +21,16 @@ protected PredictResponse getPrediction(String name) throws I ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - InvoiceSplitterV1.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/invoice_splitter/response_v1/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, InvoiceSplitterV1.class); + return objectMapper + .readValue( + new File( + getV1ResourcePathString("products/invoice_splitter/response_v1/" + name + ".json") + ), + type + ); } @Test @@ -43,8 +45,8 @@ void whenCompleteDeserialized_mustHaveValidDocumentSummary() throws IOException PredictResponse response = getPrediction("complete"); Document doc = response.getDocument(); assertStringEqualsFile( - doc.toString(), - getV1ResourcePathString("products/invoice_splitter/response_v1/summary_full.rst") + doc.toString(), + getV1ResourcePathString("products/invoice_splitter/response_v1/summary_full.rst") ); } diff --git a/src/test/java/com/mindee/product/multireceiptsdetector/MultiReceiptsDetectorV1Test.java b/src/test/java/com/mindee/product/multireceiptsdetector/MultiReceiptsDetectorV1Test.java index 69683e37c..d0aae9d78 100644 --- a/src/test/java/com/mindee/product/multireceiptsdetector/MultiReceiptsDetectorV1Test.java +++ b/src/test/java/com/mindee/product/multireceiptsdetector/MultiReceiptsDetectorV1Test.java @@ -21,20 +21,25 @@ protected PredictResponse getPrediction(String name) th ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - MultiReceiptsDetectorV1.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/multi_receipts_detector/response_v1/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, MultiReceiptsDetectorV1.class); + return objectMapper + .readValue( + new File( + getV1ResourcePathString("products/multi_receipts_detector/response_v1/" + name + ".json") + ), + type + ); } @Test void whenEmptyDeserialized_mustHaveValidProperties() throws IOException { PredictResponse response = getPrediction("empty"); - MultiReceiptsDetectorV1Document docPrediction = response.getDocument().getInference().getPrediction(); + MultiReceiptsDetectorV1Document docPrediction = response + .getDocument() + .getInference() + .getPrediction(); Assertions.assertTrue(docPrediction.getReceipts().isEmpty()); } @@ -43,8 +48,8 @@ void whenCompleteDeserialized_mustHaveValidDocumentSummary() throws IOException PredictResponse response = getPrediction("complete"); Document doc = response.getDocument(); assertStringEqualsFile( - doc.toString(), - getV1ResourcePathString("products/multi_receipts_detector/response_v1/summary_full.rst") + doc.toString(), + getV1ResourcePathString("products/multi_receipts_detector/response_v1/summary_full.rst") ); } diff --git a/src/test/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Test.java b/src/test/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Test.java index ffdd6e524..48eba9820 100644 --- a/src/test/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Test.java +++ b/src/test/java/com/mindee/product/nutritionfactslabel/NutritionFactsLabelV1Test.java @@ -21,20 +21,23 @@ protected PredictResponse getPrediction(String name) thro ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - NutritionFactsLabelV1.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/nutrition_facts/response_v1/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, NutritionFactsLabelV1.class); + return objectMapper + .readValue( + new File(getV1ResourcePathString("products/nutrition_facts/response_v1/" + name + ".json")), + type + ); } @Test void whenEmptyDeserialized_mustHaveValidProperties() throws IOException { PredictResponse response = getPrediction("empty"); - NutritionFactsLabelV1Document docPrediction = response.getDocument().getInference().getPrediction(); + NutritionFactsLabelV1Document docPrediction = response + .getDocument() + .getInference() + .getPrediction(); Assertions.assertNull(docPrediction.getServingPerBox().getValue()); Assertions.assertNull(docPrediction.getServingSize().getAmount()); Assertions.assertNull(docPrediction.getServingSize().getUnit()); @@ -80,8 +83,8 @@ void whenCompleteDeserialized_mustHaveValidDocumentSummary() throws IOException PredictResponse response = getPrediction("complete"); Document doc = response.getDocument(); assertStringEqualsFile( - doc.toString(), - getV1ResourcePathString("products/nutrition_facts/response_v1/summary_full.rst") + doc.toString(), + getV1ResourcePathString("products/nutrition_facts/response_v1/summary_full.rst") ); } diff --git a/src/test/java/com/mindee/product/passport/PassportV1Test.java b/src/test/java/com/mindee/product/passport/PassportV1Test.java index c641260e5..9ba9121fc 100644 --- a/src/test/java/com/mindee/product/passport/PassportV1Test.java +++ b/src/test/java/com/mindee/product/passport/PassportV1Test.java @@ -21,14 +21,14 @@ protected PredictResponse getPrediction(String name) throws IOExcept ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - PassportV1.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/passport/response_v1/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, PassportV1.class); + return objectMapper + .readValue( + new File(getV1ResourcePathString("products/passport/response_v1/" + name + ".json")), + type + ); } @Test @@ -53,8 +53,8 @@ void whenCompleteDeserialized_mustHaveValidDocumentSummary() throws IOException PredictResponse response = getPrediction("complete"); Document doc = response.getDocument(); assertStringEqualsFile( - doc.toString(), - getV1ResourcePathString("products/passport/response_v1/summary_full.rst") + doc.toString(), + getV1ResourcePathString("products/passport/response_v1/summary_full.rst") ); } diff --git a/src/test/java/com/mindee/product/receipt/ReceiptV5Test.java b/src/test/java/com/mindee/product/receipt/ReceiptV5Test.java index 2869317ca..fd1466201 100644 --- a/src/test/java/com/mindee/product/receipt/ReceiptV5Test.java +++ b/src/test/java/com/mindee/product/receipt/ReceiptV5Test.java @@ -22,14 +22,16 @@ protected PredictResponse getPrediction(String name) throws IOExcepti ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - ReceiptV5.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/expense_receipts/response_v5/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, ReceiptV5.class); + return objectMapper + .readValue( + new File( + getV1ResourcePathString("products/expense_receipts/response_v5/" + name + ".json") + ), + type + ); } @Test @@ -60,8 +62,8 @@ void whenCompleteDeserialized_mustHaveValidDocumentSummary() throws IOException PredictResponse response = getPrediction("complete"); Document doc = response.getDocument(); assertStringEqualsFile( - doc.toString(), - getV1ResourcePathString("products/expense_receipts/response_v5/summary_full.rst") + doc.toString(), + getV1ResourcePathString("products/expense_receipts/response_v5/summary_full.rst") ); } diff --git a/src/test/java/com/mindee/product/resume/ResumeV1Test.java b/src/test/java/com/mindee/product/resume/ResumeV1Test.java index 9dac190ea..9d5bdcb80 100644 --- a/src/test/java/com/mindee/product/resume/ResumeV1Test.java +++ b/src/test/java/com/mindee/product/resume/ResumeV1Test.java @@ -22,14 +22,14 @@ protected PredictResponse getPrediction(String name) throws IOExceptio ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - ResumeV1.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/resume/response_v1/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, ResumeV1.class); + return objectMapper + .readValue( + new File(getV1ResourcePathString("products/resume/response_v1/" + name + ".json")), + type + ); } @Test @@ -60,8 +60,8 @@ void whenCompleteDeserialized_mustHaveValidDocumentSummary() throws IOException PredictResponse response = getPrediction("complete"); Document doc = response.getDocument(); assertStringEqualsFile( - doc.toString(), - getV1ResourcePathString("products/resume/response_v1/summary_full.rst") + doc.toString(), + getV1ResourcePathString("products/resume/response_v1/summary_full.rst") ); } diff --git a/src/test/java/com/mindee/product/us/bankcheck/BankCheckV1Test.java b/src/test/java/com/mindee/product/us/bankcheck/BankCheckV1Test.java index 93886cfbf..ca8a28933 100644 --- a/src/test/java/com/mindee/product/us/bankcheck/BankCheckV1Test.java +++ b/src/test/java/com/mindee/product/us/bankcheck/BankCheckV1Test.java @@ -22,14 +22,14 @@ protected PredictResponse getPrediction(String name) throws IOExcep ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - BankCheckV1.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/bank_check/response_v1/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, BankCheckV1.class); + return objectMapper + .readValue( + new File(getV1ResourcePathString("products/bank_check/response_v1/" + name + ".json")), + type + ); } @Test @@ -42,7 +42,12 @@ void whenEmptyDeserialized_mustHaveValidProperties() throws IOException { Assertions.assertNull(docPrediction.getRoutingNumber().getValue()); Assertions.assertNull(docPrediction.getAccountNumber().getValue()); Assertions.assertNull(docPrediction.getCheckNumber().getValue()); - BankCheckV1Page pagePrediction = response.getDocument().getInference().getPages().get(0).getPrediction(); + BankCheckV1Page pagePrediction = response + .getDocument() + .getInference() + .getPages() + .get(0) + .getPrediction(); Assertions.assertEquals(pagePrediction.getCheckPosition().toString(), ""); Assertions.assertTrue(pagePrediction.getSignaturesPositions().isEmpty()); } @@ -52,8 +57,8 @@ void whenCompleteDeserialized_mustHaveValidDocumentSummary() throws IOException PredictResponse response = getPrediction("complete"); Document doc = response.getDocument(); assertStringEqualsFile( - doc.toString(), - getV1ResourcePathString("products/bank_check/response_v1/summary_full.rst") + doc.toString(), + getV1ResourcePathString("products/bank_check/response_v1/summary_full.rst") ); } @@ -62,8 +67,8 @@ void whenCompleteDeserialized_mustHaveValidPage0Summary() throws IOException { PredictResponse response = getPrediction("complete"); Page page = response.getDocument().getInference().getPages().get(0); assertStringEqualsFile( - page.toString(), - getV1ResourcePathString("products/bank_check/response_v1/summary_page0.rst") + page.toString(), + getV1ResourcePathString("products/bank_check/response_v1/summary_page0.rst") ); } } diff --git a/src/test/java/com/mindee/product/us/healthcarecard/HealthcareCardV1Test.java b/src/test/java/com/mindee/product/us/healthcarecard/HealthcareCardV1Test.java index 307d7e115..01332619e 100644 --- a/src/test/java/com/mindee/product/us/healthcarecard/HealthcareCardV1Test.java +++ b/src/test/java/com/mindee/product/us/healthcarecard/HealthcareCardV1Test.java @@ -21,14 +21,16 @@ protected PredictResponse getPrediction(String name) throws IO ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - HealthcareCardV1.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/us_healthcare_cards/response_v1/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, HealthcareCardV1.class); + return objectMapper + .readValue( + new File( + getV1ResourcePathString("products/us_healthcare_cards/response_v1/" + name + ".json") + ), + type + ); } @Test @@ -56,8 +58,8 @@ void whenCompleteDeserialized_mustHaveValidDocumentSummary() throws IOException PredictResponse response = getPrediction("complete"); Document doc = response.getDocument(); assertStringEqualsFile( - doc.toString(), - getV1ResourcePathString("products/us_healthcare_cards/response_v1/summary_full.rst") + doc.toString(), + getV1ResourcePathString("products/us_healthcare_cards/response_v1/summary_full.rst") ); } diff --git a/src/test/java/com/mindee/product/us/usmail/UsMailV3Test.java b/src/test/java/com/mindee/product/us/usmail/UsMailV3Test.java index 877bb100c..1c1c947d3 100644 --- a/src/test/java/com/mindee/product/us/usmail/UsMailV3Test.java +++ b/src/test/java/com/mindee/product/us/usmail/UsMailV3Test.java @@ -21,14 +21,14 @@ protected PredictResponse getPrediction(String name) throws IOExceptio ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - JavaType type = objectMapper.getTypeFactory().constructParametricType( - PredictResponse.class, - UsMailV3.class - ); - return objectMapper.readValue( - new File(getV1ResourcePathString("products/us_mail/response_v3/" + name + ".json")), - type - ); + JavaType type = objectMapper + .getTypeFactory() + .constructParametricType(PredictResponse.class, UsMailV3.class); + return objectMapper + .readValue( + new File(getV1ResourcePathString("products/us_mail/response_v3/" + name + ".json")), + type + ); } @Test @@ -51,8 +51,8 @@ void whenCompleteDeserialized_mustHaveValidDocumentSummary() throws IOException PredictResponse response = getPrediction("complete"); Document doc = response.getDocument(); assertStringEqualsFile( - doc.toString(), - getV1ResourcePathString("products/us_mail/response_v3/summary_full.rst") + doc.toString(), + getV1ResourcePathString("products/us_mail/response_v3/summary_full.rst") ); } diff --git a/src/test/java/com/mindee/workflow/WorkflowIT.java b/src/test/java/com/mindee/workflow/WorkflowIT.java index aa36488a7..323dde272 100644 --- a/src/test/java/com/mindee/workflow/WorkflowIT.java +++ b/src/test/java/com/mindee/workflow/WorkflowIT.java @@ -33,46 +33,51 @@ static void clientSetUp() throws IOException { client = new MindeeClient(); workflowId = System.getenv("WORKFLOW_ID"); financialDocumentInputSource = new LocalInputSource( - getV1ResourcePath("products/financial_document/default_sample.jpg") + getV1ResourcePath("products/financial_document/default_sample.jpg") ); } @Test - public void givenAWorkflowIdUploadShouldReturnACorrectWorkflowObject() throws - IOException { + public void givenAWorkflowIdUploadShouldReturnACorrectWorkflowObject() throws IOException { - WorkflowOptions options = WorkflowOptions.builder().alias("java-" + currentDateTime).priority( - ExecutionPriority.LOW).rag(true).build(); - WorkflowResponse response = - client.executeWorkflow(workflowId, financialDocumentInputSource, options); + WorkflowOptions options = WorkflowOptions + .builder() + .alias("java-" + currentDateTime) + .priority(ExecutionPriority.LOW) + .rag(true) + .build(); + WorkflowResponse response = client + .executeWorkflow(workflowId, financialDocumentInputSource, options); Execution execution = response.getExecution(); Assertions.assertEquals("low", execution.getPriority()); Assertions.assertEquals("java-" + currentDateTime, execution.getFile().getAlias()); } @Test - public void GivenAWorkflowIdPredictCustomShouldPollAndNotMatchRag() throws - IOException, InterruptedException { + public void GivenAWorkflowIdPredictCustomShouldPollAndNotMatchRag() throws IOException, InterruptedException { PredictOptions predictOptions = PredictOptions.builder().workflowId(workflowId).build(); - AsyncPredictResponse response = client.enqueueAndParse( - FinancialDocumentV1.class, financialDocumentInputSource, predictOptions); + AsyncPredictResponse response = client + .enqueueAndParse(FinancialDocumentV1.class, financialDocumentInputSource, predictOptions); Assertions.assertNotNull(response.getDocumentObj().toString()); - Assertions.assertNull( - response.getDocumentObj().getInference().getExtras().getRag()); + Assertions.assertNull(response.getDocumentObj().getInference().getExtras().getRag()); } @Test - public void GivenAWorkflowIdPredictCustomShouldPollAndMatchRag() throws - IOException, InterruptedException { + public void GivenAWorkflowIdPredictCustomShouldPollAndMatchRag() throws IOException, InterruptedException { - PredictOptions predictOptions = PredictOptions.builder().workflowId(workflowId).rag(true).build(); - AsyncPredictResponse response = client.enqueueAndParse( - FinancialDocumentV1.class, financialDocumentInputSource, predictOptions); + PredictOptions predictOptions = PredictOptions + .builder() + .workflowId(workflowId) + .rag(true) + .build(); + AsyncPredictResponse response = client + .enqueueAndParse(FinancialDocumentV1.class, financialDocumentInputSource, predictOptions); Assertions.assertNotNull(response.getDocumentObj().toString()); - Assertions.assertNotNull( - response.getDocumentObj().getInference().getExtras().getRag()); - Assertions.assertNotNull( - response.getDocumentObj().getInference().getExtras().getRag().getMatchingDocumentId()); + Assertions.assertNotNull(response.getDocumentObj().getInference().getExtras().getRag()); + Assertions + .assertNotNull( + response.getDocumentObj().getInference().getExtras().getRag().getMatchingDocumentId() + ); } } diff --git a/src/test/java/com/mindee/workflow/WorkflowTest.java b/src/test/java/com/mindee/workflow/WorkflowTest.java index 8719c8048..cba596487 100644 --- a/src/test/java/com/mindee/workflow/WorkflowTest.java +++ b/src/test/java/com/mindee/workflow/WorkflowTest.java @@ -43,49 +43,40 @@ public void setUp() { } @Test - void givenAWorkflowMockFileShouldReturnAValidWorkflowObject() - throws IOException { + void givenAWorkflowMockFileShouldReturnAValidWorkflowObject() throws IOException { WorkflowResponse workflowResponse = new WorkflowResponse(); workflowResponse.setExecution(new Execution()); workflowResponse.setApiRequest(null); - when( - mindeeApi.executeWorkflowPost( - Mockito.any(), - Mockito.any(), - Mockito.any() - )) - .thenReturn(workflowResponse); - - WorkflowResponse execution = client.executeWorkflow( - "", - new LocalInputSource(getResourcePath("file_types/pdf/blank_1.pdf")) - ); + when(mindeeApi.executeWorkflowPost(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(workflowResponse); + + WorkflowResponse execution = client + .executeWorkflow("", new LocalInputSource(getResourcePath("file_types/pdf/blank_1.pdf"))); Assertions.assertNotNull(execution); - Mockito.verify(mindeeApi, Mockito.times(1)) - .executeWorkflowPost(Mockito.any(), Mockito.any(), Mockito.any()); + Mockito + .verify(mindeeApi, Mockito.times(1)) + .executeWorkflowPost(Mockito.any(), Mockito.any(), Mockito.any()); } @Test void sendingADocumentToAnExecutionShouldDeserializeResponseCorrectly() throws IOException { - WorkflowResponse.Default mockResponse = objectMapper.readValue( + WorkflowResponse.Default mockResponse = objectMapper + .readValue( getV1ResourcePath("workflows/success.json").toFile(), WorkflowResponse.Default.class - ); + ); - when(mockedClient.executeWorkflow(Mockito.anyString(), - Mockito.any(LocalInputSource.class) - )) - .thenReturn(mockResponse); + when(mockedClient.executeWorkflow(Mockito.anyString(), Mockito.any(LocalInputSource.class))) + .thenReturn(mockResponse); String workflowId = "07ebf237-ff27-4eee-b6a2-425df4a5cca6"; LocalInputSource inputSource = new LocalInputSource( - getV1ResourcePath("products/financial_document/default_sample.jpg") + getV1ResourcePath("products/financial_document/default_sample.jpg") ); - WorkflowResponse response = - mockedClient.executeWorkflow(workflowId, inputSource); + WorkflowResponse response = mockedClient.executeWorkflow(workflowId, inputSource); Assertions.assertNotNull(response); Assertions.assertNotNull(response.getApiRequest()); @@ -93,65 +84,63 @@ void sendingADocumentToAnExecutionShouldDeserializeResponseCorrectly() throws IO Assertions.assertNull(response.getExecution().getCreatedAt()); Assertions.assertNull(response.getExecution().getFile().getAlias()); Assertions.assertEquals("default_sample.jpg", response.getExecution().getFile().getName()); - Assertions.assertEquals( - "8c75c035-e083-4e77-ba3b-7c3598bd1d8a", response.getExecution().getId()); + Assertions + .assertEquals("8c75c035-e083-4e77-ba3b-7c3598bd1d8a", response.getExecution().getId()); Assertions.assertNull(response.getExecution().getInference()); Assertions.assertEquals("medium", response.getExecution().getPriority()); Assertions.assertNull(response.getExecution().getReviewedAt()); Assertions.assertNull(response.getExecution().getReviewedPrediction()); Assertions.assertEquals("processing", response.getExecution().getStatus()); Assertions.assertEquals("manual", response.getExecution().getType()); - Assertions.assertEquals( - "2024-11-13T13:02:31.699190", response.getExecution().getUploadedAt().toString()); - Assertions.assertEquals( - workflowId, response.getExecution().getWorkflowId()); + Assertions + .assertEquals( + "2024-11-13T13:02:31.699190", + response.getExecution().getUploadedAt().toString() + ); + Assertions.assertEquals(workflowId, response.getExecution().getWorkflowId()); Mockito.verify(mockedClient).executeWorkflow(workflowId, inputSource); } - @Test - void sendingADocumentToAnExecutionWithPriorityAndAliasShouldDeserializeResponseCorrectly() - throws IOException { - WorkflowResponse.Default mockResponse = objectMapper.readValue( + void sendingADocumentToAnExecutionWithPriorityAndAliasShouldDeserializeResponseCorrectly() throws IOException { + WorkflowResponse.Default mockResponse = objectMapper + .readValue( getV1ResourcePath("workflows/success_low_priority.json").toFile(), WorkflowResponse.Default.class - ); + ); - when(mockedClient.executeWorkflow(Mockito.anyString(), - Mockito.any(LocalInputSource.class) - )) - .thenReturn(mockResponse); + when(mockedClient.executeWorkflow(Mockito.anyString(), Mockito.any(LocalInputSource.class))) + .thenReturn(mockResponse); String workflowId = "07ebf237-ff27-4eee-b6a2-425df4a5cca6"; LocalInputSource inputSource = new LocalInputSource( - getV1ResourcePath("products/financial_document/default_sample.jpg") + getV1ResourcePath("products/financial_document/default_sample.jpg") ); - WorkflowResponse response = - mockedClient.executeWorkflow(workflowId, inputSource); + WorkflowResponse response = mockedClient.executeWorkflow(workflowId, inputSource); Assertions.assertNotNull(response); Assertions.assertNotNull(response.getApiRequest()); Assertions.assertNull(response.getExecution().getBatchName()); Assertions.assertNull(response.getExecution().getCreatedAt()); - Assertions.assertEquals( - "low-priority-sample-test", response.getExecution().getFile().getAlias() - ); + Assertions + .assertEquals("low-priority-sample-test", response.getExecution().getFile().getAlias()); Assertions.assertEquals("default_sample.jpg", response.getExecution().getFile().getName()); - Assertions.assertEquals( - "b743e123-e18c-4b62-8a07-811a4f72afd3", response.getExecution().getId() - ); + Assertions + .assertEquals("b743e123-e18c-4b62-8a07-811a4f72afd3", response.getExecution().getId()); Assertions.assertNull(response.getExecution().getInference()); Assertions.assertEquals("low", response.getExecution().getPriority()); Assertions.assertNull(response.getExecution().getReviewedAt()); Assertions.assertNull(response.getExecution().getReviewedPrediction()); Assertions.assertEquals("processing", response.getExecution().getStatus()); Assertions.assertEquals("manual", response.getExecution().getType()); - Assertions.assertEquals( - "2024-11-13T13:17:01.315179", response.getExecution().getUploadedAt().toString()); - Assertions.assertEquals( - workflowId, response.getExecution().getWorkflowId()); + Assertions + .assertEquals( + "2024-11-13T13:17:01.315179", + response.getExecution().getUploadedAt().toString() + ); + Assertions.assertEquals(workflowId, response.getExecution().getWorkflowId()); Mockito.verify(mockedClient).executeWorkflow(workflowId, inputSource); }