From 6aac4b09058f151c7d2a18654565239ef332869a Mon Sep 17 00:00:00 2001 From: "Breno A." Date: Sat, 20 Jul 2024 18:16:03 -0300 Subject: [PATCH] refactor: code cleanup --- docs/content/_index.md | 14 +- docs/content/classes/CnpjValidator.md | 32 +- docs/content/classes/CpfValidator.md | 16 +- docs/content/classes/CreditCardValidator.md | 38 +- docs/content/classes/Utils.md | 24 +- docs/content/classes/Validate.md | 67 +- docs/content/classes/Validator.md | 23 +- pom.xml | 192 +++--- .../multiform_validator/CnpjValidator.java | 91 --- .../multiform_validator/CpfValidator.java | 51 -- .../CreditCardValidator.java | 95 --- .../multiform_validator/FileValidator.java | 275 -------- .../io/github/multiform_validator/Main.java | 37 +- .../io/github/multiform_validator/Utils.java | 135 ---- .../github/multiform_validator/Validate.java | 153 ----- .../github/multiform_validator/Validator.java | 399 ------------ .../file/AudioValidator.java | 98 +++ .../file/FileValidator.java | 82 +++ .../file/ImageValidator.java | 117 ++++ .../format/DateValidator.java | 96 +++ .../format/EmailValidator.java | 132 ++++ .../format/StringValidator.java | 53 ++ .../format/email/EmailDelegate.java | 151 +++++ .../format/email/OnlyEmailParams.java | 23 + .../format/email/ValidateEmailBuilder.java | 25 + .../identity/AddressValidator.java | 72 ++ .../identity/CnpjValidator.java | 86 +++ .../identity/CpfValidator.java | 63 ++ .../identity/CreditCardValidator.java | 89 +++ .../numeric/MachineValidator.java | 52 ++ .../numeric/NumberValidator.java | 28 + .../multiform_validator/utils/FileUtils.java | 33 + .../utils/NumberUtils.java | 27 + src/test/java/AudioValidatorTest.java | 74 +++ src/test/java/CnpjValidatorTest.java | 105 +-- src/test/java/CpfValidatorTest.java | 114 ++-- src/test/java/CreditCardValidatorTest.java | 84 +-- src/test/java/EmailValidatorTest.java | 63 ++ src/test/java/FileValidatorTest.java | 228 ------- src/test/java/ImageValidatorTest.java | 94 +++ src/test/java/PDFValidatorTest.java | 35 + src/test/java/TextValidatorTest.java | 35 + src/test/java/UtilsTest.java | 130 ++-- src/test/java/ValidateTest.java | 66 -- src/test/java/ValidatorTest.java | 614 ++++++++---------- 45 files changed, 2254 insertions(+), 2257 deletions(-) delete mode 100644 src/main/java/io/github/multiform_validator/CnpjValidator.java delete mode 100644 src/main/java/io/github/multiform_validator/CpfValidator.java delete mode 100644 src/main/java/io/github/multiform_validator/CreditCardValidator.java delete mode 100644 src/main/java/io/github/multiform_validator/FileValidator.java delete mode 100644 src/main/java/io/github/multiform_validator/Utils.java delete mode 100644 src/main/java/io/github/multiform_validator/Validate.java delete mode 100644 src/main/java/io/github/multiform_validator/Validator.java create mode 100644 src/main/java/io/github/multiform_validator/file/AudioValidator.java create mode 100644 src/main/java/io/github/multiform_validator/file/FileValidator.java create mode 100644 src/main/java/io/github/multiform_validator/file/ImageValidator.java create mode 100644 src/main/java/io/github/multiform_validator/format/DateValidator.java create mode 100644 src/main/java/io/github/multiform_validator/format/EmailValidator.java create mode 100644 src/main/java/io/github/multiform_validator/format/StringValidator.java create mode 100644 src/main/java/io/github/multiform_validator/format/email/EmailDelegate.java create mode 100644 src/main/java/io/github/multiform_validator/format/email/OnlyEmailParams.java create mode 100644 src/main/java/io/github/multiform_validator/format/email/ValidateEmailBuilder.java create mode 100644 src/main/java/io/github/multiform_validator/identity/AddressValidator.java create mode 100644 src/main/java/io/github/multiform_validator/identity/CnpjValidator.java create mode 100644 src/main/java/io/github/multiform_validator/identity/CpfValidator.java create mode 100644 src/main/java/io/github/multiform_validator/identity/CreditCardValidator.java create mode 100644 src/main/java/io/github/multiform_validator/numeric/MachineValidator.java create mode 100644 src/main/java/io/github/multiform_validator/numeric/NumberValidator.java create mode 100644 src/main/java/io/github/multiform_validator/utils/FileUtils.java create mode 100644 src/main/java/io/github/multiform_validator/utils/NumberUtils.java create mode 100644 src/test/java/AudioValidatorTest.java create mode 100644 src/test/java/EmailValidatorTest.java delete mode 100644 src/test/java/FileValidatorTest.java create mode 100644 src/test/java/ImageValidatorTest.java create mode 100644 src/test/java/PDFValidatorTest.java create mode 100644 src/test/java/TextValidatorTest.java delete mode 100644 src/test/java/ValidateTest.java diff --git a/docs/content/_index.md b/docs/content/_index.md index 7cdf7d3..50b5aed 100644 --- a/docs/content/_index.md +++ b/docs/content/_index.md @@ -135,14 +135,14 @@ Step 2. Add the dependency ```java // You can import the class or use the full path -import io.github.multiform_validator.CnpjValidator; +import io.github.multiform_validator.identity.CnpjValidator; public class Main { - public static void main(String[] args) { - String cnpjTrue = "69.807.668/0001-41"; - String cnpjFalse = "61.807.661/0001-48"; - System.out.println(CnpjValidator.cnpjIsValid(cnpjTrue)); // true - System.out.println(CnpjValidator.cnpjIsValid(cnpjFalse)); // false - } + public static void main(String[] args) { + String cnpjTrue = "69.807.668/0001-41"; + String cnpjFalse = "61.807.661/0001-48"; + System.out.println(CnpjValidator.cnpjIsValid(cnpjTrue)); // true + System.out.println(CnpjValidator.cnpjIsValid(cnpjFalse)); // false + } } ``` diff --git a/docs/content/classes/CnpjValidator.md b/docs/content/classes/CnpjValidator.md index c2db777..eda8f81 100644 --- a/docs/content/classes/CnpjValidator.md +++ b/docs/content/classes/CnpjValidator.md @@ -6,23 +6,23 @@ a `String` as a parameter and returns a `boolean` value. ```java // You can import the class or use the full path -import io.github.multiform_validator.CnpjValidator; +import io.github.multiform_validator.identity.CnpjValidator; public class Main { - public static void main(String[] args) { - System.out.println(cnpjIsTrue()); // true - System.out.println(cnpjIsFalse()); // false - } - - public static boolean cnpjIsTrue() { - String cnpjTrue = "69.807.668/0001-41"; - return CnpjValidator.cnpjIsValid(cnpjTrue); - } - - public static boolean cnpjIsFalse() { - String cnpjFalse = "61.807.661/0001-48"; - return CnpjValidator.cnpjIsValid(cnpjFalse); - } + public static void main(String[] args) { + System.out.println(cnpjIsTrue()); // true + System.out.println(cnpjIsFalse()); // false + } + + public static boolean cnpjIsTrue() { + String cnpjTrue = "69.807.668/0001-41"; + return CnpjValidator.cnpjIsValid(cnpjTrue); + } + + public static boolean cnpjIsFalse() { + String cnpjFalse = "61.807.661/0001-48"; + return CnpjValidator.cnpjIsValid(cnpjFalse); + } } ``` @@ -33,4 +33,4 @@ public class Main { - [FileValidator](https://multiform-validator.github.io/java/classes/FileValidator) - [Utils](https://multiform-validator.github.io/java/classes/Utils) - [Validate](https://multiform-validator.github.io/java/classes/Validate) -- [Validator](https://multiform-validator.github.io/java/classes/Validator) \ No newline at end of file +- [Validator](https://multiform-validator.github.io/java/classes/Validator) diff --git a/docs/content/classes/CpfValidator.md b/docs/content/classes/CpfValidator.md index 433098d..9365870 100644 --- a/docs/content/classes/CpfValidator.md +++ b/docs/content/classes/CpfValidator.md @@ -6,15 +6,15 @@ a `String` as a parameter and returns a `boolean` value. ```java // You can also import the method as static or use the full path -import static io.github.multiform_validator.CpfValidator.cpfIsValid; +import static io.github.multiform_validator.identity.CpfValidator.cpfIsValid; public class Main { - public static void main(String[] args) { - String cpfTrue = "123.456.789-09"; - String cpfFalse = "123.456.789-10"; - System.out.println(cpfIsValid(cpfTrue)); // true - System.out.println(cpfIsValid(cpfFalse)); // false - } + public static void main(String[] args) { + String cpfTrue = "123.456.789-09"; + String cpfFalse = "123.456.789-10"; + System.out.println(cpfIsValid(cpfTrue)); // true + System.out.println(cpfIsValid(cpfFalse)); // false + } } ``` @@ -25,4 +25,4 @@ public class Main { - [FileValidator](https://multiform-validator.github.io/java/classes/FileValidator) - [Utils](https://multiform-validator.github.io/java/classes/Utils) - [Validate](https://multiform-validator.github.io/java/classes/Validate) -- [Validator](https://multiform-validator.github.io/java/classes/Validator) \ No newline at end of file +- [Validator](https://multiform-validator.github.io/java/classes/Validator) diff --git a/docs/content/classes/CreditCardValidator.md b/docs/content/classes/CreditCardValidator.md index 1f59424..2941290 100644 --- a/docs/content/classes/CreditCardValidator.md +++ b/docs/content/classes/CreditCardValidator.md @@ -6,34 +6,34 @@ and `identifyCreditCard`. ### isCreditCardValid ```java -import io.github.multiform_validator.CreditCardValidator; +import io.github.multiform_validator.identity.CreditCardValidator; public class Main { - public static void main(String[] args) { - valid(); - invalid(); - } - - private static void valid() { - System.out.println(CreditCardValidator.isCreditCardValid("4532 8770 0040 4166")); // true - } - - private static void invalid() { - System.out.println(CreditCardValidator.isCreditCardValid("4532 8770 0040 4167")); // false - } + public static void main(String[] args) { + valid(); + invalid(); + } + + private static void valid() { + System.out.println(CreditCardValidator.isCreditCardValid("4532 8770 0040 4166")); // true + } + + private static void invalid() { + System.out.println(CreditCardValidator.isCreditCardValid("4532 8770 0040 4167")); // false + } } ``` ### identifyCreditCard ```java -import io.github.multiform_validator.CreditCardValidator; +import io.github.multiform_validator.identity.CreditCardValidator; public class Main { - public static void main(String[] args) { - String creditCard = "4532 8770 0040 4166"; - System.out.println(CreditCardValidator.identifyCreditCard(creditCard)); // Visa - } + public static void main(String[] args) { + String creditCard = "4532 8770 0040 4166"; + System.out.println(CreditCardValidator.identifyCreditCard(creditCard)); // Visa + } } ``` @@ -44,4 +44,4 @@ public class Main { - [FileValidator](https://multiform-validator.github.io/java/classes/FileValidator) - [Utils](https://multiform-validator.github.io/java/classes/Utils) - [Validate](https://multiform-validator.github.io/java/classes/Validate) -- [Validator](https://multiform-validator.github.io/java/classes/Validator) \ No newline at end of file +- [Validator](https://multiform-validator.github.io/java/classes/Validator) diff --git a/docs/content/classes/Utils.md b/docs/content/classes/Utils.md index 6533d97..0c6e804 100644 --- a/docs/content/classes/Utils.md +++ b/docs/content/classes/Utils.md @@ -13,19 +13,19 @@ methods: ### getOnlyEmail ```java -import io.github.multiform_validator.Utils; + public class Main { - public static void main(String[] args) { - String msg1 = "This is a message example with foo@bar.com email to test"; - System.out.println(Utils.getOnlyEmail(msg1, null)); // foo@bar.com - - String msg2 = "Example two foo1@bar.com and foo2@bar.com"; - // With options - Utils.GetOnlyEmailOptionsParams options = new Utils.GetOnlyEmailOptionsParams(); - options.setMultiple(true); - System.out.println(Utils.getOnlyEmailWithOptions(msg2, options)); // [foo1@bar.com, foo2@bar.com] - } + public static void main(String[] args) { + String msg1 = "This is a message example with foo@bar.com email to test"; + System.out.println(Utils.getOnlyEmail(msg1, null)); // foo@bar.com + + String msg2 = "Example two foo1@bar.com and foo2@bar.com"; + // With options + Utils.OnlyEmailParams options = new Utils.OnlyEmailParams(); + options.setMultiple(true); + System.out.println(Utils.getOnlyEmailWithOptions(msg2, options)); // [foo1@bar.com, foo2@bar.com] + } } ``` @@ -36,4 +36,4 @@ public class Main { - [CreditCardValidator](https://multiform-validator.github.io/java/classes/CreditCardValidator) - [FileValidator](https://multiform-validator.github.io/java/classes/FileValidator) - [Validate](https://multiform-validator.github.io/java/classes/Validate) -- [Validator](https://multiform-validator.github.io/java/classes/Validator) \ No newline at end of file +- [Validator](https://multiform-validator.github.io/java/classes/Validator) diff --git a/docs/content/classes/Validate.md b/docs/content/classes/Validate.md index 433b093..4bd6526 100644 --- a/docs/content/classes/Validate.md +++ b/docs/content/classes/Validate.md @@ -23,49 +23,48 @@ The `Validate` class is a utility class with some methods to validate data. It h ### validateEmail ```java -import io.github.multiform_validator.Validate; -import io.github.multiform_validator.Validate.ValidateEmailOptionsParams; +import io.github.multiform_validator.format.EmailValidator; import java.util.Collections; public class Main { - public static void main(String[] args) { - validateEmailExample(); - } + public static void main(String[] args) { + validateEmailExample(); + } - public static void validateEmailExample() { - // IMPORTANT: validDomains can not be used with validDomainsList, you can use only one of them + public static void validateEmailExample() { + // IMPORTANT: validDomains can not be used with validDomainsList, you can use only one of them - // Basic email validation - boolean isValid = Validate.validateEmail("example@example.com"); - System.out.println("Is valid: " + isValid); // Expected: true + // Basic email validation + boolean isValid = EmailValidator.validateEmail("example@example.com"); + System.out.println("Is valid: " + isValid); // Expected: true - // Email validation with options: maxLength - ValidateEmailOptionsParams optionsMaxLength = new ValidateEmailOptionsParams(); - optionsMaxLength.setMaxLength(10); // Setting max length to 10, which should fail for longer emails - boolean isValidMaxLength = Validate.validateEmail("longemail@example.com", optionsMaxLength); - System.out.println("Is valid with maxLength: " + isValidMaxLength); // Expected: false + // Email validation with options: maxLength + EmailParams optionsMaxLength = new EmailValidator.EmailParams(); + optionsMaxLength.setMaxLength(10); // Setting max length to 10, which should fail for longer emails + boolean isValidMaxLength = EmailValidator.validateEmail("longemail@example.com", optionsMaxLength); + System.out.println("Is valid with maxLength: " + isValidMaxLength); // Expected: false - // Email validation with options: country specific - ValidateEmailOptionsParams optionsCountry = new ValidateEmailOptionsParams(); - optionsCountry.setCountry("us"); // Expecting an email from the US - boolean isNotValidCountry = Validate.validateEmail("example@domain.com", optionsCountry); - boolean isValidCountry = Validate.validateEmail("example@domain.com.us", optionsCountry); - System.out.println("Is not valid with country: " + isNotValidCountry); // Expected: false - System.out.println("Is valid with country: " + isValidCountry); // Expected: true + // Email validation with options: country specific + EmailParams optionsCountry = new EmailParams(); + optionsCountry.setCountry("us"); // Expecting an email from the US + boolean isNotValidCountry = EmailValidator.validateEmail("example@domain.com", optionsCountry); + boolean isValidCountry = EmailValidator.validateEmail("example@domain.com.us", optionsCountry); + System.out.println("Is not valid with country: " + isNotValidCountry); // Expected: false + System.out.println("Is valid with country: " + isValidCountry); // Expected: true - // Email validation with options: validDomains - ValidateEmailOptionsParams optionsValidDomains = new ValidateEmailOptionsParams(); - optionsValidDomains.setValidDomains(true); // Only allow certain domains (implementation specific) - boolean isValidValidDomains = Validate.validateEmail("example@gmail.com", optionsValidDomains); - System.out.println("Is valid with validDomains: " + isValidValidDomains); // Expected: true + // Email validation with options: validDomains + EmailParams optionsValidDomains = new EmailParams(); + optionsValidDomains.setValidDomains(true); // Only allow certain domains (implementation specific) + boolean isValidValidDomains = EmailValidator.validateEmail("example@gmail.com", optionsValidDomains); + System.out.println("Is valid with validDomains: " + isValidValidDomains); // Expected: true - // Email validation with options: validDomainsList - ValidateEmailOptionsParams optionsValidDomainsList = new ValidateEmailOptionsParams(); - optionsValidDomainsList.setValidDomainsList(Collections.singletonList("specificdomain.com")); // Adding a specific domain to the list - boolean isValidValidDomainsList = Validate.validateEmail("example@specificdomain.com", optionsValidDomainsList); - System.out.println("Is valid with validDomainsList: " + isValidValidDomainsList); // Expected: true - } + // Email validation with options: validDomainsList + EmailValidator.EmailParams optionsValidDomainsList = new EmailValidator.EmailParams(); + optionsValidDomainsList.setValidDomainsList(Collections.singletonList("specificdomain.com")); // Adding a specific domain to the list + boolean isValidValidDomainsList = EmailValidator.validateEmail("example@specificdomain.com", optionsValidDomainsList); + System.out.println("Is valid with validDomainsList: " + isValidValidDomainsList); // Expected: true + } } ``` @@ -76,4 +75,4 @@ public class Main { - [CreditCardValidator](https://multiform-validator.github.io/java/classes/CreditCardValidator) - [FileValidator](https://multiform-validator.github.io/java/classes/FileValidator) - [Utils](https://multiform-validator.github.io/java/classes/Utils) -- [Validator](https://multiform-validator.github.io/java/classes/Validator) \ No newline at end of file +- [Validator](https://multiform-validator.github.io/java/classes/Validator) diff --git a/docs/content/classes/Validator.md b/docs/content/classes/Validator.md index f422605..7f552e7 100644 --- a/docs/content/classes/Validator.md +++ b/docs/content/classes/Validator.md @@ -160,27 +160,6 @@ public class Main { } ``` -### isNumber - -```java -import static io.github.multiform_validator.Validator.isNumber; - -public class Main { - public static void main(String[] args) { - valid(); - invalid(); - } - - private static void valid() { - System.out.println(isNumber("123")); // true - } - - private static void invalid() { - System.out.println(isNumber("123a")); // false - } -} -``` - ### isPort ```java @@ -263,4 +242,4 @@ public class Main { - [CreditCardValidator](https://multiform-validator.github.io/java/classes/CreditCardValidator) - [FileValidator](https://multiform-validator.github.io/java/classes/FileValidator) - [Utils](https://multiform-validator.github.io/java/classes/Utils) -- [Validate](https://multiform-validator.github.io/java/classes/Validate) \ No newline at end of file +- [Validate](https://multiform-validator.github.io/java/classes/Validate) diff --git a/pom.xml b/pom.xml index 326823e..da0bda9 100644 --- a/pom.xml +++ b/pom.xml @@ -2,96 +2,122 @@ - 4.0.0 + 4.0.0 - io.github - multiform-validator - 0.0.5 + io.github + multiform-validator + 0.0.5 - Multiform Validator - - Multilingual library made for validation, various form fields, such as: email, cpf, cnpj, credit card and much + Multiform Validator + + Multilingual library made for validation, various form fields, such as: email, cpf, cnpj, credit card and much more. - https://github.com/Multiform-Validator/java/ - - - Apache License 2.0 - https://github.com/Multiform-Validator/java/blob/main/LICENSE - - - - - Gabriel Logan - - + https://github.com/Multiform-Validator/java/ + + + Apache License 2.0 + https://github.com/Multiform-Validator/java/blob/main/LICENSE + + + + + Gabriel Logan + + - - 1.8 - 1.8 - UTF-8 - + + + github + GitHub multiform-validator Apache Maven Packages + https://maven.pkg.github.com/multiform-validator/java + + - - - org.jetbrains - annotations - 24.1.0 - compile - + + 1.8 + 1.8 + UTF-8 + - - - org.junit.jupiter - junit-jupiter-api - 5.7.0 - test - - - - org.junit.jupiter - junit-jupiter-engine - 5.7.0 - test - - + + + org.jetbrains + annotations + 24.1.0 + compile + - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.2 - - - **/*Test.java - **/*Tests.java - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 3.7.0 - - - attach-javadocs - package - - jar - - - - - - + + org.projectlombok + lombok + 1.18.34 + provided + - - - github - GitHub multiform-validator Apache Maven Packages - https://maven.pkg.github.com/multiform-validator/java - - + + + org.junit.jupiter + junit-jupiter-api + 5.10.3 + test + + + + org.junit.jupiter + junit-jupiter-engine + 5.10.3 + test + + + + + maven_central + Maven Central + https://repo.maven.apache.org/maven2/ + + - \ No newline at end of file + + + + com.spotify.fmt + fmt-maven-plugin + 2.23 + + + + format + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.2 + + + **/*Test.java + **/*Tests.java + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.7.0 + + + attach-javadocs + package + + jar + + + + + + + + diff --git a/src/main/java/io/github/multiform_validator/CnpjValidator.java b/src/main/java/io/github/multiform_validator/CnpjValidator.java deleted file mode 100644 index 3fd39dc..0000000 --- a/src/main/java/io/github/multiform_validator/CnpjValidator.java +++ /dev/null @@ -1,91 +0,0 @@ -package io.github.multiform_validator; - -import java.util.Arrays; - -public class CnpjValidator { - // Prevent instantiation - private CnpjValidator() { - throw new IllegalStateException("Utility class"); - } - - /** - * Calculate the first verifier digit of a CNPJ - * - * @param cnpjBase an array of integers with the first 12 digits of a CNPJ - * @return the first verifier digit - */ - private static int calculateFirstVerifier(int[] cnpjBase) { - final int[] weight = {5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2}; - int sum = 0; - - for (int i = 0; i < 12; i++) { - sum += cnpjBase[i] * weight[i]; - } - final int remainder = sum % 11; - - return remainder < 2 ? 0 : 11 - remainder; - } - - /** - * Calculate the second verifier digit of a CNPJ - * - * @param cnpjBase an array of integers with the first 12 digits of a CNPJ - * @param firstVerifier the first verifier digit - * @return the second verifier digit - */ - private static int calculateSecondVerifier(int[] cnpjBase, int firstVerifier) { - final int[] weight = {6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2}; - int sum = 0; - - for (int i = 0; i < 12; i++) { - sum += cnpjBase[i] * weight[i]; - } - sum += firstVerifier * weight[12]; - - final int remainder = sum % 11; - - return remainder < 2 ? 0 : 11 - remainder; - } - - /** - * Check if a CNPJ is valid - * - * @param cnpj the CNPJ to be validated - * @return true if the CNPJ is valid, false otherwise - * @throws NullPointerException if the CNPJ is null - */ - public static boolean cnpjIsValid(String cnpj) { - if (cnpj == null) { - throw new NullPointerException("CNPJ cannot be null"); - } - - final String cnpjClean = cnpj.replaceAll("\\D", ""); - - if (cnpjClean.isEmpty()) { - return false; - } - - if (cnpjClean.length() != 14) { - return false; - } - - // Check if all digits are the same - if (cnpjClean.chars().distinct().count() <= 1) { - return false; - } - - // Convert the string to an array of integers - final int[] cnpjArray = cnpjClean.chars().map(Character::getNumericValue).toArray(); - - // Calculate the first verifier and second verifier - final int[] cnpjBase = Arrays.copyOfRange(cnpjArray, 0, 12); - final int firstVerifier = calculateFirstVerifier(cnpjBase); - - final int[] cnpjBaseWithFirstVerifier = Arrays.copyOf(cnpjBase, cnpjBase.length + 1); - cnpjBaseWithFirstVerifier[cnpjBaseWithFirstVerifier.length - 1] = firstVerifier; - - final int secondVerifier = calculateSecondVerifier(cnpjBaseWithFirstVerifier, firstVerifier); - - return cnpjArray[12] == firstVerifier && cnpjArray[13] == secondVerifier; - } -} \ No newline at end of file diff --git a/src/main/java/io/github/multiform_validator/CpfValidator.java b/src/main/java/io/github/multiform_validator/CpfValidator.java deleted file mode 100644 index 879b2c0..0000000 --- a/src/main/java/io/github/multiform_validator/CpfValidator.java +++ /dev/null @@ -1,51 +0,0 @@ -package io.github.multiform_validator; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.IntStream; - -/** - * The CpfValidator class provides a utility method to validate CPF (Cadastro de Pessoas Físicas) numbers. - */ -public class CpfValidator { - // Prevent instantiation - private CpfValidator() { - throw new IllegalStateException("Utility class"); - } - - /** - * Validates a CPF number. - * - * @param cpf the CPF number to validate - * @return true if the CPF number is valid, false otherwise - * @throws NullPointerException if the CPF number is null - */ - public static boolean cpfIsValid(String cpf) { - if (cpf == null) { - throw new NullPointerException("CPF cannot be null"); - } - - final String cpfClean = cpf.replaceAll("\\D", ""); - - if (cpfClean.length() != 11) { - return false; - } - - Pattern pattern = Pattern.compile("(\\d)\\1{10}"); - Matcher matcher = pattern.matcher(cpfClean); - - if (matcher.find()) { - return false; - } - - final int[] cpfArray = cpfClean.chars().map(Character::getNumericValue).toArray(); - - final int sum1 = IntStream.range(0, 9).map(i -> cpfArray[i] * (10 - i)).sum(); - final int sum2 = IntStream.range(0, 10).map(i -> cpfArray[i] * (11 - i)).sum(); - - final int validator1 = sum1 % 11 < 2 ? 0 : 11 - (sum1 % 11); - final int validator2 = sum2 % 11 < 2 ? 0 : 11 - (sum2 % 11); - - return cpfArray[9] == validator1 && cpfArray[10] == validator2; - } -} \ No newline at end of file diff --git a/src/main/java/io/github/multiform_validator/CreditCardValidator.java b/src/main/java/io/github/multiform_validator/CreditCardValidator.java deleted file mode 100644 index 8e3e918..0000000 --- a/src/main/java/io/github/multiform_validator/CreditCardValidator.java +++ /dev/null @@ -1,95 +0,0 @@ -package io.github.multiform_validator; - -public class CreditCardValidator { - // Message constants - private static final String INPUT_VALUE_CANNOT_BE_EMPTY = "Input value cannot be empty."; - - // Prevent instantiation - private CreditCardValidator() { - throw new IllegalStateException("Utility class"); - } - - // ############################################################################################################## - // ############################################################################################################## - // ############################################################################################################## - // isCreditCardValid - - /** - * Validates a credit card number. - * - * @param creditCard The credit card number to validate. - * @return true if the credit card number is valid, false otherwise. - * @throws IllegalArgumentException if the input value is null or empty. - */ - public static boolean isCreditCardValid(String creditCard) { - if (creditCard == null || creditCard.isEmpty()) { - throw new IllegalArgumentException(INPUT_VALUE_CANNOT_BE_EMPTY); - } - - final String creditCardString = creditCard.replaceAll("\\D", ""); - - if (creditCardString.length() < 13 || creditCardString.length() > 19) { - return false; - } - - int sum = 0; - boolean alternate = false; - - for (int i = creditCardString.length() - 1; i >= 0; i--) { - int n = Integer.parseInt(creditCardString.substring(i, i + 1)); - - if (alternate) { - n *= 2; - - if (n > 9) { - n = (n % 10) + 1; - } - } - - sum += n; - alternate = !alternate; - } - - return sum % 10 == 0; - } - - // ############################################################################################################## - // ############################################################################################################## - // ############################################################################################################## - // identifyFlagCard - - /** - * Identifies the flag of a credit card based on its number. - * - * @param cardNumber The credit card number. - * @return The flag of the credit card, or "Unknown" if the flag is not recognized. - * @throws IllegalArgumentException if the input value is null or empty. - */ - public static String identifyFlagCard(String cardNumber) { - if (cardNumber == null || cardNumber.isEmpty()) { - throw new IllegalArgumentException("The input should be a string."); - } - - String[][] flags = { - {"Visa", "^4[0-9]{12}(?:[0-9]{3})?$"}, - {"Mastercard", "^5[1-5][0-9]{14}$"}, - {"American Express", "^3[47][0-9]{13}$"}, - {"Discover", "^6(?:011|5[0-9]{2})[0-9]{12}$"}, - {"JCB", "^(?:2131|1800|35[0-9]{3})[0-9]{11}$"}, - {"Diners Club", "^3(?:0[0-5]|[68][0-9])[0-9]{11}$"}, - {"Maestro", "^(?:5[0678][0-9]{2}|6304|6390|67[0-9]{2})[0-9]{12,15}$"}, - {"UnionPay", "^(62|88)[0-9]{14,17}$"}, - {"Elo", "^63[789][0-9]{13}$"}, - {"Hipercard", "^(3841[0-9]{12}|60[0-9]{14})$"} - }; - - for (String[] flag : flags) { - if (cardNumber.matches(flag[1])) { - return flag[0]; - } - } - - return "Unknown"; - } - -} \ No newline at end of file diff --git a/src/main/java/io/github/multiform_validator/FileValidator.java b/src/main/java/io/github/multiform_validator/FileValidator.java deleted file mode 100644 index a319612..0000000 --- a/src/main/java/io/github/multiform_validator/FileValidator.java +++ /dev/null @@ -1,275 +0,0 @@ -package io.github.multiform_validator; - -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NotNull; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Logger; - -public class FileValidator { - // Prevent instantiation - private FileValidator() { - throw new IllegalStateException("Utility class"); - } - - // Logger - private static final Logger logger = Logger.getLogger(FileValidator.class.getName()); - - // Constants - private static final String ILLEGAL_ARGUMENT_MESSAGE = "The input value cannot be null."; - private static final String ERROR_WHILE_READING_FILE_MESSAGE = "An error occurred while reading the file: "; - - // ############################################################################################################ - // ############################################################################################################ - // ############################################################################################################ - // Image file validation - - /** - * Validates an image file. - * - * @param file The image file to validate. - * @return true if the file is a valid image, false otherwise. - * @throws IllegalArgumentException if the input value is null. - */ - public static boolean isValidImage(File file) { - return isValidImage(file, null); - } - - /** - * Validates an image file, excluding specific file types. - * - * @param file The image file to validate. - * @param exclude A list of file types to exclude from validation. - * @return true if the file is a valid image, false otherwise. - * @throws IllegalArgumentException if the input value is null. - */ - public static boolean isValidImage(File file, List exclude) { - if (file == null) { - throw new IllegalArgumentException(ILLEGAL_ARGUMENT_MESSAGE); - } - - try { - byte[] fileBytes = Files.readAllBytes(file.toPath()); - - if (exclude == null) { - return validateAllImagesFileTypes(fileBytes); - } - - List listToValidate = new ArrayList<>(); - listToValidate.add("gif"); - listToValidate.add("ico"); - listToValidate.add("jpeg"); - listToValidate.add("png"); - - List filteredList = new ArrayList<>(); - for (String item : listToValidate) { - if (!exclude.contains(item)) { - filteredList.add(item); - } - } - - if (filteredList.isEmpty()) { - return false; - } - - return validateImagesFileTypes(fileBytes, filteredList); - - } catch (IOException e) { - logger.severe(ERROR_WHILE_READING_FILE_MESSAGE + e.getMessage()); - return false; - } - } - - @Contract(pure = true) - private static boolean isPng(byte @NotNull [] fileBytes) { - return fileBytes[0] == (byte) 0x89 && fileBytes[1] == 0x50 && fileBytes[2] == 0x4E && fileBytes[3] == 0x47; - } - - @Contract(pure = true) - private static boolean isJpeg(byte @NotNull [] fileBytes) { - return fileBytes[0] == (byte) 0xFF && fileBytes[1] == (byte) 0xD8 && fileBytes[2] == (byte) 0xFF; - } - - @Contract(pure = true) - private static boolean isGif(byte @NotNull [] fileBytes) { - return fileBytes[0] == 0x47 && fileBytes[1] == 0x49 && fileBytes[2] == 0x46 && fileBytes[3] == 0x38; - } - - @Contract(pure = true) - private static boolean isIco(byte @NotNull [] fileBytes) { - return fileBytes[0] == 0x00 && fileBytes[1] == 0x00 && fileBytes[2] == 0x01; - } - - private static boolean validateImagesFileTypes(byte[] fileBytes, @NotNull List filteredList) { - boolean isGifValid = filteredList.contains("gif") && isGif(fileBytes); - boolean isIcoValid = filteredList.contains("ico") && isIco(fileBytes); - boolean isJpegValid = filteredList.contains("jpeg") && isJpeg(fileBytes); - boolean isPngValid = filteredList.contains("png") && isPng(fileBytes); - - return isGifValid || isIcoValid || isJpegValid || isPngValid; - } - - private static boolean validateAllImagesFileTypes(byte[] fileBytes) { - return isGif(fileBytes) || isIco(fileBytes) || isJpeg(fileBytes) || isPng(fileBytes); - } - - // ############################################################################################################ - // ############################################################################################################ - // ############################################################################################################ - // Audio file validation - - /** - * Validates an audio file. - * - * @param file The audio file to validate. - * @return true if the file is a valid audio, false otherwise. - * @throws IllegalArgumentException if the input value is null. - */ - public static boolean isValidAudio(File file) { - return isValidAudio(file, null); - - } - - /** - * Validates an audio file, excluding specific file types. - * - * @param file The audio file to validate. - * @param exclude A list of file types to exclude from validation. - * @return true if the file is a valid audio, false otherwise. - * @throws IllegalArgumentException if the input value is null. - */ - public static boolean isValidAudio(File file, List exclude) { - if (file == null) { - throw new IllegalArgumentException(ILLEGAL_ARGUMENT_MESSAGE); - } - - try { - byte[] fileBytes = Files.readAllBytes(file.toPath()); - - if (exclude == null) { - return validateAllAudiosFileTypes(fileBytes); - } - - List listToValidate = new ArrayList<>(); - listToValidate.add("mp3"); - listToValidate.add("wav"); - - List filteredList = new ArrayList<>(); - for (String item : listToValidate) { - if (!exclude.contains(item)) { - filteredList.add(item); - } - } - - if (filteredList.isEmpty()) { - return false; - } - - return validateAudiosFileTypes(fileBytes, filteredList); - - } catch (IOException e) { - logger.severe(ERROR_WHILE_READING_FILE_MESSAGE + e.getMessage()); - return false; - } - } - - - @Contract(pure = true) - private static boolean isMp3(byte @NotNull [] fileBytes) { - return fileBytes[0] == 0x49 && fileBytes[1] == 0x44 && fileBytes[2] == 0x33; - } - - @Contract(pure = true) - private static boolean isWav(byte @NotNull [] fileBytes) { - return fileBytes[0] == 0x52 && fileBytes[1] == 0x49 && fileBytes[2] == 0x46 && fileBytes[3] == 0x46; - } - - private static boolean validateAudiosFileTypes(byte[] fileBytes, @NotNull List filteredList) { - boolean isMp3Valid = filteredList.contains("mp3") && isMp3(fileBytes); - boolean isWavValid = filteredList.contains("wav") && isWav(fileBytes); - - return isMp3Valid || isWavValid; - } - - private static boolean validateAllAudiosFileTypes(byte[] fileBytes) { - return isMp3(fileBytes) || isWav(fileBytes); - } - - // ############################################################################################################ - // ############################################################################################################ - // ############################################################################################################ - // Pdf file validation - - /** - * Validates a PDF file. - * - * @param file The PDF file to validate. - * @return true if the file is a valid PDF, false otherwise. - * @throws IllegalArgumentException if the input value is null. - */ - public static boolean isValidPdf(File file) { - if (file == null) { - throw new IllegalArgumentException(ILLEGAL_ARGUMENT_MESSAGE); - } - - try { - byte[] fileBytes = Files.readAllBytes(file.toPath()); - return isPdf(fileBytes); - } catch (IOException e) { - logger.severe(ERROR_WHILE_READING_FILE_MESSAGE + e.getMessage()); - return false; - } - } - - @Contract(pure = true) - private static boolean isPdf(byte @NotNull [] fileBytes) { - return fileBytes[0] == 0x25 && fileBytes[1] == 0x50 && fileBytes[2] == 0x44 && fileBytes[3] == 0x46; - } - - // ############################################################################################################ - // ############################################################################################################ - // ############################################################################################################ - // Txt file validation - - /** - * Validates a TXT file. - * - * @param file The TXT file to validate. - * @return true if the file is a valid TXT, false otherwise. - * @throws IllegalArgumentException if the input value is null. - */ - public static boolean isValidTxt(File file) { - if (file == null) { - throw new IllegalArgumentException(ILLEGAL_ARGUMENT_MESSAGE); - } - - try { - byte[] fileBytes = Files.readAllBytes(file.toPath()); - return isTxt(fileBytes); - } catch (IOException e) { - logger.severe(ERROR_WHILE_READING_FILE_MESSAGE + e.getMessage()); - return false; - } - } - - @Contract(pure = true) - private static boolean isTxt(byte @NotNull [] fileBytes) { - if (fileBytes.length == 0) { - return false; - } - for (byte b : fileBytes) { - if ( - (b < 0x20 || b > 0x7e) && - b != 0x0a && - b != 0x0d - ) { - return false; - } - } - return true; - } -} \ No newline at end of file diff --git a/src/main/java/io/github/multiform_validator/Main.java b/src/main/java/io/github/multiform_validator/Main.java index fd19349..286a37c 100644 --- a/src/main/java/io/github/multiform_validator/Main.java +++ b/src/main/java/io/github/multiform_validator/Main.java @@ -1,22 +1,27 @@ /** - * The Main class is the entry point of the application. - * It provides a main method that prints a message to the console. - * This class cannot be instantiated directly. - * Please use the classes in the io.multiform_validator package. - * This is a test version and should not be used in production. + * The Main class is the entry point of the application. It provides a main method that prints a + * message to the console. This class cannot be instantiated directly. Please use the classes in the + * io.multiform_validator package. This is a test version and should not be used in production. */ package io.github.multiform_validator; import java.util.logging.Logger; + public class Main { - private static final Logger logger = Logger.getLogger(Main.class.getName()); - public static void main(String[] args) { - logger.info("This class cannot be instantiated."); - logger.info("Please use the classes in the io.multiform_validator package."); - logger.info("READ the documentation: https://github.com/Multiform-Validator/java/tree/main/docs"); - logger.info("Multiform Validator: Version `0.0.5`"); - logger.info("Library for validating multiple types of documents."); - logger.info("Created by: Gabriel Logan"); - logger.info("Github: https://github.com/gabriel-logan"); - } -} \ No newline at end of file + public static final String REPOSITORY_URL = "https://github.com/Multiform-Validator/java"; + public static final String BRANCH_NAME = "main"; + public static final String VERSION = "0.0.5"; + public static final String GITHUB_USERNAME = "gabriel-logan"; + private static final Logger logger = Logger.getLogger(Main.class.getName()); + + public static void main(String[] args) { + logger.info("This class must not be instantiated."); + logger.info("Please use the classes in the io.multiform_validator package."); + logger.info( + "READ the documentation: " + REPOSITORY_URL + "/blob/" + BRANCH_NAME + "/README.md"); + logger.info("Multiform Validator: Version " + VERSION); + logger.info("Library for validating multiple types of documents."); + logger.info("Created by: " + GITHUB_USERNAME); + logger.info("Github: https://github.com/" + GITHUB_USERNAME); + } +} diff --git a/src/main/java/io/github/multiform_validator/Utils.java b/src/main/java/io/github/multiform_validator/Utils.java deleted file mode 100644 index 30b0117..0000000 --- a/src/main/java/io/github/multiform_validator/Utils.java +++ /dev/null @@ -1,135 +0,0 @@ -package io.github.multiform_validator; - -import org.jetbrains.annotations.NotNull; - -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class Utils { - // Prevent instantiation - private Utils() { - throw new IllegalStateException("Utility class"); - } - - // ############################################################################################################## - // ############################################################################################################## - // ############################################################################################################## - // getOnlyEmail - private static final List GetOnlyEmailCleanAfterDefaultDomain = Arrays.asList( - ".br", ".io", ".pt", ".us", ".org", ".com" - ); - - /** - * Options for the getOnlyEmail method. - */ - public static class GetOnlyEmailOptionsParams { - private Boolean multiple = false; - private Object cleanDomain = false; - private Boolean repeatEmail = false; - - public void setMultiple(Boolean multiple) { - this.multiple = multiple; - } - - public void setCleanDomain(Object cleanDomain) { - this.cleanDomain = cleanDomain; - } - - public void setRepeatEmail(Boolean repeatEmail) { - this.repeatEmail = repeatEmail; - } - } - - private static final GetOnlyEmailOptionsParams getOnlyEmailDefaultOptionsParams = new GetOnlyEmailOptionsParams(); - - /** - * Extracts email addresses from the given text. - * - * @param text The text to extract email addresses from. - * @param options The options for extracting email addresses. - * @return The extracted email addresses. - */ - public static Object getOnlyEmail(String text, GetOnlyEmailOptionsParams options) { - options = validateOptions(options); - - List matches = getEmailMatches(text); - - if (matches.isEmpty()) { - return "No email found"; - } - - if (options.cleanDomain != null && !options.cleanDomain.equals(false)) { - matches = cleanDomain(matches, options.cleanDomain); - } - - return handleRepeatEmail(matches, options); - } - - private static @NotNull GetOnlyEmailOptionsParams validateOptions(GetOnlyEmailOptionsParams options) { - if (options == null) { - options = getOnlyEmailDefaultOptionsParams; - } - - options.multiple = options.multiple != null ? options.multiple : getOnlyEmailDefaultOptionsParams.multiple; - options.cleanDomain = options.cleanDomain != null ? options.cleanDomain : getOnlyEmailDefaultOptionsParams.cleanDomain; - options.repeatEmail = options.repeatEmail != null ? options.repeatEmail : getOnlyEmailDefaultOptionsParams.repeatEmail; - - return options; - } - - private static @NotNull List getEmailMatches(String text) { - Pattern emailPattern = Pattern.compile("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); - Matcher matcher = emailPattern.matcher(text); - - List matches = new ArrayList<>(); - while (matcher.find()) { - matches.add(matcher.group()); - } - - return matches; - } - - private static @NotNull List cleanDomain(@NotNull List emails, Object cleanDomain) { - List domainsToClean; - - if (cleanDomain instanceof List) { - @SuppressWarnings("unchecked") - List castedList = (List) cleanDomain; - domainsToClean = castedList; - } else { - domainsToClean = GetOnlyEmailCleanAfterDefaultDomain; - } - - List cleanedEmails = new ArrayList<>(); - for (String email : emails) { - for (String domain : domainsToClean) { - int index = email.lastIndexOf(domain); - if (index != -1) { - email = email.substring(0, index + domain.length()); - break; - } - } - - for (String domain : domainsToClean) { - int index = email.indexOf(domain); - if (index != -1) { - email = email.substring(0, index + domain.length()); - break; - } - } - cleanedEmails.add(email); - } - - return cleanedEmails; - } - - private static Object handleRepeatEmail(List emails, @NotNull GetOnlyEmailOptionsParams options) { - if (Boolean.FALSE.equals(options.repeatEmail)) { - Set uniqueEmails = new LinkedHashSet<>(emails); - return Boolean.TRUE.equals(options.multiple) ? new ArrayList<>(uniqueEmails) : uniqueEmails.iterator().next(); - } - - return Boolean.TRUE.equals(options.multiple) ? emails : emails.get(0); - } -} \ No newline at end of file diff --git a/src/main/java/io/github/multiform_validator/Validate.java b/src/main/java/io/github/multiform_validator/Validate.java deleted file mode 100644 index 93829ef..0000000 --- a/src/main/java/io/github/multiform_validator/Validate.java +++ /dev/null @@ -1,153 +0,0 @@ -package io.github.multiform_validator; - -import org.jetbrains.annotations.NotNull; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static io.github.multiform_validator.Validator.isEmail; - -public class Validate { - // Prevent instantiation - private Validate() { - throw new IllegalStateException("Utility class"); - } - - // ############################################################################################################## - // ############################################################################################################## - // ############################################################################################################## - // validateEmail - - /** - * The default list of valid email domains. - */ - private static final List validateEmailValidDomainsDefault = Arrays.asList( - "@gmail.com", - "@outlook.com", - "@yahoo.com", - "@icloud.com", - "@hotmail.com", - "@mail.ru", - "@yandex.ru", - "@gmx.com", - "@zoho.com", - "@protonmail.com", - "@protonmail.ch" - ); - - /** - * The ValidateEmailOptionsParams class represents the options for email validation. - */ - public static class ValidateEmailOptionsParams { - private int maxLength = 400; - private String country = ""; - private boolean validDomains = false; - private List validDomainsList = new ArrayList<>(); - - public void setMaxLength(int maxLength) { - this.maxLength = maxLength; - } - - public void setCountry(String country) { - this.country = country; - } - - public void setValidDomains(boolean validDomains) { - this.validDomains = validDomains; - } - - public void setValidDomainsList(List validDomainsList) { - this.validDomainsList = validDomainsList; - } - } - - // Default options for email validation - private static final ValidateEmailOptionsParams validateEmailDefaultOptionsParams = new ValidateEmailOptionsParams(); - - /** - * Validates an email address using the default options. - * - * @param email The email address to validate. - * @return true if the email address is valid, false otherwise. - * @throws IllegalArgumentException if the input value is empty. - */ - public static boolean validateEmail(String email) { - return validateEmail(email, null); - } - - /** - * Validates an email address using the specified options. - * - * @param email The email address to validate. - * @param options The options for email validation. - * @return true if the email address is valid, false otherwise. - * @throws IllegalArgumentException if the input value is empty or if both validDomains and validDomainsList are used at the same time. - */ - public static boolean validateEmail(String email, ValidateEmailOptionsParams options) { - options = validateOptions(options); - - if (email == null || email.isEmpty()) { - throw new IllegalArgumentException("Input value cannot be empty."); - } - - Pattern regex = createRegexPattern(options); - - return validateEmailWithRegex(email, regex, options); - } - - private static @NotNull ValidateEmailOptionsParams validateOptions(ValidateEmailOptionsParams options) { - if (options == null) { - options = validateEmailDefaultOptionsParams; - } - - if (options.validDomains && !options.validDomainsList.isEmpty()) { - throw new IllegalArgumentException("Cannot use validDomains and validDomainsList at the same time."); - } - - return options; - } - - private static @NotNull Pattern createRegexPattern(@NotNull ValidateEmailOptionsParams options) { - List validDomains = options.validDomains ? validateEmailDefaultOptionsParams.validDomainsList : options.validDomainsList; - - List validDomainsCustom = new ArrayList<>(); - if (validDomains != null && !validDomains.isEmpty()) { - for (String domain : validDomains) { - validDomainsCustom.add(domain.replaceAll("[.*+?^${}()|\\[\\]\\\\]", "\\\\$0")); - } - return Pattern.compile(String.join("|", validDomainsCustom) + "$", Pattern.CASE_INSENSITIVE); - } else if (validDomains != null) { - return Pattern.compile(String.join("|", validateEmailValidDomainsDefault) + "$", Pattern.CASE_INSENSITIVE); - } - - return Pattern.compile(""); - } - - private static boolean validateEmailWithRegex(String email, @NotNull Pattern regex, ValidateEmailOptionsParams options) { - Matcher matcher = regex.matcher(email); - if (!matcher.find()) { - return false; - } - - if (!isEmail(email)) { - return false; - } - - if (email.length() > options.maxLength) { - return false; - } - - if (options.country != null && !options.country.isEmpty()) { - return email.endsWith("." + options.country); - } - - return true; - } - - // ############################################################################################################## - // ############################################################################################################## - // ############################################################################################################## -} \ No newline at end of file diff --git a/src/main/java/io/github/multiform_validator/Validator.java b/src/main/java/io/github/multiform_validator/Validator.java deleted file mode 100644 index 717e46e..0000000 --- a/src/main/java/io/github/multiform_validator/Validator.java +++ /dev/null @@ -1,399 +0,0 @@ -package io.github.multiform_validator; - -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; -import java.util.*; -import java.util.regex.Pattern; - -public class Validator { - private static final String INPUT_VALUE_CANNOT_BE_EMPTY = "Input value cannot be empty."; - - private Validator() { - throw new IllegalStateException("Utility class"); - } - - // ############################################################################################################## - // ############################################################################################################## - // ############################################################################################################## - // isAscii - - /** - * Checks if the given string contains only ASCII characters. - * - * @param value the string to be checked - * @return true if the string contains only ASCII characters, false otherwise - * @throws IllegalArgumentException if the input value is null or empty - */ - public static boolean isAscii(String value) { - if (value == null || value.isEmpty()) { - throw new IllegalArgumentException(INPUT_VALUE_CANNOT_BE_EMPTY); - } - - return value.chars().allMatch(c -> c < 128); - } - - // ############################################################################################################## - // ############################################################################################################## - // ############################################################################################################## - // isBase64 - - /** - * Checks if the given string is a valid Base64 encoded string. - * - * @param value the string to be checked - * @return true if the string is a valid Base64 encoded string, false otherwise - * @throws IllegalArgumentException if the input value is null or empty - */ - public static boolean isBase64(String value) { - if (value == null || value.isEmpty()) { - throw new IllegalArgumentException(INPUT_VALUE_CANNOT_BE_EMPTY); - } - - return value.matches("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"); - } - - // ############################################################################################################## - // ############################################################################################################## - // ############################################################################################################## - // isCEP - - /** - * Checks if the given string is a valid CEP (Brazilian postal code). - * - * @param cep the string to be checked - * @return true if the string is a valid CEP, false otherwise - */ - public static boolean isCEP(String cep) { - if (cep.length() < 8 || cep.length() > 10) { - return false; - } - - final String cepString = cep.replaceAll("\\D", ""); - - if (cepString.length() != 8) { - return false; - } - - try { - Integer.parseInt(cepString); - } catch (NumberFormatException e) { - return false; - } - - return true; - } - - // ############################################################################################################## - // ############################################################################################################## - // ############################################################################################################## - // isDate - - private static final List DATE_FORMATTERS = Arrays.asList( - DateTimeFormatter.ofPattern("yyyy-MM-dd"), - DateTimeFormatter.ofPattern("MM/dd/yyyy"), - DateTimeFormatter.ofPattern("dd-MM-yyyy"), - DateTimeFormatter.ofPattern("yyyy/MM/dd"), - DateTimeFormatter.ofPattern("dd.MM.yyyy"), - DateTimeFormatter.ofPattern("yyyy.MM.dd"), - DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.ENGLISH), - DateTimeFormatter.ofPattern("dd-MMMM-yyyy", Locale.ENGLISH), - DateTimeFormatter.ofPattern("dd-MMM-yy", Locale.ENGLISH), - DateTimeFormatter.ofPattern("dd-MMMM-yy", Locale.ENGLISH) - ); - - private static final List DATE_TIME_FORMATTERS = Arrays.asList( - DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"), - DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"), - DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"), - DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"), - DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss"), - DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss"), - DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm:ss", Locale.ENGLISH), - DateTimeFormatter.ofPattern("dd-MMMM-yyyy HH:mm:ss", Locale.ENGLISH), - DateTimeFormatter.ofPattern("dd-MMM-yy HH:mm:ss", Locale.ENGLISH), - DateTimeFormatter.ofPattern("dd-MMMM-yy HH:mm:ss", Locale.ENGLISH) - ); - - /** - * Checks if the given string is a valid date. - * The date can be in the following formats: - * - * @param dateStr the string to be checked - * @return true if the string is a valid date, false otherwise - */ - public static boolean isDate(String dateStr) { - if (dateStr == null || dateStr.isEmpty()) { - throw new IllegalArgumentException("Date string cannot be null or empty"); - } - - for (DateTimeFormatter formatter : DATE_FORMATTERS) { - if (isValidFormat(dateStr, formatter, false)) { - return true; - } - } - - for (DateTimeFormatter formatter : DATE_TIME_FORMATTERS) { - if (isValidFormat(dateStr, formatter, true)) { - return true; - } - } - - return false; - } - - private static boolean isValidFormat(String dateStr, DateTimeFormatter formatter, boolean isDateTime) { - try { - if (isDateTime) { - LocalDateTime.parse(dateStr, formatter); - } else { - LocalDate.parse(dateStr, formatter); - } - return true; - } catch (DateTimeParseException e) { - return false; - } - } - - // ############################################################################################################## - // ############################################################################################################## - // ############################################################################################################## - // isDecimal - - /** - * Checks if the given string is a valid decimal number. - * - * @param value the string to be checked - * @return true if the string is a valid decimal number, false otherwise - * @throws IllegalArgumentException if the input value is null or empty - */ - public static boolean isDecimal(String value) { - if (value == null || value.isEmpty()) { - throw new IllegalArgumentException(INPUT_VALUE_CANNOT_BE_EMPTY); - } - - try { - double parsedValue = Double.parseDouble(value); - - return parsedValue % 1 != 0; - } catch (NumberFormatException e) { - return false; - } - } - - // ############################################################################################################## - // ############################################################################################################## - // ############################################################################################################## - // isEmail - - /** - * Checks if the given string is a valid email address. - * - * @param email the string to be checked - * @return true if the string is a valid email address, false otherwise - * @throws NullPointerException if the email is null - */ - public static boolean isEmail(String email) { - if (email == null) { - throw new NullPointerException("Email cannot be null"); - } - - final Pattern startsWithSpecialChar = Pattern.compile("^[^a-zA-Z]"); - - if (startsWithSpecialChar.matcher(email).find()) { - return false; - } - - final Pattern regex = Pattern.compile("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"); - - if (!regex.matcher(email).find()) { - return false; - } - - final int beforeAt = email.indexOf("@"); - final int afterAt = email.indexOf("@") + 1; - final int afterLastDot = email.lastIndexOf("."); - - if (Character.isDigit(email.charAt(afterAt))) { - return false; - } - - if (Character.isDigit(email.charAt(afterLastDot))) { - return false; - } - - if (email.substring(0, beforeAt).contains("..")) { - return false; - } - - if (email.substring(0, beforeAt).endsWith(".")) { - return false; - } - - final String[] parts = email.split("\\."); - - if (parts.length > 2 && parts[parts.length - 2].equals(parts[parts.length - 3])) { - return false; - } - - // Check if there is more than one @ - if (email.split("@").length - 1 > 1) { - return false; - } - - if (email.substring(afterAt).contains("..")) { - return false; - } - - String[] domainParts = email.split("@")[1].split("\\."); - Set uniqueDomainParts = new HashSet<>(Arrays.asList(domainParts)); - - return domainParts.length == uniqueDomainParts.size(); - } - - // ############################################################################################################## - // ############################################################################################################## - // ############################################################################################################## - // isMACAddress - - /** - * Checks if the given string is a valid MAC address. - * - * @param macAddress the string to be checked - * @return true if the string is a valid MAC address, false otherwise - * @throws IllegalArgumentException if the input value is null or empty - */ - public static boolean isMACAddress(String macAddress) { - if (macAddress == null || macAddress.isEmpty()) { - throw new IllegalArgumentException(INPUT_VALUE_CANNOT_BE_EMPTY); - } - - return macAddress.matches("^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$"); - } - - // ############################################################################################################## - // ############################################################################################################## - // ############################################################################################################## - // isMD5 - - /** - * Checks if the given string is a valid MD5 hash. - * - * @param value the string to be checked - * @return true if the string is a valid MD5 hash, false otherwise - * @throws IllegalArgumentException if the input value is null or empty - */ - public static boolean isMD5(String value) { - if (value == null || value.isEmpty()) { - throw new IllegalArgumentException(INPUT_VALUE_CANNOT_BE_EMPTY); - } - - return value.matches("^[a-fA-F0-9]{32}$"); - } - - // ############################################################################################################## - // ############################################################################################################## - // ############################################################################################################## - // isNumber - - /** - * Checks if the given string is a valid number. - * - * @param value the string to be checked - * @return true if the string is a valid number, false otherwise - * @throws IllegalArgumentException if the input value is null or empty - */ - public static boolean isNumber(String value) { - if (value == null || value.isEmpty()) { - throw new IllegalArgumentException(INPUT_VALUE_CANNOT_BE_EMPTY); - } - - return value.matches("^-?\\d+$"); - } - - // ############################################################################################################## - // ############################################################################################################## - // ############################################################################################################## - // isPort - - /** - * Checks if the given port number is valid. - * - * @param port the port number to be checked - * @return true if the port number is valid, false otherwise - */ - public static boolean isPort(int port) { - return port >= 0 && port <= 65535; - } - - /** - * Checks if the given string is a valid port number. - * - * @param port the string to be checked - * @return true if the string is a valid port number, false otherwise - * @throws IllegalArgumentException if the input value is null or empty - */ - public static boolean isPort(String port) { - if (port == null || port.isEmpty()) { - throw new IllegalArgumentException(INPUT_VALUE_CANNOT_BE_EMPTY); - } - - try { - final int portNumber = Integer.parseInt(port); - return portNumber >= 0 && portNumber <= 65535; - } catch (NumberFormatException e) { - return false; - } - } - - // ############################################################################################################## - // ############################################################################################################## - // ############################################################################################################## - // isPostalCode - - /** - * Checks if the given string is a valid postal code. - * - * @param postalCode the string to be checked - * @return true if the string is a valid postal code, false otherwise - * @throws IllegalArgumentException if the input value is null or empty - */ - public static boolean isPostalCode(String postalCode) { - if (postalCode == null || postalCode.isEmpty()) { - throw new IllegalArgumentException("Input value must be a string."); - } - - final String REGEX_TEST1 = "^\\d{5}(-\\d{4})?$"; // US ZIP code - final String REGEX_TEST2 = "^[A-Za-z]\\d[A-Za-z] \\d[A-Za-z]\\d$"; // Canada postal code - final String REGEX_TEST3 = "^[A-Za-z]{1,2}\\d[A-Za-z\\d]? \\d[A-Za-z]{2}$"; // UK postal code - final String REGEX_TEST4 = "^\\d{5}$"; // France, Spain, Italy, Germany, US postal code - final String REGEX_TEST5 = "^\\d{4}$"; // Netherlands, South Africa, Switzerland postal code - final String REGEX_TEST6 = "^\\d{3}-\\d{4}$"; // Japan postal code - final String REGEX_TEST7 = "^\\d{5}-\\d{3}$"; // Brazil postal code - - return postalCode.matches(REGEX_TEST1) || postalCode.matches(REGEX_TEST2) || postalCode.matches(REGEX_TEST3) - || postalCode.matches(REGEX_TEST4) || postalCode.matches(REGEX_TEST5) || postalCode.matches(REGEX_TEST6) - || postalCode.matches(REGEX_TEST7); - } - - // ############################################################################################################## - // ############################################################################################################## - // ############################################################################################################## - // isTime - - /** - * Checks if the given string is a valid time in the format "HH:mm:ss" or "HH:mm:ss a". - * - * @param time the string to be checked - * @return true if the string is a valid time, false otherwise - * @throws IllegalArgumentException if the input value is null or empty - */ - public static boolean isTime(String time) { - if (time == null || time.isEmpty()) { - throw new IllegalArgumentException(INPUT_VALUE_CANNOT_BE_EMPTY); - } - - return time.matches("^(?:2[0-3]|1\\d|0?\\d):[0-5]\\d(?::[0-5]\\d)?(?: [APap][Mm])?$"); - } -} \ No newline at end of file diff --git a/src/main/java/io/github/multiform_validator/file/AudioValidator.java b/src/main/java/io/github/multiform_validator/file/AudioValidator.java new file mode 100644 index 0000000..d9549f0 --- /dev/null +++ b/src/main/java/io/github/multiform_validator/file/AudioValidator.java @@ -0,0 +1,98 @@ +package io.github.multiform_validator.file; + +import static io.github.multiform_validator.utils.FileUtils.getFilteredList; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Logger; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; + +public class AudioValidator { + private AudioValidator() { + throw new IllegalStateException("Utility class"); + } + + private static final Logger logger = Logger.getLogger(AudioValidator.class.getName()); + private static final String ILLEGAL_ARGUMENT_MESSAGE = "The input value cannot be null."; + private static final String ERROR_WHILE_READING_FILE_MESSAGE = + "An error occurred while reading the file: "; + private static final List FILE_TYPES = new ArrayList<>(); + + static { + FILE_TYPES.add("mp3"); + FILE_TYPES.add("wav"); + } + + /** + * Validates an audio file. + * + * @param file The audio file to validate. + * @return true if the file is a valid audio, false otherwise. + * @throws IllegalArgumentException if the input value is null. + */ + public static boolean isValidAudio(File file) { + return isValidAudio(file, null); + } + + /** + * Validates an audio file, excluding specific file types. + * + * @param file The audio file to validate. + * @param exclude A list of file types to exclude from validation. + * @return true if the file is a valid audio, false otherwise. + * @throws IllegalArgumentException if the input value is null. + */ + public static boolean isValidAudio(File file, List exclude) { + if (file == null) { + throw new IllegalArgumentException(ILLEGAL_ARGUMENT_MESSAGE); + } + + try { + byte[] fileBytes = Files.readAllBytes(file.toPath()); + + if (exclude == null) { + return validateAllAudiosFileTypes(fileBytes); + } + + List filteredList = getFilteredList(exclude, FILE_TYPES); + if (filteredList == null) { + return false; + } + + return validateAudiosFileTypes(fileBytes, filteredList); + + } catch (IOException e) { + logger.severe(ERROR_WHILE_READING_FILE_MESSAGE + e.getMessage()); + return false; + } + } + + @Contract(pure = true) + private static boolean isMp3(byte @NotNull [] fileBytes) { + return fileBytes[0] == 0x49 && fileBytes[1] == 0x44 && fileBytes[2] == 0x33; + } + + @Contract(pure = true) + private static boolean isWav(byte @NotNull [] fileBytes) { + return fileBytes[0] == 0x52 + && fileBytes[1] == 0x49 + && fileBytes[2] == 0x46 + && fileBytes[3] == 0x46; + } + + private static boolean validateAudiosFileTypes( + byte[] fileBytes, @NotNull List filteredList) { + boolean isMp3Valid = filteredList.contains("mp3") && isMp3(fileBytes); + boolean isWavValid = filteredList.contains("wav") && isWav(fileBytes); + + return isMp3Valid || isWavValid; + } + + private static boolean validateAllAudiosFileTypes(byte[] fileBytes) { + return isMp3(fileBytes) || isWav(fileBytes); + } +} diff --git a/src/main/java/io/github/multiform_validator/file/FileValidator.java b/src/main/java/io/github/multiform_validator/file/FileValidator.java new file mode 100644 index 0000000..4c7ceaf --- /dev/null +++ b/src/main/java/io/github/multiform_validator/file/FileValidator.java @@ -0,0 +1,82 @@ +package io.github.multiform_validator.file; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.logging.Logger; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; + +public class FileValidator { + private FileValidator() { + throw new IllegalStateException("Utility class"); + } + + private static final Logger logger = Logger.getLogger(FileValidator.class.getName()); + private static final String ILLEGAL_ARGUMENT_MESSAGE = "The input value cannot be null."; + private static final String ERROR_WHILE_READING_FILE_MESSAGE = + "An error occurred while reading the file: "; + + /** + * Validates a PDF file. + * + * @param file The PDF file to validate. + * @return true if the file is a valid PDF, false otherwise. + * @throws IllegalArgumentException if the input value is null. + */ + public static boolean isValidPdf(File file) { + if (file == null) { + throw new IllegalArgumentException(ILLEGAL_ARGUMENT_MESSAGE); + } + + try { + byte[] fileBytes = Files.readAllBytes(file.toPath()); + return isPdf(fileBytes); + } catch (IOException e) { + logger.severe(ERROR_WHILE_READING_FILE_MESSAGE + e.getMessage()); + return false; + } + } + + @Contract(pure = true) + private static boolean isPdf(byte @NotNull [] fileBytes) { + return fileBytes[0] == 0x25 + && fileBytes[1] == 0x50 + && fileBytes[2] == 0x44 + && fileBytes[3] == 0x46; + } + + /** + * Validates a TXT file. + * + * @param file The TXT file to validate. + * @return true if the file is a valid TXT, false otherwise. + * @throws IllegalArgumentException if the input value is null. + */ + public static boolean isValidTxt(File file) { + if (file == null) { + throw new IllegalArgumentException(ILLEGAL_ARGUMENT_MESSAGE); + } + + try { + byte[] fileBytes = Files.readAllBytes(file.toPath()); + return isTxt(fileBytes); + } catch (IOException e) { + logger.severe(ERROR_WHILE_READING_FILE_MESSAGE + e.getMessage()); + return false; + } + } + + @Contract(pure = true) + private static boolean isTxt(byte @NotNull [] fileBytes) { + if (fileBytes.length == 0) { + return false; + } + for (byte b : fileBytes) { + if ((b < 0x20 || b > 0x7e) && b != 0x0a && b != 0x0d) { + return false; + } + } + return true; + } +} diff --git a/src/main/java/io/github/multiform_validator/file/ImageValidator.java b/src/main/java/io/github/multiform_validator/file/ImageValidator.java new file mode 100644 index 0000000..cb8bc75 --- /dev/null +++ b/src/main/java/io/github/multiform_validator/file/ImageValidator.java @@ -0,0 +1,117 @@ +package io.github.multiform_validator.file; + +import static io.github.multiform_validator.utils.FileUtils.getFilteredList; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Logger; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; + +public class ImageValidator { + private ImageValidator() { + throw new IllegalStateException("Utility class"); + } + + private static final Logger logger = Logger.getLogger(ImageValidator.class.getName()); + private static final String ILLEGAL_ARGUMENT_MESSAGE = "The input value cannot be null."; + private static final String ERROR_WHILE_READING_FILE_MESSAGE = + "An error occurred while reading the file: "; + private static final List FILE_TYPES = new ArrayList<>(); + + static { + FILE_TYPES.add("gif"); + FILE_TYPES.add("ico"); + FILE_TYPES.add("jpeg"); + FILE_TYPES.add("png"); + } + + /** + * Validates an image file. + * + * @param file The image file to validate. + * @return true if the file is a valid image, false otherwise. + * @throws IllegalArgumentException if the input value is null. + */ + public static boolean isValidImage(File file) { + return isValidImage(file, null); + } + + /** + * Validates an image file, excluding specific file types. + * + * @param file The image file to validate. + * @param exclude A list of file types to exclude from validation. + * @return true if the file is a valid image, false otherwise. + * @throws IllegalArgumentException if the input value is null. + */ + public static boolean isValidImage(File file, List exclude) { + if (file == null) { + throw new IllegalArgumentException(ILLEGAL_ARGUMENT_MESSAGE); + } + + try { + byte[] fileBytes = Files.readAllBytes(file.toPath()); + + if (exclude == null) { + return validateAllImagesFileTypes(fileBytes); + } + + List filteredList = getFilteredList(exclude, FILE_TYPES); + if (filteredList == null) { + return false; + } + + return validateImagesFileTypes(fileBytes, filteredList); + + } catch (IOException e) { + logger.severe(ERROR_WHILE_READING_FILE_MESSAGE + e.getMessage()); + return false; + } + } + + @Contract(pure = true) + private static boolean isPng(byte @NotNull [] fileBytes) { + return fileBytes[0] == (byte) 0x89 + && fileBytes[1] == 0x50 + && fileBytes[2] == 0x4E + && fileBytes[3] == 0x47; + } + + @Contract(pure = true) + private static boolean isJpeg(byte @NotNull [] fileBytes) { + return fileBytes[0] == (byte) 0xFF + && fileBytes[1] == (byte) 0xD8 + && fileBytes[2] == (byte) 0xFF; + } + + @Contract(pure = true) + private static boolean isGif(byte @NotNull [] fileBytes) { + return fileBytes[0] == 0x47 + && fileBytes[1] == 0x49 + && fileBytes[2] == 0x46 + && fileBytes[3] == 0x38; + } + + @Contract(pure = true) + private static boolean isIco(byte @NotNull [] fileBytes) { + return fileBytes[0] == 0x00 && fileBytes[1] == 0x00 && fileBytes[2] == 0x01; + } + + private static boolean validateImagesFileTypes( + byte[] fileBytes, @NotNull List filteredList) { + boolean isGifValid = filteredList.contains("gif") && isGif(fileBytes); + boolean isIcoValid = filteredList.contains("ico") && isIco(fileBytes); + boolean isJpegValid = filteredList.contains("jpeg") && isJpeg(fileBytes); + boolean isPngValid = filteredList.contains("png") && isPng(fileBytes); + + return isGifValid || isIcoValid || isJpegValid || isPngValid; + } + + private static boolean validateAllImagesFileTypes(byte[] fileBytes) { + return isGif(fileBytes) || isIco(fileBytes) || isJpeg(fileBytes) || isPng(fileBytes); + } +} diff --git a/src/main/java/io/github/multiform_validator/format/DateValidator.java b/src/main/java/io/github/multiform_validator/format/DateValidator.java new file mode 100644 index 0000000..57c82d9 --- /dev/null +++ b/src/main/java/io/github/multiform_validator/format/DateValidator.java @@ -0,0 +1,96 @@ +package io.github.multiform_validator.format; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; + +public class DateValidator { + private DateValidator() {} + + private static final String INPUT_VALUE_CANNOT_BE_EMPTY = "Input value cannot be empty."; + + private static final List DATE_FORMATTERS = + Arrays.asList( + DateTimeFormatter.ofPattern("yyyy-MM-dd"), + DateTimeFormatter.ofPattern("MM/dd/yyyy"), + DateTimeFormatter.ofPattern("dd-MM-yyyy"), + DateTimeFormatter.ofPattern("yyyy/MM/dd"), + DateTimeFormatter.ofPattern("dd.MM.yyyy"), + DateTimeFormatter.ofPattern("yyyy.MM.dd"), + DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.ENGLISH), + DateTimeFormatter.ofPattern("dd-MMMM-yyyy", Locale.ENGLISH), + DateTimeFormatter.ofPattern("dd-MMM-yy", Locale.ENGLISH), + DateTimeFormatter.ofPattern("dd-MMMM-yy", Locale.ENGLISH)); + + private static final List DATE_TIME_FORMATTERS = + Arrays.asList( + DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"), + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"), + DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"), + DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"), + DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss"), + DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss"), + DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm:ss", Locale.ENGLISH), + DateTimeFormatter.ofPattern("dd-MMMM-yyyy HH:mm:ss", Locale.ENGLISH), + DateTimeFormatter.ofPattern("dd-MMM-yy HH:mm:ss", Locale.ENGLISH), + DateTimeFormatter.ofPattern("dd-MMMM-yy HH:mm:ss", Locale.ENGLISH)); + + /** + * Checks if the given string is a valid date. The date can be in the following formats: + * + * @param dateStr the string to be checked + * @return true if the string is a valid date, false otherwise + */ + public static boolean isDate(String dateStr) { + if (dateStr == null || dateStr.isEmpty()) { + throw new IllegalArgumentException("Date string cannot be null or empty"); + } + + for (DateTimeFormatter formatter : DATE_FORMATTERS) { + if (isValidFormat(dateStr, formatter, false)) { + return true; + } + } + + for (DateTimeFormatter formatter : DATE_TIME_FORMATTERS) { + if (isValidFormat(dateStr, formatter, true)) { + return true; + } + } + + return false; + } + + private static boolean isValidFormat( + String dateStr, DateTimeFormatter formatter, boolean isDateTime) { + try { + if (isDateTime) { + LocalDateTime.parse(dateStr, formatter); + } else { + LocalDate.parse(dateStr, formatter); + } + return true; + } catch (DateTimeParseException e) { + return false; + } + } + + /** + * Checks if the given string is a valid time in the format "HH:mm:ss" or "HH:mm:ss a". + * + * @param time the string to be checked + * @return true if the string is a valid time, false otherwise + * @throws IllegalArgumentException if the input value is null or empty + */ + public static boolean isTime(String time) { + if (time == null || time.isEmpty()) { + throw new IllegalArgumentException(INPUT_VALUE_CANNOT_BE_EMPTY); + } + + return time.matches("^(?:2[0-3]|1\\d|0?\\d):[0-5]\\d(?::[0-5]\\d)?(?: [APap][Mm])?$"); + } +} diff --git a/src/main/java/io/github/multiform_validator/format/EmailValidator.java b/src/main/java/io/github/multiform_validator/format/EmailValidator.java new file mode 100644 index 0000000..1b94950 --- /dev/null +++ b/src/main/java/io/github/multiform_validator/format/EmailValidator.java @@ -0,0 +1,132 @@ +package io.github.multiform_validator.format; + +import io.github.multiform_validator.format.email.EmailDelegate; +import io.github.multiform_validator.format.email.OnlyEmailParams; +import io.github.multiform_validator.format.email.ValidateEmailBuilder; +import java.util.*; +import java.util.regex.Pattern; + +public class EmailValidator { + private EmailValidator() { + throw new IllegalStateException("Utility class"); + } + + /** + * Checks if the given string is a valid email address. + * + * @param email the string to be checked + * @return true if the string is a valid email address, false otherwise + * @throws NullPointerException if the email is null + */ + public static boolean isEmail(String email) { + if (email == null) { + throw new NullPointerException("Email cannot be null"); + } + + final Pattern startsWithSpecialChar = Pattern.compile("^[^a-zA-Z]"); + + if (startsWithSpecialChar.matcher(email).find()) { + return false; + } + + final Pattern regex = Pattern.compile("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"); + + if (!regex.matcher(email).find()) { + return false; + } + + final int beforeAt = email.indexOf("@"); + final int afterAt = email.indexOf("@") + 1; + final int afterLastDot = email.lastIndexOf("."); + + if (Character.isDigit(email.charAt(afterAt))) { + return false; + } + + if (Character.isDigit(email.charAt(afterLastDot))) { + return false; + } + + if (email.substring(0, beforeAt).contains("..")) { + return false; + } + + if (email.substring(0, beforeAt).endsWith(".")) { + return false; + } + + final String[] parts = email.split("\\."); + + if (parts.length > 2 && parts[parts.length - 2].equals(parts[parts.length - 3])) { + return false; + } + + // Check if there is more than one @ + if (email.split("@").length - 1 > 1) { + return false; + } + + if (email.substring(afterAt).contains("..")) { + return false; + } + + String[] domainParts = email.split("@")[1].split("\\."); + Set uniqueDomainParts = new HashSet<>(Arrays.asList(domainParts)); + + return domainParts.length == uniqueDomainParts.size(); + } + + /** + * Validates an email address using the default options. + * + * @param email The email address to validate. + * @return true if the email address is valid, false otherwise. + * @throws IllegalArgumentException if the input value is empty. + */ + public static boolean validateEmail(String email) { + return validateEmail(email, null); + } + + /** + * Validates an email address using the specified options. + * + * @param email The email address to validate. + * @param options The options for email validation. + * @return true if the email address is valid, false otherwise. + * @throws IllegalArgumentException if the input value is empty or if both validDomains and + * validDomainsList are used at the same time. + */ + public static boolean validateEmail(String email, ValidateEmailBuilder options) { + options = EmailDelegate.validateOptions(options); + + if (email == null || email.isEmpty()) { + throw new IllegalArgumentException("Input value cannot be empty."); + } + + Pattern regex = EmailDelegate.createRegexPattern(options); + return EmailDelegate.validateEmailWithRegex(email, regex, options); + } + + /** + * Extracts email addresses from the given text. + * + * @param text The text to extract email addresses from. + * @param options The options for extracting email addresses. + * @return The extracted email addresses. + */ + public static Object getOnlyEmail(String text, OnlyEmailParams options) { + options = EmailDelegate.validateOptions(options); + + List matches = EmailDelegate.getEmailMatches(text); + + if (matches.isEmpty()) { + return "No email found"; + } + + if (!options.getCleanDomain().equals(false)) { + matches = EmailDelegate.cleanDomain(matches, options.getCleanDomain()); + } + + return EmailDelegate.handleRepeatEmail(matches, options); + } +} diff --git a/src/main/java/io/github/multiform_validator/format/StringValidator.java b/src/main/java/io/github/multiform_validator/format/StringValidator.java new file mode 100644 index 0000000..e2cb594 --- /dev/null +++ b/src/main/java/io/github/multiform_validator/format/StringValidator.java @@ -0,0 +1,53 @@ +package io.github.multiform_validator.format; + +public class StringValidator { + + private StringValidator() {} + + private static final String INPUT_VALUE_CANNOT_BE_EMPTY = "Input value cannot be empty"; + + /** + * Checks if the given string contains only ASCII characters. + * + * @param value the string to be checked + * @return true if the string contains only ASCII characters, false otherwise + * @throws IllegalArgumentException if the input value is null or empty + */ + public static boolean isAscii(String value) { + if (value == null || value.isEmpty()) { + throw new IllegalArgumentException(INPUT_VALUE_CANNOT_BE_EMPTY); + } + + return value.chars().allMatch(c -> c < 128); + } + + /** + * Checks if the given string is a valid Base64 encoded string. + * + * @param value the string to be checked + * @return true if the string is a valid Base64 encoded string, false otherwise + * @throws IllegalArgumentException if the input value is null or empty + */ + public static boolean isBase64(String value) { + if (value == null || value.isEmpty()) { + throw new IllegalArgumentException(INPUT_VALUE_CANNOT_BE_EMPTY); + } + + return value.matches("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"); + } + + /** + * Checks if the given string is a valid MD5 hash. + * + * @param value the string to be checked + * @return true if the string is a valid MD5 hash, false otherwise + * @throws IllegalArgumentException if the input value is null or empty + */ + public static boolean isMD5(String value) { + if (value == null || value.isEmpty()) { + throw new IllegalArgumentException(INPUT_VALUE_CANNOT_BE_EMPTY); + } + + return value.matches("^[a-fA-F0-9]{32}$"); + } +} diff --git a/src/main/java/io/github/multiform_validator/format/email/EmailDelegate.java b/src/main/java/io/github/multiform_validator/format/email/EmailDelegate.java new file mode 100644 index 0000000..ab05fbb --- /dev/null +++ b/src/main/java/io/github/multiform_validator/format/email/EmailDelegate.java @@ -0,0 +1,151 @@ +package io.github.multiform_validator.format.email; + +import io.github.multiform_validator.format.EmailValidator; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import org.jetbrains.annotations.NotNull; + +public class EmailDelegate { + private EmailDelegate() { + throw new IllegalStateException("Utility class"); + } + + /** The default list of valid email domains. */ + protected static final List VALID_DOMAINS = + Arrays.asList( + "@gmail.com", + "@outlook.com", + "@yahoo.com", + "@icloud.com", + "@hotmail.com", + "@mail.ru", + "@yandex.ru", + "@gmx.com", + "@zoho.com", + "@protonmail.com", + "@protonmail.ch"); + + protected static final List GetOnlyEmailCleanAfterDefaultDomain = + Arrays.asList(".br", ".io", ".pt", ".us", ".org", ".com"); + + public static @NotNull ValidateEmailBuilder validateOptions(ValidateEmailBuilder options) { + if (options == null) { + options = new ValidateEmailBuilder(); + } + + if (options.isValidDomains() && !options.getValidDomainsList().isEmpty()) { + throw new IllegalArgumentException( + "Cannot use validDomains and validDomainsList at the same time."); + } + + return options; + } + + public static @NotNull Pattern createRegexPattern(@NotNull ValidateEmailBuilder options) { + List validDomains = + options.isValidDomains() + ? new ValidateEmailBuilder().getValidDomainsList() + : options.getValidDomainsList(); + List validDomainsCustom; + if (validDomains != null && !validDomains.isEmpty()) { + validDomainsCustom = + validDomains.stream() + .map(domain -> domain.replaceAll("[.*+?^${}()|\\[\\]\\\\]", "\\\\$0")) + .collect(Collectors.toList()); + return getPattern(validDomainsCustom); + } + + if (validDomains != null) { + return getPattern(VALID_DOMAINS); + } + + return Pattern.compile(""); + } + + public static @NotNull Pattern getPattern(List validDomainsCustom) { + return Pattern.compile(String.join("|", validDomainsCustom) + "$", Pattern.CASE_INSENSITIVE); + } + + public static boolean validateEmailWithRegex( + String email, @NotNull Pattern regex, ValidateEmailBuilder options) { + if (!regex.matcher(email).find() + || !EmailValidator.isEmail(email) + || email.length() > options.getMaxLength()) { + return false; + } + + if (options.getCountry() == null || options.getCountry().isEmpty()) { + return true; + } + + return email.endsWith("." + options.getCountry()); + } + + public static @NotNull OnlyEmailParams validateOptions(OnlyEmailParams options) { + if (options == null) { + options = new OnlyEmailParams(); + } + + return options; + } + + public static @NotNull List getEmailMatches(String text) { + Pattern emailPattern = Pattern.compile("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); + Matcher matcher = emailPattern.matcher(text); + + List matches = new ArrayList<>(); + while (matcher.find()) { + matches.add(matcher.group()); + } + + return matches; + } + + public static @NotNull List cleanDomain( + @NotNull List emails, Object cleanDomain) { + List domainsToClean; + + if (cleanDomain instanceof List) { + @SuppressWarnings("unchecked") + List castedList = (List) cleanDomain; + domainsToClean = castedList; + } else { + domainsToClean = GetOnlyEmailCleanAfterDefaultDomain; + } + + List cleanedEmails = new ArrayList<>(); + for (String email : emails) { + for (String domain : domainsToClean) { + int index = email.lastIndexOf(domain); + if (index != -1) { + email = email.substring(0, index + domain.length()); + break; + } + } + + for (String domain : domainsToClean) { + int index = email.indexOf(domain); + if (index != -1) { + email = email.substring(0, index + domain.length()); + break; + } + } + cleanedEmails.add(email); + } + + return cleanedEmails; + } + + public static Object handleRepeatEmail(List emails, @NotNull OnlyEmailParams options) { + if (Boolean.FALSE.equals(options.getRepeatEmail())) { + Set uniqueEmails = new LinkedHashSet<>(emails); + return Boolean.TRUE.equals(options.getMultiple()) + ? new ArrayList<>(uniqueEmails) + : uniqueEmails.iterator().next(); + } + + return Boolean.TRUE.equals(options.getMultiple()) ? emails : emails.get(0); + } +} diff --git a/src/main/java/io/github/multiform_validator/format/email/OnlyEmailParams.java b/src/main/java/io/github/multiform_validator/format/email/OnlyEmailParams.java new file mode 100644 index 0000000..5ed4f51 --- /dev/null +++ b/src/main/java/io/github/multiform_validator/format/email/OnlyEmailParams.java @@ -0,0 +1,23 @@ +package io.github.multiform_validator.format.email; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NonNull; +import lombok.Setter; + +/** Options for the getOnlyEmail method. */ +@Setter +@Getter +@AllArgsConstructor +@NonNull +public class OnlyEmailParams { + @NonNull private Boolean multiple; + @NonNull private Object cleanDomain; + @NonNull private Boolean repeatEmail; + + public OnlyEmailParams() { + this.multiple = false; + this.cleanDomain = false; + this.repeatEmail = false; + } +} diff --git a/src/main/java/io/github/multiform_validator/format/email/ValidateEmailBuilder.java b/src/main/java/io/github/multiform_validator/format/email/ValidateEmailBuilder.java new file mode 100644 index 0000000..d58b79f --- /dev/null +++ b/src/main/java/io/github/multiform_validator/format/email/ValidateEmailBuilder.java @@ -0,0 +1,25 @@ +package io.github.multiform_validator.format.email; + +import java.util.ArrayList; +import java.util.List; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +/** The ValidateEmailBuilder class represents the options for email validation. */ +@Setter +@Getter +@AllArgsConstructor +public class ValidateEmailBuilder { + private int maxLength; + private String country; + private boolean validDomains; + private List validDomainsList; + + public ValidateEmailBuilder() { + this.maxLength = 400; + this.country = ""; + this.validDomains = false; + this.validDomainsList = new ArrayList<>(); + } +} diff --git a/src/main/java/io/github/multiform_validator/identity/AddressValidator.java b/src/main/java/io/github/multiform_validator/identity/AddressValidator.java new file mode 100644 index 0000000..3ac79f3 --- /dev/null +++ b/src/main/java/io/github/multiform_validator/identity/AddressValidator.java @@ -0,0 +1,72 @@ +package io.github.multiform_validator.identity; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; + +public class AddressValidator { + private AddressValidator() {} + + private static final List POSTAL_PATTERNS = new ArrayList<>(); + + static { + POSTAL_PATTERNS.add(Pattern.compile("^\\d{5}(-\\d{4})?$")); // US ZIP code + POSTAL_PATTERNS.add( + Pattern.compile("^[A-Za-z]\\d[A-Za-z] \\d[A-Za-z]\\d$")); // Canada postal code + POSTAL_PATTERNS.add( + Pattern.compile("^[A-Za-z]{1,2}\\d[A-Za-z\\d]? \\d[A-Za-z]{2}$")); // UK postal code + POSTAL_PATTERNS.add( + Pattern.compile("^\\d{5}$")); // France, Spain, Italy, Germany, US postal code + POSTAL_PATTERNS.add( + Pattern.compile("^\\d{4}$")); // Netherlands, South Africa, Switzerland postal code + POSTAL_PATTERNS.add(Pattern.compile("^\\d{3}-\\d{4}$")); // Japan postal code + POSTAL_PATTERNS.add(Pattern.compile("^\\d{5}-\\d{3}$")); // Brazil postal code + } + + /** + * Checks if the given string is a valid CEP (Brazilian postal code). + * + * @param cep the string to be checked + * @return true if the string is a valid CEP, false otherwise + */ + public static boolean isCEP(String cep) { + if (cep.length() < 8 || cep.length() > 10) { + return false; + } + + final String cepString = cep.replaceAll("\\D", ""); + + if (cepString.length() != 8) { + return false; + } + + try { + Integer.parseInt(cepString); + } catch (NumberFormatException e) { + return false; + } + + return true; + } + + /** + * Checks if the given string is a valid postal code. + * + * @param postalCode the string to be checked + * @return true if the string is a valid postal code, false otherwise + * @throws IllegalArgumentException if the input value is null or empty + */ + public static boolean isPostalCode(String postalCode) { + if (postalCode == null || postalCode.isEmpty()) { + throw new IllegalArgumentException("Input value must be a string."); + } + + for (Pattern pattern : POSTAL_PATTERNS) { + if (pattern.matcher(postalCode).matches()) { + return true; + } + } + + return false; + } +} diff --git a/src/main/java/io/github/multiform_validator/identity/CnpjValidator.java b/src/main/java/io/github/multiform_validator/identity/CnpjValidator.java new file mode 100644 index 0000000..d10656d --- /dev/null +++ b/src/main/java/io/github/multiform_validator/identity/CnpjValidator.java @@ -0,0 +1,86 @@ +package io.github.multiform_validator.identity; + +import static io.github.multiform_validator.utils.NumberUtils.NON_DIGIT_PATTERN; +import static io.github.multiform_validator.utils.NumberUtils.isAllSameDigit; + +import java.util.Arrays; + +public class CnpjValidator { + + private CnpjValidator() { + throw new IllegalStateException("Utility class"); + } + + private static final int[] FIRST_WEIGHT = {5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2}; + private static final int[] SECOND_WEIGHT = {6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2}; + + /** + * Calculate the first verifier digit of a CNPJ + * + * @param cnpjBase an array of integers with the first 12 digits of a CNPJ + * @return the first verifier digit + */ + private static int calculateFirstVerifier(int[] cnpjBase) { + int sum = 0; + for (int i = 0; i < 12; i++) { + int i1 = cnpjBase[i] * FIRST_WEIGHT[i]; + sum += i1; + } + final int remainder = sum % 11; + + return remainder < 2 ? 0 : 11 - remainder; + } + + /** + * Calculate the second verifier digit of a CNPJ + * + * @param cnpjBase an array of integers with the first 12 digits of a CNPJ + * @param firstVerifier the first verifier digit + * @return the second verifier digit + */ + private static int calculateSecondVerifier(int[] cnpjBase, int firstVerifier) { + int sum = 0; + for (int i = 0; i < 12; i++) { + int i1 = cnpjBase[i] * SECOND_WEIGHT[i]; + sum += i1; + } + sum += firstVerifier * SECOND_WEIGHT[12]; + + final int remainder = sum % 11; + + return remainder < 2 ? 0 : 11 - remainder; + } + + /** + * Check if a CNPJ is valid + * + * @param cnpj the CNPJ to be validated + * @return true if the CNPJ is valid, false otherwise + * @throws NullPointerException if the CNPJ is null + */ + public static boolean cnpjIsValid(String cnpj) { + if (cnpj == null) { + throw new NullPointerException("CNPJ cannot be null"); + } + + final String cnpjClean = NON_DIGIT_PATTERN.matcher(cnpj).replaceAll(""); + + if (cnpjClean.length() != 14 || isAllSameDigit(cnpjClean)) { + return false; + } + + // Convert the string to an array of integers + final int[] cnpjArray = cnpjClean.chars().map(Character::getNumericValue).toArray(); + + // Calculate the first verifier and second verifier + final int[] cnpjBase = Arrays.copyOfRange(cnpjArray, 0, 12); + final int firstVerifier = calculateFirstVerifier(cnpjBase); + + final int[] cnpjBaseWithFirstVerifier = Arrays.copyOf(cnpjBase, cnpjBase.length + 1); + cnpjBaseWithFirstVerifier[cnpjBaseWithFirstVerifier.length - 1] = firstVerifier; + + final int secondVerifier = calculateSecondVerifier(cnpjBaseWithFirstVerifier, firstVerifier); + + return cnpjArray[12] == firstVerifier && cnpjArray[13] == secondVerifier; + } +} diff --git a/src/main/java/io/github/multiform_validator/identity/CpfValidator.java b/src/main/java/io/github/multiform_validator/identity/CpfValidator.java new file mode 100644 index 0000000..5b87b45 --- /dev/null +++ b/src/main/java/io/github/multiform_validator/identity/CpfValidator.java @@ -0,0 +1,63 @@ +package io.github.multiform_validator.identity; + +import static io.github.multiform_validator.utils.NumberUtils.NON_DIGIT_PATTERN; +import static io.github.multiform_validator.utils.NumberUtils.isAllSameDigit; + +import org.jetbrains.annotations.NotNull; + +/** + * The CpfValidator class provides a utility method to validate CPF (Cadastro de Pessoas Físicas) + * numbers. + */ +public class CpfValidator { + private CpfValidator() { + throw new IllegalStateException("Utility class"); + } + + /** + * Validates a CPF number. + * + * @param cpf the CPF number to validate + * @return true if the CPF number is valid, false otherwise + * @throws NullPointerException if the CPF number is null + */ + public static boolean cpfIsValid(String cpf) { + if (cpf == null) { + throw new NullPointerException("CPF cannot be null"); + } + + final String cpfClean = NON_DIGIT_PATTERN.matcher(cpf).replaceAll(""); + if (cpfClean.length() != 11 || isAllSameDigit(cpfClean)) { + return false; + } + + int[] cpfArray = getCpfArray(cpfClean); + + int sum1 = 0; + int sum2 = 0; + for (int i = 0; i < 9; i++) { + sum1 += cpfArray[i] * (10 - i); + sum2 += cpfArray[i] * (11 - i); + } + sum2 += cpfArray[9] * 2; + + int validator1 = sum1 % 11 < 2 ? 0 : 11 - (sum1 % 11); + int validator2 = sum2 % 11 < 2 ? 0 : 11 - (sum2 % 11); + + return cpfArray[9] == validator1 && cpfArray[10] == validator2; + } + + /** + * Converts a clean CPF number to an array of integers. + * + * @param cpfClean the clean CPF number + * @return an array of integers + */ + private static int @NotNull [] getCpfArray(String cpfClean) { + int[] cpfArray = new int[11]; + for (int i = 0; i < 11; i++) { + cpfArray[i] = cpfClean.charAt(i) - '0'; + } + return cpfArray; + } +} diff --git a/src/main/java/io/github/multiform_validator/identity/CreditCardValidator.java b/src/main/java/io/github/multiform_validator/identity/CreditCardValidator.java new file mode 100644 index 0000000..54bab96 --- /dev/null +++ b/src/main/java/io/github/multiform_validator/identity/CreditCardValidator.java @@ -0,0 +1,89 @@ +package io.github.multiform_validator.identity; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.regex.Pattern; + +public class CreditCardValidator { + private CreditCardValidator() { + throw new IllegalStateException("Utility class"); + } + + private static final String INPUT_VALUE_CANNOT_BE_EMPTY = "Input value cannot be empty."; + private static final Map patternFlagMap = new HashMap<>(); + + static { + patternFlagMap.put(Pattern.compile("^4\\d{12}(?:\\d{3})?$"), "Visa"); + patternFlagMap.put(Pattern.compile("^5[1-5]\\d{14}$"), "Mastercard"); + patternFlagMap.put(Pattern.compile("^3[47]\\d{13}$"), "American Express"); + patternFlagMap.put(Pattern.compile("^6(?:011|5\\d{2})\\d{12}$"), "Discover"); + patternFlagMap.put(Pattern.compile("^(?:2131|1800|35\\d{3})\\d{11}$"), "JCB"); + patternFlagMap.put(Pattern.compile("^3(?:0[0-5]|[68]\\d)\\d{11}$"), "Diners Club"); + patternFlagMap.put( + Pattern.compile("^(?:5[0678]\\d{2}|6304|6390|67\\d{2})\\d{12,15}$"), "Maestro"); + patternFlagMap.put(Pattern.compile("^(62|88)\\d{14,17}$"), "UnionPay"); + patternFlagMap.put(Pattern.compile("^63[789]\\d{13}$"), "Elo"); + patternFlagMap.put(Pattern.compile("^(3841\\d{12}|60(?!11)\\d{14})$"), "Hipercard"); + } + + /** + * Validates a credit card number. + * + * @param creditCard The credit card number to validate. + * @return true if the credit card number is valid, false otherwise. + * @throws IllegalArgumentException if the input value is null or empty. + */ + public static boolean isCreditCardValid(String creditCard) { + if (creditCard == null || creditCard.isEmpty()) { + throw new IllegalArgumentException(INPUT_VALUE_CANNOT_BE_EMPTY); + } + + final String creditCardString = creditCard.replaceAll("\\D", ""); + + if (creditCardString.length() < 13 || creditCardString.length() > 19) { + return false; + } + + int sum = 0; + boolean alternate = false; + + for (int i = creditCardString.length() - 1; i >= 0; i--) { + int n = Integer.parseInt(creditCardString.substring(i, i + 1)); + + if (alternate) { + n *= 2; + + if (n > 9) { + n = (n % 10) + 1; + } + } + + sum += n; + alternate = !alternate; + } + + return sum % 10 == 0; + } + + /** + * Identifies the flag of a credit card based on its number. + * + * @param cardNumber The credit card number. + * @return An optional containing the flag of the credit card if it was identified, or an empty + * optional otherwise. + */ + public static Optional identifyFlagCard(String cardNumber) { + if (cardNumber == null || cardNumber.isEmpty()) { + return Optional.empty(); + } + + for (Map.Entry entry : patternFlagMap.entrySet()) { + if (entry.getKey().matcher(cardNumber).matches()) { + return Optional.of(entry.getValue()); + } + } + + return Optional.empty(); + } +} diff --git a/src/main/java/io/github/multiform_validator/numeric/MachineValidator.java b/src/main/java/io/github/multiform_validator/numeric/MachineValidator.java new file mode 100644 index 0000000..4a7e652 --- /dev/null +++ b/src/main/java/io/github/multiform_validator/numeric/MachineValidator.java @@ -0,0 +1,52 @@ +package io.github.multiform_validator.numeric; + +public class MachineValidator { + private MachineValidator() {} + + private static final String INPUT_VALUE_CANNOT_BE_EMPTY = "Input value cannot be empty"; + + /** + * Checks if the given string is a valid MAC address. + * + * @param macAddress the string to be checked + * @return true if the string is a valid MAC address, false otherwise + * @throws IllegalArgumentException if the input value is null or empty + */ + public static boolean isMACAddress(String macAddress) { + if (macAddress == null || macAddress.isEmpty()) { + throw new IllegalArgumentException(INPUT_VALUE_CANNOT_BE_EMPTY); + } + + return macAddress.matches("^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$"); + } + + /** + * Checks if the given port number is valid. + * + * @param port the port number to be checked + * @return true if the port number is valid, false otherwise + */ + public static boolean isPort(int port) { + return port >= 0 && port <= 65535; + } + + /** + * Checks if the given string is a valid port number. + * + * @param port the string to be checked + * @return true if the string is a valid port number, false otherwise + * @throws IllegalArgumentException if the input value is null or empty + */ + public static boolean isPort(String port) { + if (port == null || port.isEmpty()) { + throw new IllegalArgumentException(INPUT_VALUE_CANNOT_BE_EMPTY); + } + + try { + final int portNumber = Integer.parseInt(port); + return portNumber >= 0 && portNumber <= 65535; + } catch (NumberFormatException e) { + return false; + } + } +} diff --git a/src/main/java/io/github/multiform_validator/numeric/NumberValidator.java b/src/main/java/io/github/multiform_validator/numeric/NumberValidator.java new file mode 100644 index 0000000..e5f2661 --- /dev/null +++ b/src/main/java/io/github/multiform_validator/numeric/NumberValidator.java @@ -0,0 +1,28 @@ +package io.github.multiform_validator.numeric; + +public class NumberValidator { + private NumberValidator() {} + + private static final String INPUT_VALUE_CANNOT_BE_EMPTY = "Input value cannot be empty"; + + /** + * Checks if the given string is a valid decimal number. + * + * @param value the string to be checked + * @return true if the string is a valid decimal number, false otherwise + * @throws IllegalArgumentException if the input value is null or empty + */ + public static boolean isDecimal(String value) { + if (value == null || value.isEmpty()) { + throw new IllegalArgumentException(INPUT_VALUE_CANNOT_BE_EMPTY); + } + + try { + double parsedValue = Double.parseDouble(value); + + return parsedValue % 1 != 0; + } catch (NumberFormatException e) { + return false; + } + } +} diff --git a/src/main/java/io/github/multiform_validator/utils/FileUtils.java b/src/main/java/io/github/multiform_validator/utils/FileUtils.java new file mode 100644 index 0000000..ac2cd56 --- /dev/null +++ b/src/main/java/io/github/multiform_validator/utils/FileUtils.java @@ -0,0 +1,33 @@ +package io.github.multiform_validator.utils; + +import java.util.ArrayList; +import java.util.List; +import org.jetbrains.annotations.Nullable; + +public class FileUtils { + private FileUtils() { + throw new IllegalStateException("Utility class"); + } + + /** + * Filters a list of strings. + * + * @param exclude A list of strings to exclude from the list to validate. + * @param listToValidate The list of strings to validate. + * @return A filtered list of strings. + */ + public static @Nullable List getFilteredList( + List exclude, List listToValidate) { + List filteredList = new ArrayList<>(); + for (String item : listToValidate) { + if (!exclude.contains(item)) { + filteredList.add(item); + } + } + + if (filteredList.isEmpty()) { + return null; + } + return filteredList; + } +} diff --git a/src/main/java/io/github/multiform_validator/utils/NumberUtils.java b/src/main/java/io/github/multiform_validator/utils/NumberUtils.java new file mode 100644 index 0000000..ab98566 --- /dev/null +++ b/src/main/java/io/github/multiform_validator/utils/NumberUtils.java @@ -0,0 +1,27 @@ +package io.github.multiform_validator.utils; + +import java.util.regex.Pattern; + +public class NumberUtils { + private NumberUtils() { + throw new IllegalStateException("Utility class"); + } + + public static final Pattern NON_DIGIT_PATTERN = Pattern.compile("\\D"); + + /** + * Check if all characters in a string are the same. + * + * @param string The string to check. + * @return true if all characters are the same, false otherwise. + */ + public static boolean isAllSameDigit(String string) { + char firstChar = string.charAt(0); + for (int i = 1; i < string.length(); i++) { + if (string.charAt(i) != firstChar) { + return false; + } + } + return true; + } +} diff --git a/src/test/java/AudioValidatorTest.java b/src/test/java/AudioValidatorTest.java new file mode 100644 index 0000000..7a11850 --- /dev/null +++ b/src/test/java/AudioValidatorTest.java @@ -0,0 +1,74 @@ +import static io.github.multiform_validator.file.AudioValidator.isValidAudio; +import static org.junit.jupiter.api.Assertions.*; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import org.junit.jupiter.api.Test; + +class AudioValidatorTest { + final String audioBasePath = "src/test/java/assets/isValidAudio"; + final String validAudioMp3Path = audioBasePath + "/valid/valid.mp3"; + final String validAudioWavPath = audioBasePath + "/valid/valid.wav"; + + final String invalidAudioMp3Path = audioBasePath + "/invalid/invalid.mp3"; + final String invalidAudioWavPath = audioBasePath + "/invalid/invalid.wav"; + + @Test + void testValidateAudioWithValidMp3Audio() { + File file = new File(validAudioMp3Path); + assertTrue(isValidAudio(file)); + } + + @Test + void testValidateAudioWithInvalidMp3Audio() { + File file = new File(invalidAudioMp3Path); + assertFalse(isValidAudio(file)); + } + + @Test + void testValidateAudioWithValidWavAudio() { + File file = new File(validAudioWavPath); + assertTrue(isValidAudio(file)); + } + + @Test + void testValidateAudioWithInvalidWavAudio() { + File file = new File(invalidAudioWavPath); + assertFalse(isValidAudio(file)); + } + + @Test + void testValidateAudioWithExclusionExceptAudioToBeValidate() { + File file = new File(validAudioWavPath); + List exclude = Collections.singletonList("mp3"); + assertTrue(isValidAudio(file, exclude)); + } + + @Test + void testValidateAudioWithValidAudioAndValidExclusion() { + File file = new File(validAudioMp3Path); + List exclude = Collections.singletonList("mp3"); + assertFalse(isValidAudio(file, exclude)); + } + + @Test + void testValidateAudioWithValidAudioAndInvalidExclusion() { + File file = new File(validAudioMp3Path); + List exclude = Collections.singletonList("wav"); + assertTrue(isValidAudio(file, exclude)); + } + + @Test + void testValidateExcludingAllAudios() { + File file = new File(validAudioMp3Path); + List exclude = Arrays.asList("wav", "mp3"); + assertFalse(isValidAudio(file, exclude)); + } + + @Test + void testValidateAudioWithNullFile() { + assertThrows(IllegalArgumentException.class, () -> isValidAudio(null)); + } +} diff --git a/src/test/java/CnpjValidatorTest.java b/src/test/java/CnpjValidatorTest.java index 98c1ddd..232d19f 100644 --- a/src/test/java/CnpjValidatorTest.java +++ b/src/test/java/CnpjValidatorTest.java @@ -1,64 +1,65 @@ -import org.junit.jupiter.api.Test; - -import static io.github.multiform_validator.CnpjValidator.cnpjIsValid; +import static io.github.multiform_validator.identity.CnpjValidator.cnpjIsValid; import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + class CnpjValidatorTest { - @Test - void testValidCnpj() { - assertTrue(cnpjIsValid("72.231.875/0001-05")); - assertTrue(cnpjIsValid("41997509000138")); - } - @Test - void testInvalidCnpj() { - assertFalse(cnpjIsValid("12.345.678/0001-91")); - assertFalse(cnpjIsValid("12345678000191")); - } + @Test + void testValidCnpj() { + assertTrue(cnpjIsValid("72.231.875/0001-05")); + assertTrue(cnpjIsValid("41997509000138")); + } + + @Test + void testInvalidCnpj() { + assertFalse(cnpjIsValid("12.345.678/0001-91")); + assertFalse(cnpjIsValid("12345678000191")); + } - @Test - void testNullCnpj() { - assertThrows(NullPointerException.class, () -> cnpjIsValid(null)); - } + @Test + void testNullCnpj() { + assertThrows(NullPointerException.class, () -> cnpjIsValid(null)); + } - @Test - void testEmptyCnpj() { - assertFalse(cnpjIsValid("")); - } + @Test + void testEmptyCnpj() { + assertFalse(cnpjIsValid("")); + } - @Test - void testInvalidFormatCnpj() { - assertFalse(cnpjIsValid("12.345.678/0001-9")); - assertFalse(cnpjIsValid("1234567800019")); - } + @Test + void testInvalidFormatCnpj() { + assertFalse(cnpjIsValid("12.345.678/0001-9")); + assertFalse(cnpjIsValid("1234567800019")); + } - @Test - void testInvalidLengthCnpj() { - assertFalse(cnpjIsValid("12.345.678/0001-900")); - assertFalse(cnpjIsValid("123456780001900")); - } + @Test + void testInvalidLengthCnpj() { + assertFalse(cnpjIsValid("12.345.678/0001-900")); + assertFalse(cnpjIsValid("123456780001900")); + } - @Test - void testInvalidCnpjWithLetters() { - assertFalse(cnpjIsValid("12.345.678/0001-9A")); - assertFalse(cnpjIsValid("1234567800019A")); - } + @Test + void testInvalidCnpjWithLetters() { + assertFalse(cnpjIsValid("12.345.678/0001-9A")); + assertFalse(cnpjIsValid("1234567800019A")); + } - @Test - void testInvalidCnpjWithSpecialCharacters() { - assertFalse(cnpjIsValid("12.345.678/0001-9@")); - assertFalse(cnpjIsValid("1234567800019@")); - } + @Test + void testInvalidCnpjWithSpecialCharacters() { + assertFalse(cnpjIsValid("12.345.678/0001-9@")); + assertFalse(cnpjIsValid("1234567800019@")); + } - @Test - void testInvalidCnpjWithSpaces() { - assertFalse(cnpjIsValid("12.345.678/0001-9 ")); - assertFalse(cnpjIsValid("1234567800019 ")); - } + @Test + void testInvalidCnpjWithSpaces() { + assertFalse(cnpjIsValid("12.345.678/0001-9 ")); + assertFalse(cnpjIsValid("1234567800019 ")); + } - @Test - void testAllDigitsAreEqual() { - assertFalse(cnpjIsValid("00.000.000/0000-00")); - assertFalse(cnpjIsValid("00000000000000")); - } -} \ No newline at end of file + @Test + void testAllDigitsAreEqual() { + assertFalse(cnpjIsValid("00.000.000/0000-00")); + assertFalse(cnpjIsValid("00000000000000")); + } +} diff --git a/src/test/java/CpfValidatorTest.java b/src/test/java/CpfValidatorTest.java index 48064f1..52c7411 100644 --- a/src/test/java/CpfValidatorTest.java +++ b/src/test/java/CpfValidatorTest.java @@ -1,70 +1,70 @@ -import org.junit.jupiter.api.Test; - -import static io.github.multiform_validator.CpfValidator.cpfIsValid; +import static io.github.multiform_validator.identity.CpfValidator.cpfIsValid; import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + class CpfValidatorTest { - @Test - void testValidCpf() { - assertTrue(cpfIsValid("12345678909")); - assertTrue(cpfIsValid("11144477735")); - } + @Test + void testValidCpf() { + assertTrue(cpfIsValid("12345678909")); + assertTrue(cpfIsValid("11144477735")); + } - @Test - void testInvalidCpf() { - assertFalse(cpfIsValid("12345678901")); - assertFalse(cpfIsValid("11144477736")); - } + @Test + void testInvalidCpf() { + assertFalse(cpfIsValid("12345678901")); + assertFalse(cpfIsValid("11144477736")); + } - @Test - void testNullCpf() { - assertThrows(NullPointerException.class, () -> cpfIsValid(null)); - } + @Test + void testNullCpf() { + assertThrows(NullPointerException.class, () -> cpfIsValid(null)); + } - @Test - void testEmptyCpf() { - assertFalse(cpfIsValid("")); - } + @Test + void testEmptyCpf() { + assertFalse(cpfIsValid("")); + } - @Test - void testInvalidFormatCpf() { - assertFalse(cpfIsValid("123.456.789-19")); - assertFalse(cpfIsValid("1114447773A")); - } + @Test + void testInvalidFormatCpf() { + assertFalse(cpfIsValid("123.456.789-19")); + assertFalse(cpfIsValid("1114447773A")); + } - @Test - void testInvalidLengthCpf() { - assertFalse(cpfIsValid("1234567890")); - assertFalse(cpfIsValid("111444777350")); - } + @Test + void testInvalidLengthCpf() { + assertFalse(cpfIsValid("1234567890")); + assertFalse(cpfIsValid("111444777350")); + } - @Test - void testInvalidCpfWithLetters() { - assertFalse(cpfIsValid("1234567890A")); - assertFalse(cpfIsValid("1114447773A")); - } + @Test + void testInvalidCpfWithLetters() { + assertFalse(cpfIsValid("1234567890A")); + assertFalse(cpfIsValid("1114447773A")); + } - @Test - void testInvalidCpfWithSpecialCharacters() { - assertFalse(cpfIsValid("1234567890@")); - assertFalse(cpfIsValid("1114447773@")); - } + @Test + void testInvalidCpfWithSpecialCharacters() { + assertFalse(cpfIsValid("1234567890@")); + assertFalse(cpfIsValid("1114447773@")); + } - @Test - void testInvalidCpfWithSpaces() { - assertFalse(cpfIsValid("1234567890 ")); - assertFalse(cpfIsValid("1114447773 ")); - } + @Test + void testInvalidCpfWithSpaces() { + assertFalse(cpfIsValid("1234567890 ")); + assertFalse(cpfIsValid("1114447773 ")); + } - @Test - void testAllDigitsAreEqual() { - assertFalse(cpfIsValid("00000000000")); - assertFalse(cpfIsValid("11111111111")); - } + @Test + void testAllDigitsAreEqual() { + assertFalse(cpfIsValid("00000000000")); + assertFalse(cpfIsValid("11111111111")); + } - @Test - void testInvalidCpfWithSpecialCharactersAndLetters() { - assertFalse(cpfIsValid("1234567890@")); - assertFalse(cpfIsValid("1114447773A")); - } -} \ No newline at end of file + @Test + void testInvalidCpfWithSpecialCharactersAndLetters() { + assertFalse(cpfIsValid("1234567890@")); + assertFalse(cpfIsValid("1114447773A")); + } +} diff --git a/src/test/java/CreditCardValidatorTest.java b/src/test/java/CreditCardValidatorTest.java index 52d62a8..070a504 100644 --- a/src/test/java/CreditCardValidatorTest.java +++ b/src/test/java/CreditCardValidatorTest.java @@ -1,44 +1,54 @@ -import org.junit.jupiter.api.Test; - -import static io.github.multiform_validator.CreditCardValidator.identifyFlagCard; -import static io.github.multiform_validator.CreditCardValidator.isCreditCardValid; +import static io.github.multiform_validator.identity.CreditCardValidator.identifyFlagCard; +import static io.github.multiform_validator.identity.CreditCardValidator.isCreditCardValid; import static org.junit.jupiter.api.Assertions.*; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import org.junit.jupiter.api.Test; + class CreditCardValidatorTest { - // ############################################################################################################## - // ############################################################################################################## - // ############################################################################################################## - // Test IsCreditCardValid - @Test - void testIsCreditCardValid() { - assertTrue(isCreditCardValid("4111111111111111")); - assertTrue(isCreditCardValid("5500000000000004")); - assertFalse(isCreditCardValid("1234567890123456")); - assertFalse(isCreditCardValid("12345678901234567890")); - assertThrows(IllegalArgumentException.class, () -> isCreditCardValid(null)); - assertThrows(IllegalArgumentException.class, () -> isCreditCardValid("")); - } + @Test + void testIsCreditCardValid() { + assertTrue(isCreditCardValid("4111111111111111")); + assertTrue(isCreditCardValid("5500000000000004")); + assertFalse(isCreditCardValid("1234567890123456")); + assertFalse(isCreditCardValid("12345678901234567890")); + assertThrows(IllegalArgumentException.class, () -> isCreditCardValid(null)); + assertThrows(IllegalArgumentException.class, () -> isCreditCardValid("")); + } + + @Test + void testIdentifyFlagCard() { + HashMap cards = new HashMap<>(); + + cards.put("4111111111111111", "Visa"); + cards.put("5555555555554444", "Mastercard"); + cards.put("378282246310005", "American Express"); + cards.put("6011111111111117", "Discover"); + cards.put("3530111333300000", "JCB"); + cards.put("30569309025904", "Diners Club"); + cards.put("6304000000000000", "Maestro"); + cards.put("6200000000000005", "UnionPay"); + cards.put("6370950000000005", "Elo"); + cards.put("3841000000000000", "Hipercard"); + cards.put("1234567890123456", null); + cards.put("", null); + cards.put(null, null); - // ############################################################################################################## - // ############################################################################################################## - // ############################################################################################################## - // Test IdentifyFlagCard + for (Map.Entry entry : cards.entrySet()) { + Optional card = identifyFlagCard(entry.getKey()); + if (entry.getKey() == null || entry.getValue() == null) { + assertFalse(card.isPresent()); + continue; + } - @Test - void testIdentifyFlagCard() { - assertEquals("Visa", identifyFlagCard("4111111111111111")); - assertEquals("Mastercard", identifyFlagCard("5555555555554444")); - assertEquals("American Express", identifyFlagCard("378282246310005")); - assertEquals("Discover", identifyFlagCard("6011111111111117")); - assertEquals("JCB", identifyFlagCard("3530111333300000")); - assertEquals("Diners Club", identifyFlagCard("30569309025904")); - assertEquals("Maestro", identifyFlagCard("6304000000000000")); - assertEquals("UnionPay", identifyFlagCard("6200000000000005")); - assertEquals("Elo", identifyFlagCard("6370950000000005")); - assertEquals("Hipercard", identifyFlagCard("3841000000000000")); - assertEquals("Unknown", identifyFlagCard("1234567890123456")); - assertThrows(IllegalArgumentException.class, () -> identifyFlagCard(null)); - assertThrows(IllegalArgumentException.class, () -> identifyFlagCard("")); + if (card.isPresent()) { + assertEquals(entry.getValue(), card.get()); + } else { + fail("Card is not present"); + } } -} \ No newline at end of file + } +} diff --git a/src/test/java/EmailValidatorTest.java b/src/test/java/EmailValidatorTest.java new file mode 100644 index 0000000..953bea2 --- /dev/null +++ b/src/test/java/EmailValidatorTest.java @@ -0,0 +1,63 @@ +import static org.junit.jupiter.api.Assertions.*; + +import io.github.multiform_validator.format.EmailValidator; +import io.github.multiform_validator.format.email.ValidateEmailBuilder; +import java.util.Collections; +import org.junit.jupiter.api.Test; + +class EmailValidatorTest { + @Test + void testValidateEmail() { + // Test with valid email + assertTrue(EmailValidator.validateEmail("foo@gmail.com")); + + // Test with invalid email + assertFalse(EmailValidator.validateEmail("foo@bar")); + + // Test with maxLength option + ValidateEmailBuilder options1 = new ValidateEmailBuilder(); + options1.setMaxLength(10); + assertFalse(EmailValidator.validateEmail("foo@gmail.com", options1)); + + // Test with country option + ValidateEmailBuilder options2 = new ValidateEmailBuilder(); + options2.setMaxLength(400); + options2.setCountry("br"); + assertTrue(EmailValidator.validateEmail("foo@gmail.com.br", options2)); + assertFalse(EmailValidator.validateEmail("foo@gmail.org", options2)); + + // Test with validDomains option + ValidateEmailBuilder options3 = new ValidateEmailBuilder(); + options3.setValidDomains(true); + assertTrue(EmailValidator.validateEmail("foo@gmail.com", options3)); + assertFalse(EmailValidator.validateEmail("foo@bar.com", options3)); + + // Test with validDomainsList option + ValidateEmailBuilder options4 = new ValidateEmailBuilder(); + options4.setValidDomainsList(Collections.singletonList("@voicemail.com")); + assertTrue(EmailValidator.validateEmail("foo@voicemail.com", options4)); + assertFalse(EmailValidator.validateEmail("foo@gmail.com", options4)); + + // Test with validDomains and validDomainsList options at the same time + ValidateEmailBuilder options5 = new ValidateEmailBuilder(); + options5.setValidDomains(true); + options5.setValidDomainsList(Collections.singletonList("@voicemail.com")); + assertThrows( + IllegalArgumentException.class, + () -> EmailValidator.validateEmail("foo@gmail.com", options5)); + + // Test with invalid domain + ValidateEmailBuilder options6 = new ValidateEmailBuilder(); + options6.setValidDomains(true); + assertFalse(EmailValidator.validateEmail("foo@bar.com", options6)); + } + + @Test + void testValidateEmailThrows() { + // Test with empty email + assertThrows(IllegalArgumentException.class, () -> EmailValidator.validateEmail("")); + + // Test with null email + assertThrows(IllegalArgumentException.class, () -> EmailValidator.validateEmail(null)); + } +} diff --git a/src/test/java/FileValidatorTest.java b/src/test/java/FileValidatorTest.java deleted file mode 100644 index c01098d..0000000 --- a/src/test/java/FileValidatorTest.java +++ /dev/null @@ -1,228 +0,0 @@ -import io.github.multiform_validator.FileValidator; -import org.junit.jupiter.api.Test; - -import java.io.File; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; - -class FileValidatorTest { - - // ############################################################################################################ - // ############################################################################################################ - // ############################################################################################################ - // Image file validation - final String imageBasePath = "src/test/java/assets/isValidImage"; - final String validImagePngPath = imageBasePath + "/valid/valid.png"; - final String validImageJpgPath = imageBasePath + "/valid/valid.jpg"; - final String validImageGifPath = imageBasePath + "/valid/valid.gif"; - final String validImageIcoPath = imageBasePath + "/valid/valid.ico"; - - final String invalidImagePngPath = imageBasePath + "/invalid/invalid.png"; - final String invalidImageJpgPath = imageBasePath + "/invalid/invalid.jpg"; - final String invalidImageGifPath = imageBasePath + "/invalid/invalid.gif"; - final String invalidImageIcoPath = imageBasePath + "/invalid/invalid.ico"; - - @Test - void testValidateImageWithExclusionExceptImageToBeValidate() { - File file = new File(validImageJpgPath); - List exclude = Arrays.asList("gif", "ico", "png"); - assertTrue(FileValidator.isValidImage(file, exclude)); - } - - @Test - void testValidateImageWithValidImageAndValidExclusion() { - File file = new File(validImagePngPath); - List exclude = Arrays.asList("gif", "ico", "png"); - assertFalse(FileValidator.isValidImage(file, exclude)); - } - - @Test - void testValidateImageWithValidImageAndInvalidExclusion() { - File file = new File(validImagePngPath); - List exclude = Arrays.asList("gif", "ico"); - assertTrue(FileValidator.isValidImage(file, exclude)); - } - - @Test - void testValidateImageWithValidPngImage() { - File file = new File(validImagePngPath); - assertTrue(FileValidator.isValidImage(file)); - } - - @Test - void testValidateImageWithInvalidPngImage() { - File file = new File(invalidImagePngPath); - assertFalse(FileValidator.isValidImage(file)); - } - - @Test - void testValidateImageWithValidJpgImage() { - File file = new File(validImageJpgPath); - assertTrue(FileValidator.isValidImage(file)); - } - - @Test - void testValidateWithInvalidJpgImage() { - File file = new File(invalidImageJpgPath); - assertFalse(FileValidator.isValidImage(file)); - } - - @Test - void testValidateImageWithValidGifImage() { - File file = new File(validImageGifPath); - assertTrue(FileValidator.isValidImage(file)); - } - - @Test - void testValidateImageWithInvalidGifImage() { - File file = new File(invalidImageGifPath); - assertFalse(FileValidator.isValidImage(file)); - } - - @Test - void testValidateImageWithValidIcoImage() { - File file = new File(validImageIcoPath); - assertTrue(FileValidator.isValidImage(file)); - } - - @Test - void testValidateImageWithInvalidIcoImage() { - File file = new File(invalidImageIcoPath); - assertFalse(FileValidator.isValidImage(file)); - } - - @Test - void testValidateImageWithNullFile() { - assertThrows(IllegalArgumentException.class, () -> FileValidator.isValidImage(null)); - } - - // ############################################################################################################ - // ############################################################################################################ - // ############################################################################################################ - // Audio file validation - - final String audioBasePath = "src/test/java/assets/isValidAudio"; - final String validAudioMp3Path = audioBasePath + "/valid/valid.mp3"; - final String validAudioWavPath = audioBasePath + "/valid/valid.wav"; - - final String invalidAudioMp3Path = audioBasePath + "/invalid/invalid.mp3"; - final String invalidAudioWavPath = audioBasePath + "/invalid/invalid.wav"; - - @Test - void testValidateAudioWithValidMp3Audio() { - File file = new File(validAudioMp3Path); - assertTrue(FileValidator.isValidAudio(file)); - } - - @Test - void testValidateAudioWithInvalidMp3Audio() { - File file = new File(invalidAudioMp3Path); - assertFalse(FileValidator.isValidAudio(file)); - } - - @Test - void testValidateAudioWithValidWavAudio() { - File file = new File(validAudioWavPath); - assertTrue(FileValidator.isValidAudio(file)); - } - - @Test - void testValidateAudioWithInvalidWavAudio() { - File file = new File(invalidAudioWavPath); - assertFalse(FileValidator.isValidAudio(file)); - } - - @Test - void testValidateAudioWithExclusionExceptAudioToBeValidate() { - File file = new File(validAudioWavPath); - List exclude = Collections.singletonList("mp3"); - assertTrue(FileValidator.isValidAudio(file, exclude)); - } - - @Test - void testValidateAudioWithValidAudioAndValidExclusion() { - File file = new File(validAudioMp3Path); - List exclude = Collections.singletonList("mp3"); - assertFalse(FileValidator.isValidAudio(file, exclude)); - } - - @Test - void testValidateAudioWithValidAudioAndInvalidExclusion() { - File file = new File(validAudioMp3Path); - List exclude = Collections.singletonList("wav"); - assertTrue(FileValidator.isValidAudio(file, exclude)); - } - - @Test - void testValidateExcludingAllAudios() { - File file = new File(validAudioMp3Path); - List exclude = Arrays.asList("wav", "mp3"); - assertFalse(FileValidator.isValidAudio(file, exclude)); - } - - @Test - void testValidateAudioWithNullFile() { - assertThrows(IllegalArgumentException.class, () -> FileValidator.isValidAudio(null)); - } - - // ############################################################################################################ - // ############################################################################################################ - // ############################################################################################################ - // Pdf file validation - - final String pdfBasePath = "src/test/java/assets/isValidPdf/"; - - final String validPdfPath = pdfBasePath + "valid.pdf"; - final String invalidPdfPath = pdfBasePath + "invalid.pdf"; - - @Test - void testValidatePdf() { - File file = new File(validPdfPath); - assertTrue(FileValidator.isValidPdf(file)); - } - - @Test - void testValidatePdfWithInvalidPdf() { - File file = new File(invalidPdfPath); - assertFalse(FileValidator.isValidPdf(file)); - } - - @Test - void testValidatePdfWithNullFile() { - assertThrows(IllegalArgumentException.class, () -> FileValidator.isValidPdf(null)); - } - - // ############################################################################################################ - // ############################################################################################################ - // ############################################################################################################ - // Txt file validation - - final String txtBasePath = "src/test/java/assets/isValidTxt"; - - final String validTxtPath = txtBasePath + "/valid.txt"; - final String invalidTxtPath = txtBasePath + "/invalid.txt"; - - @Test - void testValidateTxt() { - File file = new File(validTxtPath); - assertTrue(FileValidator.isValidTxt(file)); - } - - @Test - void testValidateTxtWithInvalidTxt() { - File file = new File(invalidTxtPath); - assertFalse(FileValidator.isValidTxt(file)); - } - - @Test - void testValidateTxtWithNullFile() { - assertThrows(IllegalArgumentException.class, () -> FileValidator.isValidTxt(null)); - } - - // ############################################################################################################ - // ############################################################################################################ - // ############################################################################################################ -} \ No newline at end of file diff --git a/src/test/java/ImageValidatorTest.java b/src/test/java/ImageValidatorTest.java new file mode 100644 index 0000000..85ca9a7 --- /dev/null +++ b/src/test/java/ImageValidatorTest.java @@ -0,0 +1,94 @@ +import static io.github.multiform_validator.file.ImageValidator.isValidImage; +import static org.junit.jupiter.api.Assertions.*; + +import java.io.File; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Test; + +class ImageValidatorTest { + final String imageBasePath = "src/test/java/assets/isValidImage"; + final String validImagePngPath = imageBasePath + "/valid/valid.png"; + final String validImageJpgPath = imageBasePath + "/valid/valid.jpg"; + final String validImageGifPath = imageBasePath + "/valid/valid.gif"; + final String validImageIcoPath = imageBasePath + "/valid/valid.ico"; + + final String invalidImagePngPath = imageBasePath + "/invalid/invalid.png"; + final String invalidImageJpgPath = imageBasePath + "/invalid/invalid.jpg"; + final String invalidImageGifPath = imageBasePath + "/invalid/invalid.gif"; + final String invalidImageIcoPath = imageBasePath + "/invalid/invalid.ico"; + + @Test + void testValidateImageWithExclusionExceptImageToBeValidate() { + File file = new File(validImageJpgPath); + List exclude = Arrays.asList("gif", "ico", "png"); + assertTrue(isValidImage(file, exclude)); + } + + @Test + void testValidateImageWithValidImageAndValidExclusion() { + File file = new File(validImagePngPath); + List exclude = Arrays.asList("gif", "ico", "png"); + assertFalse(isValidImage(file, exclude)); + } + + @Test + void testValidateImageWithValidImageAndInvalidExclusion() { + File file = new File(validImagePngPath); + List exclude = Arrays.asList("gif", "ico"); + assertTrue(isValidImage(file, exclude)); + } + + @Test + void testValidateImageWithValidPngImage() { + File file = new File(validImagePngPath); + assertTrue(isValidImage(file)); + } + + @Test + void testValidateImageWithInvalidPngImage() { + File file = new File(invalidImagePngPath); + assertFalse(isValidImage(file)); + } + + @Test + void testValidateImageWithValidJpgImage() { + File file = new File(validImageJpgPath); + assertTrue(isValidImage(file)); + } + + @Test + void testValidateWithInvalidJpgImage() { + File file = new File(invalidImageJpgPath); + assertFalse(isValidImage(file)); + } + + @Test + void testValidateImageWithValidGifImage() { + File file = new File(validImageGifPath); + assertTrue(isValidImage(file)); + } + + @Test + void testValidateImageWithInvalidGifImage() { + File file = new File(invalidImageGifPath); + assertFalse(isValidImage(file)); + } + + @Test + void testValidateImageWithValidIcoImage() { + File file = new File(validImageIcoPath); + assertTrue(isValidImage(file)); + } + + @Test + void testValidateImageWithInvalidIcoImage() { + File file = new File(invalidImageIcoPath); + assertFalse(isValidImage(file)); + } + + @Test + void testValidateImageWithNullFile() { + assertThrows(IllegalArgumentException.class, () -> isValidImage(null)); + } +} diff --git a/src/test/java/PDFValidatorTest.java b/src/test/java/PDFValidatorTest.java new file mode 100644 index 0000000..3203461 --- /dev/null +++ b/src/test/java/PDFValidatorTest.java @@ -0,0 +1,35 @@ +import static io.github.multiform_validator.file.FileValidator.isValidPdf; +import static org.junit.jupiter.api.Assertions.*; + +import java.io.File; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class PDFValidatorTest { + private String validPdfPath; + private String invalidPdfPath; + + @BeforeEach + void setUp() { + String pdfBasePath = "src/test/java/assets/isValidPdf/"; + validPdfPath = pdfBasePath + "valid.pdf"; + invalidPdfPath = pdfBasePath + "invalid.pdf"; + } + + @Test + void testValidatePdf() { + File file = new File(validPdfPath); + assertTrue(isValidPdf(file)); + } + + @Test + void testValidatePdfWithInvalidPdf() { + File file = new File(invalidPdfPath); + assertFalse(isValidPdf(file)); + } + + @Test + void testValidatePdfWithNullFile() { + assertThrows(IllegalArgumentException.class, () -> isValidPdf(null)); + } +} diff --git a/src/test/java/TextValidatorTest.java b/src/test/java/TextValidatorTest.java new file mode 100644 index 0000000..b90a7f4 --- /dev/null +++ b/src/test/java/TextValidatorTest.java @@ -0,0 +1,35 @@ +import static io.github.multiform_validator.file.FileValidator.isValidTxt; +import static org.junit.jupiter.api.Assertions.*; + +import java.io.File; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class TextValidatorTest { + private String validTxtPath; + private String invalidTxtPath; + + @BeforeEach + void setUp() { + String txtBasePath = "src/test/java/assets/isValidTxt"; + validTxtPath = txtBasePath + "/valid.txt"; + invalidTxtPath = txtBasePath + "/invalid.txt"; + } + + @Test + void testValidateTxt() { + File file = new File(validTxtPath); + assertTrue(isValidTxt(file)); + } + + @Test + void testValidateTxtWithInvalidTxt() { + File file = new File(invalidTxtPath); + assertFalse(isValidTxt(file)); + } + + @Test + void testValidateTxtWithNullFile() { + assertThrows(IllegalArgumentException.class, () -> isValidTxt(null)); + } +} diff --git a/src/test/java/UtilsTest.java b/src/test/java/UtilsTest.java index 173de20..458154a 100644 --- a/src/test/java/UtilsTest.java +++ b/src/test/java/UtilsTest.java @@ -1,78 +1,78 @@ -import io.github.multiform_validator.Utils; -import org.junit.jupiter.api.Test; +import static io.github.multiform_validator.format.EmailValidator.getOnlyEmail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import io.github.multiform_validator.format.email.OnlyEmailParams; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; - -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; class UtilsTest { - // ############################################################################################################## - // ############################################################################################################## - // ############################################################################################################## - // Test GetOnlyEmail - @Test - void testGetOnlyEmail() { - // Test with no email found - assertEquals("No email found", Utils.getOnlyEmail("This is a sample text", null)); - // Test with single email - assertEquals("test@example.com", Utils.getOnlyEmail("This is a sample text with email test@example.com", null)); + @Test + void testGetOnlyEmail() { + // Test with no email found + assertEquals("No email found", getOnlyEmail("This is a sample text", null)); + + // Test with single email + assertEquals( + "test@example.com", + getOnlyEmail("This is a sample text with email test@example.com", null)); - // Test with multiple emails - Utils.GetOnlyEmailOptionsParams options1 = new Utils.GetOnlyEmailOptionsParams(); - options1.setMultiple(true); - assertEquals( - new ArrayList<>(Arrays.asList("test1@example.com", "test2@example.com")), - Utils.getOnlyEmail("This is a sample text with emails test1@example.com and test2@example.com", options1) - ); + // Test with multiple emails + OnlyEmailParams options1 = new OnlyEmailParams(); + options1.setMultiple(true); + assertEquals( + new ArrayList<>(Arrays.asList("test1@example.com", "test2@example.com")), + getOnlyEmail( + "This is a sample text with emails test1@example.com and test2@example.com", options1)); - // Test with multiple emails and clean domain - Utils.GetOnlyEmailOptionsParams options2 = new Utils.GetOnlyEmailOptionsParams(); - options2.setMultiple(true); - options2.setCleanDomain(true); - assertEquals( - new ArrayList<>(Arrays.asList("test1@example.com", "test2@example.com")), - Utils.getOnlyEmail("This is a sample text with emails test1@example.comAWODI test2@example.comAWDOI awwdawd", options2) - ); + // Test with multiple emails and clean domain + OnlyEmailParams options2 = new OnlyEmailParams(); + options2.setMultiple(true); + options2.setCleanDomain(true); + assertEquals( + new ArrayList<>(Arrays.asList("test1@example.com", "test2@example.com")), + getOnlyEmail( + "This is a sample text with emails test1@example.comAWODI test2@example.comAWDOI awwdawd", + options2)); - // Test with multiple emails and clean domain and repeat email - Utils.GetOnlyEmailOptionsParams options3 = new Utils.GetOnlyEmailOptionsParams(); - options3.setMultiple(true); - options3.setCleanDomain(true); - options3.setRepeatEmail(true); - assertEquals( - new ArrayList<>(Arrays.asList("test1@example.com", "test1@example.com", "test2@example.com")), - Utils.getOnlyEmail("This is a sample text with emails test1@example.comASD test1@example.comASD blabla test2@example.com", options3) - ); + // Test with multiple emails and clean domain and repeat email + OnlyEmailParams options3 = new OnlyEmailParams(); + options3.setMultiple(true); + options3.setCleanDomain(true); + options3.setRepeatEmail(true); + assertEquals( + new ArrayList<>( + Arrays.asList("test1@example.com", "test1@example.com", "test2@example.com")), + getOnlyEmail( + "This is a sample text with emails test1@example.comASD test1@example.comASD blabla test2@example.com", + options3)); - // Test with multiple emails and repeated email however repeatEmail is false - Utils.GetOnlyEmailOptionsParams options4 = new Utils.GetOnlyEmailOptionsParams(); - options4.setMultiple(true); - options4.setCleanDomain(true); - options4.setRepeatEmail(false); - assertEquals( - new ArrayList<>(Arrays.asList("test1@example.com", "test2@example.com")), - Utils.getOnlyEmail("vails test1@example.comASD test1@example.comASD blabla test2@example.com", options4) - ); + // Test with multiple emails and repeated email however repeatEmail is false + OnlyEmailParams options4 = new OnlyEmailParams(); + options4.setMultiple(true); + options4.setCleanDomain(true); + options4.setRepeatEmail(false); + assertEquals( + new ArrayList<>(Arrays.asList("test1@example.com", "test2@example.com")), + getOnlyEmail( + "vails test1@example.comASD test1@example.comASD blabla test2@example.com", options4)); - // Test with clean domain as false - Utils.GetOnlyEmailOptionsParams options5 = new Utils.GetOnlyEmailOptionsParams(); - options5.setMultiple(true); - options5.setCleanDomain(false); - assertEquals( - new ArrayList<>(Arrays.asList("test1@example.comAAA", "test2@example.com.br")), - Utils.getOnlyEmail("vails test1@example.comAAA , test2@example.com.br yes no", options5) - ); + // Test with clean domain as false + OnlyEmailParams options5 = new OnlyEmailParams(); + options5.setMultiple(true); + options5.setCleanDomain(false); + assertEquals( + new ArrayList<>(Arrays.asList("test1@example.comAAA", "test2@example.com.br")), + getOnlyEmail("vails test1@example.comAAA , test2@example.com.br yes no", options5)); - // Test passing own clean domain - Utils.GetOnlyEmailOptionsParams options6 = new Utils.GetOnlyEmailOptionsParams(); - options6.setMultiple(true); - options6.setCleanDomain(Collections.singletonList(".own")); - assertEquals( - new ArrayList<>(Arrays.asList("test1@com.own", "test2@com.own")), - Utils.getOnlyEmail("vails test1@com.ownASDAW , test2@com.ownyes no", options6) - ); - } -} \ No newline at end of file + // Test passing own clean domain + OnlyEmailParams options6 = new OnlyEmailParams(); + options6.setMultiple(true); + options6.setCleanDomain(Collections.singletonList(".own")); + assertEquals( + new ArrayList<>(Arrays.asList("test1@com.own", "test2@com.own")), + getOnlyEmail("vails test1@com.ownASDAW , test2@com.ownyes no", options6)); + } +} diff --git a/src/test/java/ValidateTest.java b/src/test/java/ValidateTest.java deleted file mode 100644 index 36fbf78..0000000 --- a/src/test/java/ValidateTest.java +++ /dev/null @@ -1,66 +0,0 @@ -import io.github.multiform_validator.Validate; -import io.github.multiform_validator.Validate.ValidateEmailOptionsParams; -import org.junit.jupiter.api.Test; - -import java.util.Collections; - -import static org.junit.jupiter.api.Assertions.*; - -class ValidateTest { - // ############################################################################################################## - // ############################################################################################################## - // ############################################################################################################## - // Test ValidateEmail - @Test - void testValidateEmail() { - // Test with valid email - assertTrue(Validate.validateEmail("foo@gmail.com")); - - // Test with invalid email - assertFalse(Validate.validateEmail("foo@bar")); - - // Test with maxLength option - ValidateEmailOptionsParams options1 = new ValidateEmailOptionsParams(); - options1.setMaxLength(10); - assertFalse(Validate.validateEmail("foo@gmail.com", options1)); - - // Test with country option - ValidateEmailOptionsParams options2 = new ValidateEmailOptionsParams(); - options2.setMaxLength(400); - options2.setCountry("br"); - assertTrue(Validate.validateEmail("foo@gmail.com.br", options2)); - assertFalse(Validate.validateEmail("foo@gmail.org", options2)); - - // Test with validDomains option - ValidateEmailOptionsParams options3 = new ValidateEmailOptionsParams(); - options3.setValidDomains(true); - assertTrue(Validate.validateEmail("foo@gmail.com", options3)); - assertFalse(Validate.validateEmail("foo@bar.com", options3)); - - // Test with validDomainsList option - ValidateEmailOptionsParams options4 = new ValidateEmailOptionsParams(); - options4.setValidDomainsList(Collections.singletonList("@voicemail.com")); - assertTrue(Validate.validateEmail("foo@voicemail.com", options4)); - assertFalse(Validate.validateEmail("foo@gmail.com", options4)); - - // Test with validDomains and validDomainsList options at the same time - ValidateEmailOptionsParams options5 = new ValidateEmailOptionsParams(); - options5.setValidDomains(true); - options5.setValidDomainsList(Collections.singletonList("@voicemail.com")); - assertThrows(IllegalArgumentException.class, () -> Validate.validateEmail("foo@gmail.com", options5)); - - // Test with invalid domain - ValidateEmailOptionsParams options6 = new ValidateEmailOptionsParams(); - options6.setValidDomains(true); - assertFalse(Validate.validateEmail("foo@bar.com", options6)); - } - - @Test - void testValidateEmailThrows() { - // Test with empty email - assertThrows(IllegalArgumentException.class, () -> Validate.validateEmail("")); - - // Test with null email - assertThrows(IllegalArgumentException.class, () -> Validate.validateEmail(null)); - } -} \ No newline at end of file diff --git a/src/test/java/ValidatorTest.java b/src/test/java/ValidatorTest.java index ec89af2..401976c 100644 --- a/src/test/java/ValidatorTest.java +++ b/src/test/java/ValidatorTest.java @@ -1,340 +1,282 @@ -import io.github.multiform_validator.Validator; -import org.junit.jupiter.api.Test; - +import static io.github.multiform_validator.format.DateValidator.isDate; +import static io.github.multiform_validator.format.DateValidator.isTime; +import static io.github.multiform_validator.format.EmailValidator.isEmail; +import static io.github.multiform_validator.format.StringValidator.*; +import static io.github.multiform_validator.identity.AddressValidator.isCEP; +import static io.github.multiform_validator.identity.AddressValidator.isPostalCode; +import static io.github.multiform_validator.numeric.MachineValidator.isMACAddress; +import static io.github.multiform_validator.numeric.MachineValidator.isPort; +import static io.github.multiform_validator.numeric.NumberValidator.isDecimal; import static org.junit.jupiter.api.Assertions.*; -class ValidatorTest { - // ############################################################################################################ - // ############################################################################################################ - // ############################################################################################################ - // isAscii - @Test - void testIsAscii() { - assertTrue(Validator.isAscii("Hello World")); - assertTrue(Validator.isAscii("0123456789")); - assertTrue(Validator.isAscii("abcdefghijklmnopqrstuvwxyz")); - assertTrue(Validator.isAscii("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); - assertTrue(Validator.isAscii("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~")); - assertFalse(Validator.isAscii("こんにちは")); - assertFalse(Validator.isAscii("你好")); - assertFalse(Validator.isAscii("안녕하세요")); - assertFalse(Validator.isAscii("مرحبا")); - assertFalse(Validator.isAscii("नमस्ते")); - assertFalse(Validator.isAscii("สวัสดี")); - assertThrows(IllegalArgumentException.class, () -> Validator.isAscii(null)); - assertThrows(IllegalArgumentException.class, () -> Validator.isAscii("")); - } - - // ############################################################################################################ - // ############################################################################################################ - // ############################################################################################################ - // isBase64 - - @Test - void testIsBase64() { - assertTrue(Validator.isBase64("SGVsbG8gV29ybGQ=")); - assertTrue(Validator.isBase64("MTIzNDU2Nzg5")); - assertTrue(Validator.isBase64("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo=")); - assertTrue(Validator.isBase64("QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo=")); - assertFalse(Validator.isBase64("Hello World")); - assertFalse(Validator.isBase64("こんにちは")); - assertFalse(Validator.isBase64("你好")); - assertFalse(Validator.isBase64("안녕하세요")); - assertFalse(Validator.isBase64("مرحبا")); - assertThrows(IllegalArgumentException.class, () -> Validator.isBase64(null)); - assertThrows(IllegalArgumentException.class, () -> Validator.isBase64("")); - } - - // ############################################################################################################ - // ############################################################################################################ - // ############################################################################################################ - // isCEP - - @Test - void testIsCEP() { - assertTrue(Validator.isCEP("12345678")); - assertFalse(Validator.isCEP("1234567890")); - assertFalse(Validator.isCEP("abcdefgh")); - assertFalse(Validator.isCEP("1234567")); - assertTrue(Validator.isCEP("12345-678")); - } - - // ############################################################################################################ - // ############################################################################################################ - // ############################################################################################################ - // isDate - - @Test - void testIsDateTrue() { - // Valid date formats - assertTrue(Validator.isDate("2022-01-01")); // ISO 8601 (YYYY-MM-DD) - assertTrue(Validator.isDate("01/01/2022")); // Common US format (MM/DD/YYYY) - assertTrue(Validator.isDate("01-01-2022")); // Common EU format (DD-MM-YYYY) - assertTrue(Validator.isDate("2022/01/01")); // ISO alternate (YYYY/MM/DD) - assertTrue(Validator.isDate("01.01.2022")); // Format with dots (DD.MM.YYYY) - assertTrue(Validator.isDate("2022.01.01")); // Format with dots (YYYY.MM.DD) - assertTrue(Validator.isDate("01-Jan-2022")); // Format with abbreviated month (DD-MMM-YYYY) - assertTrue(Validator.isDate("01-January-2022")); // Format with full month name (DD-Month-YYYY) - assertTrue(Validator.isDate("01-Jan-22")); // Format with abbreviated month and two-digit year (DD-MMM-YY) - assertTrue(Validator.isDate("01-January-22")); // Format with full month name and two-digit year (DD-Month-YY) - } - - @Test - void testIsDateWithNumbersTrue() { - // Valid date-time formats - assertTrue(Validator.isDate("2022-01-01T10:15:30")); // ISO 8601 (YYYY-MM-DDTHH:MM:SS) - assertTrue(Validator.isDate("2022-01-01 10:15:30")); // Space-separated date and time - assertTrue(Validator.isDate("2022/01/01 10:15:30")); // Slash-separated date and time - assertTrue(Validator.isDate("01-01-2022 10:15:30")); // Hyphen-separated date and time (DD-MM-YYYY) - assertTrue(Validator.isDate("01.01.2022 10:15:30")); // Dot-separated date and time (DD.MM.YYYY) - assertTrue(Validator.isDate("2022.01.01 10:15:30")); // Dot-separated date and time (YYYY.MM.DD) - assertTrue(Validator.isDate("01-Jan-2022 10:15:30")); // Abbreviated month date and time (DD-MMM-YYYY) - assertTrue(Validator.isDate("01-January-2022 10:15:30")); // Full month name date and time (DD-Month-YYYY) - assertTrue(Validator.isDate("01-Jan-22 10:15:30")); // Abbreviated month and two-digit year date and time (DD-MMM-YY) - assertTrue(Validator.isDate("01-January-22 10:15:30")); // Full month name and two-digit year date and time (DD-Month-YY) - } - - @Test - void testIsDateWithNumbersFalse() { - // Invalid date-time formats - assertFalse(Validator.isDate("2022-13-01T10:15:30")); // Invalid month - assertFalse(Validator.isDate("2022-01-32T10:15:30")); // Invalid day - assertFalse(Validator.isDate("01-01-22T10:15:30")); // Invalid year format - assertFalse(Validator.isDate("2022-01-01T25:15:30")); // Invalid hour - assertFalse(Validator.isDate("2022-01-01T10:60:30")); // Invalid minute - assertFalse(Validator.isDate("2022-01-01T10:15:60")); // Invalid second - assertFalse(Validator.isDate("01-01-22 25:15:30")); // Invalid hour - assertFalse(Validator.isDate("01-01-22 10:60:30")); // Invalid minute - assertFalse(Validator.isDate("01-01-22 10:15:60")); // Invalid second - - // Null and empty string - assertThrows(IllegalArgumentException.class, () -> Validator.isDate(null)); - assertThrows(IllegalArgumentException.class, () -> Validator.isDate("")); - } - - @Test - void testIsDateFalse() { - // Invalid date formats - assertFalse(Validator.isDate("2022-13-01")); // Invalid month - assertFalse(Validator.isDate("2022-01-32")); // Invalid day - assertFalse(Validator.isDate("01-01-22")); // Invalid year format - assertFalse(Validator.isDate("abc-def-ghi")); // Invalid characters - assertFalse(Validator.isDate("01-01-22 10:15:30")); // Invalid format - assertFalse(Validator.isDate("01-01-22abc")); // Invalid format - - // Null and empty string - assertThrows(IllegalArgumentException.class, () -> Validator.isDate(null)); - assertThrows(IllegalArgumentException.class, () -> Validator.isDate("")); - } - - // ############################################################################################################ - // ############################################################################################################ - // ############################################################################################################ - // isDecimal - - @Test - void testIsDecimal() { - assertTrue(Validator.isDecimal("3.14")); - assertFalse(Validator.isDecimal("42")); - assertThrows(IllegalArgumentException.class, () -> Validator.isDecimal(null)); - assertThrows(IllegalArgumentException.class, () -> Validator.isDecimal("")); - } - - // ############################################################################################################ - // ############################################################################################################ - // ############################################################################################################ - // isEmail - - @Test - void testValidEmail() { - assertTrue(Validator.isEmail("foo@bar.com")); - assertTrue(Validator.isEmail("Foo@Bar.com")); - assertTrue(Validator.isEmail("foo@bar.com.br")); - } - - @Test - void testInvalidEmail1() { - assertFalse(Validator.isEmail("foo@bar")); - assertFalse(Validator.isEmail("1foo@bar.com")); - assertFalse(Validator.isEmail("foo@1bar.com")); - assertFalse(Validator.isEmail("foo@bar.1com")); - assertFalse(Validator.isEmail("foo.bar.com")); - assertFalse(Validator.isEmail("joaoaoao@gmail.com.com")); - assertFalse(Validator.isEmail("joao..@gmail.com")); - assertFalse(Validator.isEmail("joao.@gmail.com")); - assertFalse(Validator.isEmail("joao@@gmail.com")); - assertFalse(Validator.isEmail("joao@gmail..com")); - assertFalse(Validator.isEmail(".foo@bar.com")); - assertFalse(Validator.isEmail(",foo@bar.com")); - assertFalse(Validator.isEmail("!foo@bar.com")); - assertFalse(Validator.isEmail("@foo@bar.com")); - assertFalse(Validator.isEmail("#foo@bar.com")); - assertFalse(Validator.isEmail("$foo@bar.com")); - assertFalse(Validator.isEmail("foo@@bar.com")); - assertFalse(Validator.isEmail("foo@bar.com.br.br")); - assertFalse(Validator.isEmail("foo@bar.com.com.br.br")); - assertFalse(Validator.isEmail("foo@bar.com.com.br")); - } - - @Test - void testInvalidEmail2() { - assertFalse(Validator.isEmail("foo!@bar.com")); - assertFalse(Validator.isEmail("foo bar@baz.com")); - assertFalse(Validator.isEmail(" foo@bar.com")); - assertFalse(Validator.isEmail("foo@bar.com ")); - assertFalse(Validator.isEmail("foo..bar@baz.com")); - assertFalse(Validator.isEmail("foo@@bar.com")); - assertFalse(Validator.isEmail("foo@bar..com")); - assertFalse(Validator.isEmail("foo..bar@baz.com")); - assertFalse(Validator.isEmail("foo@bar.com..")); - assertFalse(Validator.isEmail("foo@bar..com")); - assertFalse(Validator.isEmail("foo..@bar.com")); - assertFalse(Validator.isEmail("foo@bar..com.")); - assertFalse(Validator.isEmail("foo..@bar..com.")); - assertFalse(Validator.isEmail("foo@bar.com...")); - assertFalse(Validator.isEmail("foo@bar!com")); - assertFalse(Validator.isEmail("foo!@bar.com")); - assertFalse(Validator.isEmail("foo@bar.c")); - assertFalse(Validator.isEmail("foo@bar.")); - assertFalse(Validator.isEmail("foo@bar")); - assertFalse(Validator.isEmail("foo@bar.")); - assertFalse(Validator.isEmail("foo@bar..")); - assertFalse(Validator.isEmail("foo@bar...")); - } - - @Test - void testEmptyEmail() { - assertFalse(Validator.isEmail("")); - } - - @Test - void testNullEmail() { - assertThrows(NullPointerException.class, () -> Validator.isEmail(null)); - } - - // ############################################################################################################ - // ############################################################################################################ - // ############################################################################################################ - // isMACAddress - - @Test - void testIsMACAddress() { - assertTrue(Validator.isMACAddress("00:1B:44:11:3A:B7")); - assertFalse(Validator.isMACAddress("Hello World")); - assertFalse(Validator.isMACAddress("00:1B:44:11:3A:B7:00")); - assertFalse(Validator.isMACAddress("00:1B:44:11:3A:B")); - assertThrows(IllegalArgumentException.class, () -> Validator.isMACAddress(null)); - assertThrows(IllegalArgumentException.class, () -> Validator.isMACAddress("")); - } - - // ############################################################################################################ - // ############################################################################################################ - // ############################################################################################################ - // isMD5 - - @Test - void testIsMD5() { - assertTrue(Validator.isMD5("d41d8cd98f00b204e9800998ecf8427e")); - assertFalse(Validator.isMD5("Hello World")); - assertThrows(IllegalArgumentException.class, () -> Validator.isMD5(null)); - assertThrows(IllegalArgumentException.class, () -> Validator.isMD5("")); - } - - // ############################################################################################################ - // ############################################################################################################ - // ############################################################################################################ - // isNumber - - @Test - void testIsNumber() { - assertTrue(Validator.isNumber("42")); - assertFalse(Validator.isNumber("Hello World")); - assertThrows(IllegalArgumentException.class, () -> Validator.isNumber(null)); - assertThrows(IllegalArgumentException.class, () -> Validator.isNumber("")); - } - - // ############################################################################################################ - // ############################################################################################################ - // ############################################################################################################ - // isPort - - @Test - void testIsPortInt() { - assertTrue(Validator.isPort(80)); - assertFalse(Validator.isPort(-1)); - assertFalse(Validator.isPort(65536)); - } - - @Test - void testIsPortString() { - assertTrue(Validator.isPort("80")); - assertFalse(Validator.isPort("-1")); - assertFalse(Validator.isPort("65536")); - assertThrows(IllegalArgumentException.class, () -> Validator.isPort(null)); - assertThrows(IllegalArgumentException.class, () -> Validator.isPort("")); - } - - // ############################################################################################################ - // ############################################################################################################ - // ############################################################################################################ - // isPostalCode - - @Test - void testIsPostalCode() { - assertTrue(Validator.isPostalCode("12345")); - assertFalse(Validator.isPostalCode("Hello World")); - assertFalse(Validator.isPostalCode("123456")); - assertThrows(IllegalArgumentException.class, () -> Validator.isPostalCode(null)); - assertThrows(IllegalArgumentException.class, () -> Validator.isPostalCode("")); - } - - // ############################################################################################################ - // ############################################################################################################ - // ############################################################################################################ - // isTime - - @Test - void testIsTimeTrue() { - assertTrue(Validator.isTime("12:34")); - assertTrue(Validator.isTime("12:34:56")); - assertTrue(Validator.isTime("16:30:00")); - assertTrue(Validator.isTime("23:59:59")); - assertTrue(Validator.isTime("00:00:00")); - assertTrue(Validator.isTime("00:00")); - assertTrue(Validator.isTime("23:59")); - assertTrue(Validator.isTime("8:30 PM")); - assertTrue(Validator.isTime("8:30 AM")); - assertTrue(Validator.isTime("8:30:00 PM")); - assertTrue(Validator.isTime("8:30:00 AM")); - } - - @Test - void testIsTimeFalse() { - assertFalse(Validator.isTime("Hello World")); - assertFalse(Validator.isTime("12:34:56:789")); - assertFalse(Validator.isTime("24:00:00")); - assertFalse(Validator.isTime("00:60:00")); - assertFalse(Validator.isTime("00:00:60")); - assertFalse(Validator.isTime("8:30 PMM")); - assertFalse(Validator.isTime("8:30 AMM")); - assertFalse(Validator.isTime("8:30:00 PMM")); - assertFalse(Validator.isTime("8:30:00 AMM")); - assertFalse(Validator.isTime("8:30:00 PM PM")); - assertFalse(Validator.isTime("8:30:00 AM AM")); - assertFalse(Validator.isTime("8:30:00 PM AM")); - assertFalse(Validator.isTime("8:30:00 AM PM")); - assertFalse(Validator.isTime("8:30:00 PM 8:30:00 AM")); - assertFalse(Validator.isTime("8:30:00 AM 8:30:00 PM")); - assertFalse(Validator.isTime("8:30:00 PM 8:30:00 PM")); - } +import org.junit.jupiter.api.Test; - @Test - void testIsTimeToThrow() { - assertThrows(IllegalArgumentException.class, () -> Validator.isTime(null)); - assertThrows(IllegalArgumentException.class, () -> Validator.isTime("")); - } +class ValidatorTest { - // ############################################################################################################ - // ############################################################################################################ - // ############################################################################################################ -} \ No newline at end of file + @Test + void testIsAscii() { + assertTrue(isAscii("Hello World")); + assertTrue(isAscii("0123456789")); + assertTrue(isAscii("abcdefghijklmnopqrstuvwxyz")); + assertTrue(isAscii("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); + assertTrue(isAscii("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~")); + assertFalse(isAscii("こんにちは")); + assertFalse(isAscii("你好")); + assertFalse(isAscii("안녕하세요")); + assertFalse(isAscii("مرحبا")); + assertFalse(isAscii("नमस्ते")); + assertFalse(isAscii("สวัสดี")); + assertThrows(IllegalArgumentException.class, () -> isAscii(null)); + assertThrows(IllegalArgumentException.class, () -> isAscii("")); + } + + @Test + void testIsBase64() { + assertTrue(isBase64("SGVsbG8gV29ybGQ=")); + assertTrue(isBase64("MTIzNDU2Nzg5")); + assertTrue(isBase64("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo=")); + assertTrue(isBase64("QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo=")); + assertFalse(isBase64("Hello World")); + assertFalse(isBase64("こんにちは")); + assertFalse(isBase64("你好")); + assertFalse(isBase64("안녕하세요")); + assertFalse(isBase64("مرحبا")); + assertThrows(IllegalArgumentException.class, () -> isBase64(null)); + assertThrows(IllegalArgumentException.class, () -> isBase64("")); + } + + @Test + void testIsCEP() { + assertTrue(isCEP("12345678")); + assertFalse(isCEP("1234567890")); + assertFalse(isCEP("abcdefgh")); + assertFalse(isCEP("1234567")); + assertTrue(isCEP("12345-678")); + } + + @Test + void testIsDateTrue() { + // Valid date formats + assertTrue(isDate("2022-01-01")); // ISO 8601 (YYYY-MM-DD) + assertTrue(isDate("01/01/2022")); // Common US format (MM/DD/YYYY) + assertTrue(isDate("01-01-2022")); // Common EU format (DD-MM-YYYY) + assertTrue(isDate("2022/01/01")); // ISO alternate (YYYY/MM/DD) + assertTrue(isDate("01.01.2022")); // Format with dots (DD.MM.YYYY) + assertTrue(isDate("2022.01.01")); // Format with dots (YYYY.MM.DD) + assertTrue(isDate("01-Jan-2022")); // Format with abbreviated month (DD-MMM-YYYY) + assertTrue(isDate("01-January-2022")); // Format with full month name (DD-Month-YYYY) + assertTrue(isDate("01-Jan-22")); // Format with abbreviated month and two-digit year (DD-MMM-YY) + assertTrue( + isDate("01-January-22")); // Format with full month name and two-digit year (DD-Month-YY) + } + + @Test + void testIsDateWithNumbersTrue() { + // Valid date-time formats + assertTrue(isDate("2022-01-01T10:15:30")); // ISO 8601 (YYYY-MM-DDTHH:MM:SS) + assertTrue(isDate("2022-01-01 10:15:30")); // Space-separated date and time + assertTrue(isDate("2022/01/01 10:15:30")); // Slash-separated date and time + assertTrue(isDate("01-01-2022 10:15:30")); // Hyphen-separated date and time (DD-MM-YYYY) + assertTrue(isDate("01.01.2022 10:15:30")); // Dot-separated date and time (DD.MM.YYYY) + assertTrue(isDate("2022.01.01 10:15:30")); // Dot-separated date and time (YYYY.MM.DD) + assertTrue(isDate("01-Jan-2022 10:15:30")); // Abbreviated month date and time (DD-MMM-YYYY) + assertTrue(isDate("01-January-2022 10:15:30")); // Full month name date and time (DD-Month-YYYY) + assertTrue(isDate("01-Jan-22 10:15:30")); // Abbreviated month and two-digit year date and time + // (DD-MMM-YY) + assertTrue( + isDate("01-January-22 10:15:30")); // Full month name and two-digit year date and time + // (DD-Month-YY) + } + + @Test + void testIsDateWithNumbersFalse() { + // Invalid date-time formats + assertFalse(isDate("2022-13-01T10:15:30")); // Invalid month + assertFalse(isDate("2022-01-32T10:15:30")); // Invalid day + assertFalse(isDate("01-01-22T10:15:30")); // Invalid year format + assertFalse(isDate("2022-01-01T25:15:30")); // Invalid hour + assertFalse(isDate("2022-01-01T10:60:30")); // Invalid minute + assertFalse(isDate("2022-01-01T10:15:60")); // Invalid second + assertFalse(isDate("01-01-22 25:15:30")); // Invalid hour + assertFalse(isDate("01-01-22 10:60:30")); // Invalid minute + assertFalse(isDate("01-01-22 10:15:60")); // Invalid second + + // Null and empty string + assertThrows(IllegalArgumentException.class, () -> isDate(null)); + assertThrows(IllegalArgumentException.class, () -> isDate("")); + } + + @Test + void testIsDateFalse() { + // Invalid date formats + assertFalse(isDate("2022-13-01")); // Invalid month + assertFalse(isDate("2022-01-32")); // Invalid day + assertFalse(isDate("01-01-22")); // Invalid year format + assertFalse(isDate("abc-def-ghi")); // Invalid characters + assertFalse(isDate("01-01-22 10:15:30")); // Invalid format + assertFalse(isDate("01-01-22abc")); // Invalid format + + // Null and empty string + assertThrows(IllegalArgumentException.class, () -> isDate(null)); + assertThrows(IllegalArgumentException.class, () -> isDate("")); + } + + @Test + void testIsDecimal() { + assertTrue(isDecimal("3.14")); + assertFalse(isDecimal("42")); + assertThrows(IllegalArgumentException.class, () -> isDecimal(null)); + assertThrows(IllegalArgumentException.class, () -> isDecimal("")); + } + + @Test + void testValidEmail() { + assertTrue(isEmail("foo@bar.com")); + assertTrue(isEmail("Foo@Bar.com")); + assertTrue(isEmail("foo@bar.com.br")); + } + + @Test + void testInvalidEmail1() { + assertFalse(isEmail("foo@bar")); + assertFalse(isEmail("1foo@bar.com")); + assertFalse(isEmail("foo@1bar.com")); + assertFalse(isEmail("foo@bar.1com")); + assertFalse(isEmail("foo.bar.com")); + assertFalse(isEmail("joaoaoao@gmail.com.com")); + assertFalse(isEmail("joao..@gmail.com")); + assertFalse(isEmail("joao.@gmail.com")); + assertFalse(isEmail("joao@@gmail.com")); + assertFalse(isEmail("joao@gmail..com")); + assertFalse(isEmail(".foo@bar.com")); + assertFalse(isEmail(",foo@bar.com")); + assertFalse(isEmail("!foo@bar.com")); + assertFalse(isEmail("@foo@bar.com")); + assertFalse(isEmail("#foo@bar.com")); + assertFalse(isEmail("$foo@bar.com")); + assertFalse(isEmail("foo@@bar.com")); + assertFalse(isEmail("foo@bar.com.br.br")); + assertFalse(isEmail("foo@bar.com.com.br.br")); + assertFalse(isEmail("foo@bar.com.com.br")); + } + + @Test + void testInvalidEmail2() { + assertFalse(isEmail("foo!@bar.com")); + assertFalse(isEmail("foo bar@baz.com")); + assertFalse(isEmail(" foo@bar.com")); + assertFalse(isEmail("foo@bar.com ")); + assertFalse(isEmail("foo..bar@baz.com")); + assertFalse(isEmail("foo@@bar.com")); + assertFalse(isEmail("foo@bar..com")); + assertFalse(isEmail("foo..bar@baz.com")); + assertFalse(isEmail("foo@bar.com..")); + assertFalse(isEmail("foo@bar..com")); + assertFalse(isEmail("foo..@bar.com")); + assertFalse(isEmail("foo@bar..com.")); + assertFalse(isEmail("foo..@bar..com.")); + assertFalse(isEmail("foo@bar.com...")); + assertFalse(isEmail("foo@bar!com")); + assertFalse(isEmail("foo!@bar.com")); + assertFalse(isEmail("foo@bar.c")); + assertFalse(isEmail("foo@bar.")); + assertFalse(isEmail("foo@bar")); + assertFalse(isEmail("foo@bar.")); + assertFalse(isEmail("foo@bar..")); + assertFalse(isEmail("foo@bar...")); + } + + @Test + void testEmptyEmail() { + assertFalse(isEmail("")); + } + + @Test + void testNullEmail() { + assertThrows(NullPointerException.class, () -> isEmail(null)); + } + + @Test + void testIsMACAddress() { + assertTrue(isMACAddress("00:1B:44:11:3A:B7")); + assertFalse(isMACAddress("Hello World")); + assertFalse(isMACAddress("00:1B:44:11:3A:B7:00")); + assertFalse(isMACAddress("00:1B:44:11:3A:B")); + assertThrows(IllegalArgumentException.class, () -> isMACAddress(null)); + assertThrows(IllegalArgumentException.class, () -> isMACAddress("")); + } + + @Test + void testIsMD5() { + assertTrue(isMD5("d41d8cd98f00b204e9800998ecf8427e")); + assertFalse(isMD5("Hello World")); + assertThrows(IllegalArgumentException.class, () -> isMD5(null)); + assertThrows(IllegalArgumentException.class, () -> isMD5("")); + } + + @Test + void testIsPortInt() { + assertTrue(isPort(80)); + assertFalse(isPort(-1)); + assertFalse(isPort(65536)); + } + + @Test + void testIsPortString() { + assertTrue(isPort("80")); + assertFalse(isPort("-1")); + assertFalse(isPort("65536")); + assertThrows(IllegalArgumentException.class, () -> isPort(null)); + assertThrows(IllegalArgumentException.class, () -> isPort("")); + } + + @Test + void testIsPostalCode() { + assertTrue(isPostalCode("12345")); + assertFalse(isPostalCode("Hello World")); + assertFalse(isPostalCode("123456")); + assertThrows(IllegalArgumentException.class, () -> isPostalCode(null)); + assertThrows(IllegalArgumentException.class, () -> isPostalCode("")); + } + + @Test + void testIsTimeTrue() { + assertTrue(isTime("12:34")); + assertTrue(isTime("12:34:56")); + assertTrue(isTime("16:30:00")); + assertTrue(isTime("23:59:59")); + assertTrue(isTime("00:00:00")); + assertTrue(isTime("00:00")); + assertTrue(isTime("23:59")); + assertTrue(isTime("8:30 PM")); + assertTrue(isTime("8:30 AM")); + assertTrue(isTime("8:30:00 PM")); + assertTrue(isTime("8:30:00 AM")); + } + + @Test + void testIsTimeFalse() { + assertFalse(isTime("Hello World")); + assertFalse(isTime("12:34:56:789")); + assertFalse(isTime("24:00:00")); + assertFalse(isTime("00:60:00")); + assertFalse(isTime("00:00:60")); + assertFalse(isTime("8:30 PMM")); + assertFalse(isTime("8:30 AMM")); + assertFalse(isTime("8:30:00 PMM")); + assertFalse(isTime("8:30:00 AMM")); + assertFalse(isTime("8:30:00 PM PM")); + assertFalse(isTime("8:30:00 AM AM")); + assertFalse(isTime("8:30:00 PM AM")); + assertFalse(isTime("8:30:00 AM PM")); + assertFalse(isTime("8:30:00 PM 8:30:00 AM")); + assertFalse(isTime("8:30:00 AM 8:30:00 PM")); + assertFalse(isTime("8:30:00 PM 8:30:00 PM")); + } + + @Test + void testIsTimeToThrow() { + assertThrows(IllegalArgumentException.class, () -> isTime(null)); + assertThrows(IllegalArgumentException.class, () -> isTime("")); + } +}