diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index fbc88f3..234bd55 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -2,17 +2,14 @@ ## Our Pledge -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, sex characteristics, gender identity and expression, -level of experience, education, socio-economic status, nationality, personal -appearance, race, religion, or sexual identity and orientation. +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making +participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, +disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, +socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards -Examples of behavior that contributes to creating a positive environment -include: +Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences @@ -22,53 +19,42 @@ include: Examples of unacceptable behavior by participants include: -* The use of sexualized language or imagery and unwelcome sexual attention or - advances +* The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting +* Publishing others' private information, such as a physical or electronic address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take +appropriate and fair corrective action in response to any instances of unacceptable behavior. -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, +issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any +contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. +This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the +project or its community. Examples of representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed representative at an online or offline +event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at vicky.thakor@javaquery.com. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at +vicky.thakor@javaquery.com. All complaints will be reviewed and investigated and will result in a response that is +deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with +regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. +Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent +repercussions as determined by other members of the project's leadership. ## Attribution -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available +at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org diff --git a/README.md b/README.md index b6637ec..264da4a 100644 --- a/README.md +++ b/README.md @@ -1,35 +1,56 @@ # JavaQuery Util Library + Welcome to the JavaQuery util library [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.javaquery/util/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.javaquery/util) # Overview -Goal is to remove repeated boler plate utility code from your project. This library offers util classes of following framework and objects. - -- Collections: Provides wide range of operation you perform on collection (List, Set and Map) interfaces like nullOrEmpty(Collection), nonNullNonEmpty(Collection), batches(List source, int batchSize), etc... -- Files: Provides wide range of operation you perform on java.io.File like createNewFile(T file), writeToFile(T file, String data), appendToFile(T file, String data, boolean appendNewLine), etc... -- Console: Provides replacement of System.out.println() using .log() and System.err.println() using error(). -- JFile: Extends java.io.File and provide some extra function on file like getExtension, read, write. -- JSONObject: Uses org.json.JSONObject and provides facility to optValue at any path in JSONObject, like items.item[0].batters.batter[2].available -- Strings: Provides wide range of operation you perform on java.lang.String like nullOrEmpty(String str), joinStrings(String separator, String... strings), removeNotSupportedASCIICharacters(String str), etc... -- DatePattern: Provides wide range of Date patterns commonly used worldwide like yyyyMMddHHmmss, yyyy-MM-dd HH:mm:ss'Z', yyyy-MM-dd'T'HH:mm:ss.SSSSSSS-HH:MM, etc... + +Goal is to remove repeated boler plate utility code from your project. This library offers util classes of following +framework and objects. + +- Collections: Provides wide range of operation you perform on collection (List, Set and Map) interfaces + like nullOrEmpty(Collection), nonNullNonEmpty(Collection), batches(List source, int + batchSize), etc... +- Files: Provides wide range of operation you perform on java.io.File like createNewFile(T + file), writeToFile(T file, String data), appendToFile(T file, String data, boolean + appendNewLine), etc... +- Console: Provides replacement of System.out.println() using .log() and + System.err.println() using error(). +- JFile: Extends java.io.File and provide some extra function on file like getExtension + , read, write. +- JSONObject: Uses org.json.JSONObject and provides facility to optValue at any path in JSONObject, + like items.item[0].batters.batter[2].available +- Strings: Provides wide range of operation you perform on java.lang.String like nullOrEmpty( + String str), joinStrings(String separator, String... strings), + removeNotSupportedASCIICharacters(String str), etc... +- DatePattern: Provides wide range of Date patterns commonly used worldwide like yyyyMMddHHmmss + , yyyy-MM-dd HH:mm:ss'Z', yyyy-MM-dd'T'HH:mm:ss.SSSSSSS-HH:MM, etc... - DateRange: Class can be used to store start-date and end-date. -- Dates: Provides wide range of operation you perform on java.util.Date like addInDate(Date date, int type, int amount), parse(String date, DatePattern datePattern, TimeZone timeZone), format(Date date, DatePattern datePattern, TimeZone timeZone), etc... -- Assert: Provides wide range of operation for Assertions like nonNull(Object object, Supplier exceptionSupplier), isTrue(boolean expression, Supplier exceptionSupplier), nonNullNonEmpty(Collection collection, Supplier exceptionSupplier), etc... -- Objects: Provides wide range of operation on java.lang.Object like isNull(Object obj), nonNull(Object obj). -- Regex: Provides wide range of operation using regular expression like isNumber(String value), isAlphaNumeric(String value), isValidEmail(String value). +- Dates: Provides wide range of operation you perform on java.util.Date like addInDate(Date + date, int type, int amount), parse(String date, DatePattern datePattern, TimeZone timeZone) + , format(Date date, DatePattern datePattern, TimeZone timeZone), etc... +- Assert: Provides wide range of operation for Assertions like nonNull(Object object, Supplier + exceptionSupplier), isTrue(boolean expression, Supplier exceptionSupplier), + nonNullNonEmpty(Collection collection, Supplier exceptionSupplier), etc... +- Objects: Provides wide range of operation on java.lang.Object like isNull(Object obj) + , nonNull(Object obj). +- Regex: Provides wide range of operation using regular expression like isNumber(String value) + , isAlphaNumeric(String value), isValidEmail(String value). - UniqueIdGenerator: Generate unique time based random alphanumeric string like Firebase keys. # Maven + ``` com.javaquery util - 1.0.4 + 1.0.5 ``` # Gradle + ``` -implementation 'com.javaquery:util:1.0.4' +implementation 'com.javaquery:util:1.0.5' ``` diff --git a/build.gradle b/build.gradle index b9f64a2..2e23282 100644 --- a/build.gradle +++ b/build.gradle @@ -5,7 +5,7 @@ plugins { } group 'com.javaquery' -version '1.0.4' +version '1.0.5' repositories { mavenCentral() @@ -27,6 +27,17 @@ java { withSourcesJar() } +jar { + manifest { + attributes( + 'Built-By': "Vicky Thakor", + 'Created-By': "Gradle ${gradle.gradleVersion}", + 'Build-Jdk': "${System.properties['java.version']} (${System.properties['java.vendor']} ${System.properties['java.vm.version']})", + 'Import-Package': "org.json,org.slf4j,*" + ) + } +} + publishing { publications { mavenJava(MavenPublication) { diff --git a/settings.xml b/settings.xml index 8242ca3..c9c093b 100644 --- a/settings.xml +++ b/settings.xml @@ -1,15 +1,15 @@ - - - - ossrh - ${env.MAVEN_USERNAME} - ${env.MAVEN_CENTRAL_TOKEN} - - - gpg.passphrase - ${env.MAVEN_GPG_PASSPHRASE} - - + + + + ossrh + ${env.MAVEN_USERNAME} + ${env.MAVEN_CENTRAL_TOKEN} + + + gpg.passphrase + ${env.MAVEN_GPG_PASSPHRASE} + + diff --git a/src/main/java/com/javaquery/util/Assert.java b/src/main/java/com/javaquery/util/Assert.java index 202ac54..78987e6 100644 --- a/src/main/java/com/javaquery/util/Assert.java +++ b/src/main/java/com/javaquery/util/Assert.java @@ -7,133 +7,149 @@ import java.util.function.Supplier; /** - * {@code Assert} is a collection of utility methods that helps asserting conditions and throw exception if condition fails + * {@code Assert} is a collection of utility methods that helps asserting conditions and throw + * exception if condition fails * * @author Harshit * @since 1.0 */ public final class Assert { - private Assert() { - } + private Assert() {} - /** - * Assert that {@code object} is {@code not null}. - * - * @param object object to check - * @param Type of the exception to be thrown - * @param exceptionSupplier supplier of a exception to be thrown - * @throws T if {@code object} is {@code null} - * @throws NullPointerException if {@code object} is {@code null} and {@code exceptionSupplier} is {@code null} - */ - public static void nonNull(Object object, Supplier exceptionSupplier) throws T { - if (Objects.isNull(object)) { - throw exceptionSupplier.get(); - } + /** + * Assert that {@code object} is {@code not null}. + * + * @param object object to check + * @param Type of the exception to be thrown + * @param exceptionSupplier supplier of a exception to be thrown + * @throws T if {@code object} is {@code null} + * @throws NullPointerException if {@code object} is {@code null} and {@code exceptionSupplier} is + * {@code null} + */ + public static void nonNull(Object object, Supplier exceptionSupplier) + throws T { + if (Objects.isNull(object)) { + throw exceptionSupplier.get(); } + } - /** - * Assert that {@code object} is {@code null}. - * - * @param object object to check - * @param Type of the exception to be thrown - * @param exceptionSupplier supplier of a exception to throw - * @throws T if {@code object} is {@code not null} - * @throws NullPointerException if {@code object} is {@code not null} and {@code exceptionSupplier} is {@code null} - */ - public static void isNull(Object object, Supplier exceptionSupplier) throws T { - if (Objects.nonNull(object)) { - throw exceptionSupplier.get(); - } + /** + * Assert that {@code object} is {@code null}. + * + * @param object object to check + * @param Type of the exception to be thrown + * @param exceptionSupplier supplier of a exception to throw + * @throws T if {@code object} is {@code not null} + * @throws NullPointerException if {@code object} is {@code not null} and {@code + * exceptionSupplier} is {@code null} + */ + public static void isNull(Object object, Supplier exceptionSupplier) + throws T { + if (Objects.nonNull(object)) { + throw exceptionSupplier.get(); } + } - /** - * Assert that {@code expression} is {@code true}. - * - * @param expression expression to check - * @param Type of the exception to be thrown - * @param exceptionSupplier supplier of a exception to throw - * @throws T if {@code expression} is {@code false} - * @throws NullPointerException if {@code expression} is {@code false} and {@code exceptionSupplier} is {@code null} - */ - public static void isTrue(boolean expression, Supplier exceptionSupplier) throws T { - if (!expression) { - throw exceptionSupplier.get(); - } + /** + * Assert that {@code expression} is {@code true}. + * + * @param expression expression to check + * @param Type of the exception to be thrown + * @param exceptionSupplier supplier of a exception to throw + * @throws T if {@code expression} is {@code false} + * @throws NullPointerException if {@code expression} is {@code false} and {@code + * exceptionSupplier} is {@code null} + */ + public static void isTrue(boolean expression, Supplier exceptionSupplier) + throws T { + if (!expression) { + throw exceptionSupplier.get(); } + } - /** - * Assert that {@code expression} is {@code false}. - * - * @param expression expression to check - * @param Type of the exception to be thrown - * @param exceptionSupplier supplier of a exception to throw - * @throws T if {@code expression} is {@code true} - * @throws NullPointerException if {@code expression} is {@code true} and {@code exceptionSupplier} is {@code null} - */ - public static void isFalse(boolean expression, Supplier exceptionSupplier) throws T { - if (expression) { - throw exceptionSupplier.get(); - } + /** + * Assert that {@code expression} is {@code false}. + * + * @param expression expression to check + * @param Type of the exception to be thrown + * @param exceptionSupplier supplier of a exception to throw + * @throws T if {@code expression} is {@code true} + * @throws NullPointerException if {@code expression} is {@code true} and {@code + * exceptionSupplier} is {@code null} + */ + public static void isFalse( + boolean expression, Supplier exceptionSupplier) throws T { + if (expression) { + throw exceptionSupplier.get(); } + } - /** - * Assert that {@code collection} is {@code not null} and {@code not empty}. - * - * @param collection collection to check - * @param Type of the exception to be thrown - * @param exceptionSupplier supplier of a exception to throw - * @throws T if {@code collection} is {@code null} or {@code empty} - * @throws NullPointerException if {@code collection} is {@code null} or {@code empty} and {@code exceptionSupplier} is {@code null} - */ - public static void nonNullNonEmpty(Collection collection, Supplier exceptionSupplier) throws T { - if (Collections.nullOrEmpty(collection)) { - throw exceptionSupplier.get(); - } + /** + * Assert that {@code collection} is {@code not null} and {@code not empty}. + * + * @param collection collection to check + * @param Type of the exception to be thrown + * @param exceptionSupplier supplier of a exception to throw + * @throws T if {@code collection} is {@code null} or {@code empty} + * @throws NullPointerException if {@code collection} is {@code null} or {@code empty} and {@code + * exceptionSupplier} is {@code null} + */ + public static void nonNullNonEmpty( + Collection collection, Supplier exceptionSupplier) throws T { + if (Collections.nullOrEmpty(collection)) { + throw exceptionSupplier.get(); } + } - /** - * Assert that {@code collection} is {@code null} or {@code empty}. - * - * @param collection collection to check - * @param Type of the exception to be thrown - * @param exceptionSupplier supplier of a exception to throw - * @throws T if {@code collection} is {@code not null} and {@code not empty} - * @throws NullPointerException if {@code collection} is {@code not null} and {@code not empty} and {@code exceptionSupplier} is {@code null} - */ - public static void nullOrEmpty(Collection collection, Supplier exceptionSupplier) throws T { - if (Collections.nonNullNonEmpty(collection)) { - throw exceptionSupplier.get(); - } + /** + * Assert that {@code collection} is {@code null} or {@code empty}. + * + * @param collection collection to check + * @param Type of the exception to be thrown + * @param exceptionSupplier supplier of a exception to throw + * @throws T if {@code collection} is {@code not null} and {@code not empty} + * @throws NullPointerException if {@code collection} is {@code not null} and {@code not empty} + * and {@code exceptionSupplier} is {@code null} + */ + public static void nullOrEmpty( + Collection collection, Supplier exceptionSupplier) throws T { + if (Collections.nonNullNonEmpty(collection)) { + throw exceptionSupplier.get(); } + } - /** - * Assert that {@code map} is {@code not null} and {@code not empty}. - * - * @param map map to check - * @param Type of the exception to be thrown - * @param exceptionSupplier supplier of a exception to throw - * @throws T if {@code map} is {@code null} or {@code empty} - * @throws NullPointerException if {@code map} is {@code null} or {@code empty} and {@code exceptionSupplier} is {@code null} - */ - public static void nonNullNonEmptyMap(Map map, Supplier exceptionSupplier) throws T { - if (Collections.nullOrEmpty(map)) { - throw exceptionSupplier.get(); - } + /** + * Assert that {@code map} is {@code not null} and {@code not empty}. + * + * @param map map to check + * @param Type of the exception to be thrown + * @param exceptionSupplier supplier of a exception to throw + * @throws T if {@code map} is {@code null} or {@code empty} + * @throws NullPointerException if {@code map} is {@code null} or {@code empty} and {@code + * exceptionSupplier} is {@code null} + */ + public static void nonNullNonEmptyMap( + Map map, Supplier exceptionSupplier) throws T { + if (Collections.nullOrEmpty(map)) { + throw exceptionSupplier.get(); } + } - /** - * Assert that {@code map} is {@code null} or {@code empty}. - * - * @param map map to check - * @param Type of the exception to be thrown - * @param exceptionSupplier supplier of a exception to throw - * @throws T if {@code map} is {@code not null} and {@code not empty} - * @throws NullPointerException if {@code map} is {@code not null} and {@code not empty} and {@code exceptionSupplier} is {@code null} - */ - public static void nullOrEmptyMap(Map map, Supplier exceptionSupplier) throws T { - if (Collections.nonNullNonEmpty(map)) { - throw exceptionSupplier.get(); - } + /** + * Assert that {@code map} is {@code null} or {@code empty}. + * + * @param map map to check + * @param Type of the exception to be thrown + * @param exceptionSupplier supplier of a exception to throw + * @throws T if {@code map} is {@code not null} and {@code not empty} + * @throws NullPointerException if {@code map} is {@code not null} and {@code not empty} and + * {@code exceptionSupplier} is {@code null} + */ + public static void nullOrEmptyMap( + Map map, Supplier exceptionSupplier) throws T { + if (Collections.nonNullNonEmpty(map)) { + throw exceptionSupplier.get(); } + } } diff --git a/src/main/java/com/javaquery/util/Objects.java b/src/main/java/com/javaquery/util/Objects.java index d9d4345..973fdfe 100644 --- a/src/main/java/com/javaquery/util/Objects.java +++ b/src/main/java/com/javaquery/util/Objects.java @@ -6,30 +6,41 @@ */ public final class Objects { - private Objects() { - } + private Objects() {} - /** - * Returns {@code true} if the provided reference is {@code null} otherwise - * returns {@code false}. - * - * @param obj a reference to be checked against {@code null} - * @return {@code true} if the provided reference is {@code null} otherwise - * {@code false} - */ - public static boolean isNull(Object obj) { - return obj == null; - } + /** + * Returns {@code true} if the provided reference is {@code null} otherwise returns {@code false}. + * + * @param obj a reference to be checked against {@code null} + * @return {@code true} if the provided reference is {@code null} otherwise {@code false} + */ + public static boolean isNull(Object obj) { + return obj == null; + } - /** - * Returns {@code true} if the provided reference is non-{@code null} - * otherwise returns {@code false}. - * - * @param obj a reference to be checked against {@code null} - * @return {@code true} if the provided reference is non-{@code null} - * otherwise {@code false} - */ - public static boolean nonNull(Object obj) { - return obj != null; - } + /** + * Returns {@code true} if the provided reference is non-{@code null} otherwise returns {@code + * false}. + * + * @param obj a reference to be checked against {@code null} + * @return {@code true} if the provided reference is non-{@code null} otherwise {@code false} + */ + public static boolean nonNull(Object obj) { + return obj != null; + } + + /** + * Returns {@code true} if the arguments are equal to each other and {@code false} otherwise. + * Consequently, if both arguments are {@code null}, {@code true} is returned and if exactly one + * argument is {@code null}, {@code false} is returned. Otherwise, equality is determined by using + * the {@link Object#equals equals} method of the first argument. + * + * @param a an object + * @param b an object to be compared with {@code a} for equality + * @return {@code true} if the arguments are equal to each other and {@code false} otherwise + * @see Object#equals(Object) + */ + public static boolean equals(Object a, Object b) { + return (a == b) || (a != null && a.equals(b)); + } } diff --git a/src/main/java/com/javaquery/util/Regex.java b/src/main/java/com/javaquery/util/Regex.java index a966c9e..1996e08 100644 --- a/src/main/java/com/javaquery/util/Regex.java +++ b/src/main/java/com/javaquery/util/Regex.java @@ -8,48 +8,45 @@ */ public final class Regex { - public static final String REGEX_NUMBER = "^-?[0-9]\\d*(\\.\\d+)?$"; - public static final String REGEX_ALPHA_NUMERIC = "^[a-zA-Z0-9]*$"; - public static final String REGEX_EMAIL = - "^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))[^_@!*]*?$"; - public static final Pattern EMAIL_PATTERN = Pattern.compile(REGEX_EMAIL); + public static final String REGEX_NUMBER = "^-?[0-9]\\d*(\\.\\d+)?$"; + public static final String REGEX_ALPHA_NUMERIC = "^[a-zA-Z0-9]*$"; + public static final String REGEX_EMAIL = + "^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))[^_@!*]*?$"; + public static final Pattern EMAIL_PATTERN = Pattern.compile(REGEX_EMAIL); - private Regex() { - } + private Regex() {} - /** - * Returns {@code true} if the provided String is valid number otherwise - * returns {@code false}. - * - * @param value a String to be checked against number regular expression - * @return Returns {@code true} if the provided String is valid number otherwise - * returns {@code false}. - */ - public static boolean isNumber(String value) { - return Objects.nonNull(value) && value.matches(Regex.REGEX_NUMBER); - } + /** + * Returns {@code true} if the provided String is valid number otherwise returns {@code false}. + * + * @param value a String to be checked against number regular expression + * @return Returns {@code true} if the provided String is valid number otherwise returns {@code + * false}. + */ + public static boolean isNumber(String value) { + return Objects.nonNull(value) && value.matches(Regex.REGEX_NUMBER); + } - /** - * Returns {@code true} if the provided String is valid alpha numeric otherwise - * returns {@code false}. - * - * @param value a String to be checked against alpha numeric regular expression - * @return Returns {@code true} if the provided String is valid alpha numeric otherwise - * returns {@code false}. - */ - public static boolean isAlphaNumeric(String value) { - return Objects.nonNull(value) && value.matches(Regex.REGEX_ALPHA_NUMERIC); - } + /** + * Returns {@code true} if the provided String is valid alpha numeric otherwise returns {@code + * false}. + * + * @param value a String to be checked against alpha numeric regular expression + * @return Returns {@code true} if the provided String is valid alpha numeric otherwise returns + * {@code false}. + */ + public static boolean isAlphaNumeric(String value) { + return Objects.nonNull(value) && value.matches(Regex.REGEX_ALPHA_NUMERIC); + } - /** - * Returns {@code true} if the provided String is valid email otherwise - * returns {@code false}. - * - * @param value a String to be checked against email regular expression - * @return Returns {@code true} if the provided String is valid email otherwise - * returns {@code false}. - */ - public static boolean isValidEmail(String value) { - return Objects.nonNull(value) && Regex.EMAIL_PATTERN.matcher(value).matches(); - } + /** + * Returns {@code true} if the provided String is valid email otherwise returns {@code false}. + * + * @param value a String to be checked against email regular expression + * @return Returns {@code true} if the provided String is valid email otherwise returns {@code + * false}. + */ + public static boolean isValidEmail(String value) { + return Objects.nonNull(value) && Regex.EMAIL_PATTERN.matcher(value).matches(); + } } diff --git a/src/main/java/com/javaquery/util/UniqueIdGenerator.java b/src/main/java/com/javaquery/util/UniqueIdGenerator.java index 43a13c6..4af23e3 100644 --- a/src/main/java/com/javaquery/util/UniqueIdGenerator.java +++ b/src/main/java/com/javaquery/util/UniqueIdGenerator.java @@ -6,61 +6,61 @@ */ public class UniqueIdGenerator { - // Modeled after base64 web-safe chars, but ordered by ASCII. - private final static String PUSH_CHARS = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"; - // We generate 72-bits of randomness which get turned into 12 characters and - // appended to the timestamp to prevent collisions with other clients. We store the last - // characters we generated because in the event of a collision, we'll use those same - // characters except "incremented" by one. - private static final int[] LAST_RAND_CHARS = new int[72]; - // Timestamp of last push, used to prevent local collisions if you push twice in one ms. - private static long LAST_PUSH_TIME = 0L; + // Modeled after base64 web-safe chars, but ordered by ASCII. + private static final String PUSH_CHARS = + "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"; + // We generate 72-bits of randomness which get turned into 12 characters and + // appended to the timestamp to prevent collisions with other clients. We store the last + // characters we generated because in the event of a collision, we'll use those same + // characters except "incremented" by one. + private static final int[] LAST_RAND_CHARS = new int[72]; + // Timestamp of last push, used to prevent local collisions if you push twice in one ms. + private static long LAST_PUSH_TIME = 0L; - private UniqueIdGenerator() { - } - - public static synchronized String generate() { - long now = System.currentTimeMillis(); - boolean duplicateTime = now == LAST_PUSH_TIME; - LAST_PUSH_TIME = now; + private UniqueIdGenerator() {} - char[] timeStampChars = new char[8]; - for (int i = 7; i >= 0; i--) { - timeStampChars[i] = PUSH_CHARS.charAt((int) (now % 64)); - now = (long) Math.floor((double) (now / 64)); - } + public static synchronized String generate() { + long now = System.currentTimeMillis(); + boolean duplicateTime = now == LAST_PUSH_TIME; + LAST_PUSH_TIME = now; - if (now != 0) { - throw new AssertionError("We should have converted the entire timestamp."); - } + char[] timeStampChars = new char[8]; + for (int i = 7; i >= 0; i--) { + timeStampChars[i] = PUSH_CHARS.charAt((int) (now % 64)); + now = (long) Math.floor((double) (now / 64)); + } - StringBuilder id = new StringBuilder(20); - for (char c : timeStampChars) { - id.append(c); - } + if (now != 0) { + throw new AssertionError("We should have converted the entire timestamp."); + } - if (!duplicateTime) { - for (int i = 0; i < 12; i++) { - LAST_RAND_CHARS[i] = (int) Math.floor(Double.valueOf(Math.random() * 64).intValue()); - } - } else { - // If the timestamp hasn't changed since last push, use the same random number, - //except incremented by 1. - int i; - for (i = 11; i >= 0 && LAST_RAND_CHARS[i] == 63; i--) { - LAST_RAND_CHARS[i] = 0; - } - LAST_RAND_CHARS[i]++; - } + StringBuilder id = new StringBuilder(20); + for (char c : timeStampChars) { + id.append(c); + } - for (int i = 0; i < 12; i++) { - id.append(PUSH_CHARS.charAt(LAST_RAND_CHARS[i])); - } + if (!duplicateTime) { + for (int i = 0; i < 12; i++) { + LAST_RAND_CHARS[i] = (int) Math.floor(Double.valueOf(Math.random() * 64).intValue()); + } + } else { + // If the timestamp hasn't changed since last push, use the same random number, + // except incremented by 1. + int i; + for (i = 11; i >= 0 && LAST_RAND_CHARS[i] == 63; i--) { + LAST_RAND_CHARS[i] = 0; + } + LAST_RAND_CHARS[i]++; + } - if (id.length() != 20) { - throw new AssertionError("Length should be 20."); - } + for (int i = 0; i < 12; i++) { + id.append(PUSH_CHARS.charAt(LAST_RAND_CHARS[i])); + } - return id.substring(1); + if (id.length() != 20) { + throw new AssertionError("Length should be 20."); } + + return id.substring(1); + } } diff --git a/src/main/java/com/javaquery/util/collection/Collections.java b/src/main/java/com/javaquery/util/collection/Collections.java index 34661c1..9f50cf0 100644 --- a/src/main/java/com/javaquery/util/collection/Collections.java +++ b/src/main/java/com/javaquery/util/collection/Collections.java @@ -16,223 +16,211 @@ */ public final class Collections { - private Collections() { + private Collections() {} + + /** + * Returns {@code true} if the provided Collection [List, Set] is {@code null} or empty otherwise + * returns {@code false}. + * + * @param collection a Collection [List, Set] to be checked against {@code null} or empty + * @return {@code true} if the provided Collection [List, Set] is {@code null} or empty otherwise + * {@code false} + */ + public static boolean nullOrEmpty(Collection collection) { + return Objects.isNull(collection) || collection.isEmpty(); + } + + /** + * Returns {@code true} if the provided Collection [List, Set] is non-{@code null} and non-empty + * otherwise returns {@code false}. + * + * @param collection a Collection [List, Set] to be checked against non-{@code null} and non-empty + * @return {@code true} if the provided Collection [List, Set] is non-{@code null} and non-empty + * otherwise {@code false} + */ + public static boolean nonNullNonEmpty(Collection collection) { + return Objects.nonNull(collection) && !collection.isEmpty(); + } + + /** + * Returns {@code true} if the provided Map is {@code null} and empty otherwise returns {@code + * false}. + * + * @param map a Map to be checked against {@code null} or empty + * @return {@code true} if the provided Map is {@code null} and empty otherwise * returns {@code + * false} + */ + public static boolean nullOrEmpty(Map map) { + return Objects.isNull(map) || map.isEmpty(); + } + + /** + * Returns {@code true} if the provided Map is non-{@code null} and non-empty otherwise returns + * {@code false}. + * + * @param map a Map to be checked against non-{@code null} and non-empty + * @return {@code true} if the provided Map is non-{@code null} and non-empty otherwise {@code + * false} + */ + public static boolean nonNullNonEmpty(Map map) { + return Objects.nonNull(map) && !map.isEmpty(); + } + + /** + * Returns stream of batched List from original List by given batch size. + * + * @param source a List to be batched + * @param batchSize size of batch you want + * @param the type of List to be returned. + * @return Returns stream of batched List from original List by given batch size. + *

reference: + * http://stackoverflow.com/questions/12026885/common-util-to-break-a-list-into-batch + */ + public static Stream> batches(List source, int batchSize) { + if (Objects.isNull(source)) throw new IllegalArgumentException("source can not be null"); + + int size = source.size(); + if (batchSize < 0) { + throw new IllegalArgumentException("batchSize can not be negative"); + } else if (batchSize == 0 && size != 0) { + return Stream.of(source); } - - /** - * Returns {@code true} if the provided Collection [List, Set] is {@code null} or empty otherwise - * returns {@code false}. - * - * @param collection a Collection [List, Set] to be checked against {@code null} or empty - * @return {@code true} if the provided Collection [List, Set] is {@code null} or empty - * otherwise {@code false} - */ - public static boolean nullOrEmpty(Collection collection) { - return Objects.isNull(collection) || collection.isEmpty(); + if (size <= 0) return Stream.empty(); + int fullChunks = (size - 1) / batchSize; + return IntStream.range(0, fullChunks + 1) + .mapToObj(n -> source.subList(n * batchSize, n == fullChunks ? size : (n + 1) * batchSize)); + } + + /** + * Note: Code imported from apache commons collection + * + *

Returns {@code true} iff the given {@link Collection}s contain exactly the same elements + * with exactly the same cardinalities.

+ * + *

That is, iff the cardinality of e in a is equal to the cardinality of e + * in b, for each element e in a or b

. + * + * @param collectionOne the first collection, must not be null + * @param collectionTwo the second collection, must not be null + * @return {@code true} iff the collections contain the same elements with the same cardinalities. + * @throws NullPointerException if either collection is null + * @since 1.0.3 + */ + public static boolean isCollectionEqual( + final Collection collectionOne, final Collection collectionTwo) { + Assert.nonNull(collectionOne, NullPointerException::new); + Assert.nonNull(collectionTwo, NullPointerException::new); + + if (collectionOne.size() != collectionTwo.size()) { + return false; } - /** - * Returns {@code true} if the provided Collection [List, Set] is non-{@code null} and non-empty otherwise - * returns {@code false}. - * - * @param collection a Collection [List, Set] to be checked against non-{@code null} and non-empty - * @return {@code true} if the provided Collection [List, Set] is non-{@code null} and non-empty - * otherwise {@code false} - */ - public static boolean nonNullNonEmpty(Collection collection) { - return Objects.nonNull(collection) && !collection.isEmpty(); + final CardinalityHelper helper = new CardinalityHelper<>(collectionOne, collectionTwo); + if (helper.cardinalityA.size() != helper.cardinalityB.size()) { + return false; + } + for (final Object obj : helper.cardinalityA.keySet()) { + if (helper.freqA(obj) != helper.freqB(obj)) { + return false; + } + } + return true; + } + + /** + * Note: Code imported from apache commons collection Returns a {@link Map} mapping each unique + * element in the given {@link Collection} to an {@link Integer} representing the number of + * occurrences of that element in the {@link Collection}. + * + *

Only those elements present in the collection will appear as keys in the map.

+ * + * @param the type of object in the returned {@link Map}. This is a super type of <I>. + * @param iterable the collection to get the cardinality map for, must not be null + * @return the populated cardinality map + * @throws NullPointerException if coll is null + * @since 1.0.3 + */ + public static Map getCardinalityMap(final Iterable iterable) { + Assert.nonNull(iterable, NullPointerException::new); + final Map count = new HashMap<>(); + for (final O obj : iterable) { + count.merge(obj, 1, Integer::sum); } + return count; + } + + /** + * Note: Code imported from apache commons collection Helper class to easily access cardinality + * properties of two collections. + * + * @param the element type + * @since 1.0.3 + */ + private static class CardinalityHelper { + + /** Contains the cardinality for each object in collection A. */ + final Map cardinalityA; + + /** Contains the cardinality for each object in collection B. */ + final Map cardinalityB; /** - * Returns {@code true} if the provided Map is {@code null} and empty otherwise - * returns {@code false}. + * Create a new CardinalityHelper for two collections. * - * @param map a Map to be checked against {@code null} or empty - * @return {@code true} if the provided Map is {@code null} and empty otherwise - * * returns {@code false} + * @param a the first collection + * @param b the second collection */ - public static boolean nullOrEmpty(Map map) { - return Objects.isNull(map) || map.isEmpty(); + CardinalityHelper(final Iterable a, final Iterable b) { + cardinalityA = Collections.getCardinalityMap(a); + cardinalityB = Collections.getCardinalityMap(b); } /** - * Returns {@code true} if the provided Map is non-{@code null} and non-empty otherwise - * returns {@code false}. + * Returns the maximum frequency of an object. * - * @param map a Map to be checked against non-{@code null} and non-empty - * @return {@code true} if the provided Map is non-{@code null} and non-empty - * otherwise {@code false} + * @param obj the object + * @return the maximum frequency of the object */ - public static boolean nonNullNonEmpty(Map map) { - return Objects.nonNull(map) && !map.isEmpty(); + public final int max(final Object obj) { + return Math.max(freqA(obj), freqB(obj)); } /** - * Returns stream of batched List from original List by given batch size. + * Returns the minimum frequency of an object. * - * @param source a List to be batched - * @param batchSize size of batch you want - * @param the type of List to be returned. - * @return Returns stream of batched List from original List by given batch size. - *

- * reference: http://stackoverflow.com/questions/12026885/common-util-to-break-a-list-into-batch + * @param obj the object + * @return the minimum frequency of the object */ - public static Stream> batches(List source, int batchSize) { - if (Objects.isNull(source)) - throw new IllegalArgumentException("source can not be null"); - - int size = source.size(); - if (batchSize < 0) { - throw new IllegalArgumentException("batchSize can not be negative"); - } else if (batchSize == 0 && size != 0) { - return Stream.of(source); - } - if (size <= 0) - return Stream.empty(); - int fullChunks = (size - 1) / batchSize; - return IntStream - .range(0, fullChunks + 1) - .mapToObj(n -> source.subList(n * batchSize, n == fullChunks ? size : (n + 1) * batchSize)); + public final int min(final Object obj) { + return Math.min(freqA(obj), freqB(obj)); } /** - * Note: Code imported from apache commons collection - *

- * Returns {@code true} iff the given {@link Collection}s contain - * exactly the same elements with exactly the same cardinalities. - *

- * That is, iff the cardinality of e in a is - * equal to the cardinality of e in b, - * for each element e in a or b. - *

+ * Returns the frequency of this object in collection A. * - * @param collectionOne the first collection, must not be null - * @param collectionTwo the second collection, must not be null - * @return {@code true} iff the collections contain the same elements with the same cardinalities. - * @throws NullPointerException if either collection is null - * @since 1.0.3 + * @param obj the object + * @return the frequency of the object in collection A */ - public static boolean isCollectionEqual(final Collection collectionOne, final Collection collectionTwo) { - Assert.nonNull(collectionOne, NullPointerException::new); - Assert.nonNull(collectionTwo, NullPointerException::new); - - if (collectionOne.size() != collectionTwo.size()) { - return false; - } - - final CardinalityHelper helper = new CardinalityHelper<>(collectionOne, collectionTwo); - if (helper.cardinalityA.size() != helper.cardinalityB.size()) { - return false; - } - for (final Object obj : helper.cardinalityA.keySet()) { - if (helper.freqA(obj) != helper.freqB(obj)) { - return false; - } - } - return true; + public int freqA(final Object obj) { + return getFreq(obj, cardinalityA); } /** - * Note: Code imported from apache commons collection - * Returns a {@link Map} mapping each unique element in the given - * {@link Collection} to an {@link Integer} representing the number - * of occurrences of that element in the {@link Collection}. - *

- * Only those elements present in the collection will appear as - * keys in the map. - *

+ * Returns the frequency of this object in collection B. * - * @param the type of object in the returned {@link Map}. This is a super type of <I>. - * @param iterable the collection to get the cardinality map for, must not be null - * @return the populated cardinality map - * @throws NullPointerException if coll is null - * @since 1.0.3 + * @param obj the object + * @return the frequency of the object in collection B */ - public static Map getCardinalityMap(final Iterable iterable) { - Assert.nonNull(iterable, NullPointerException::new); - final Map count = new HashMap<>(); - for (final O obj : iterable) { - count.merge(obj, 1, Integer::sum); - } - return count; + public int freqB(final Object obj) { + return getFreq(obj, cardinalityB); } - /** - * Note: Code imported from apache commons collection - * Helper class to easily access cardinality properties of two collections. - * - * @param the element type - * @since 1.0.3 - */ - private static class CardinalityHelper { - - /** - * Contains the cardinality for each object in collection A. - */ - final Map cardinalityA; - - /** - * Contains the cardinality for each object in collection B. - */ - final Map cardinalityB; - - /** - * Create a new CardinalityHelper for two collections. - * - * @param a the first collection - * @param b the second collection - */ - CardinalityHelper(final Iterable a, final Iterable b) { - cardinalityA = Collections.getCardinalityMap(a); - cardinalityB = Collections.getCardinalityMap(b); - } - - /** - * Returns the maximum frequency of an object. - * - * @param obj the object - * @return the maximum frequency of the object - */ - public final int max(final Object obj) { - return Math.max(freqA(obj), freqB(obj)); - } - - /** - * Returns the minimum frequency of an object. - * - * @param obj the object - * @return the minimum frequency of the object - */ - public final int min(final Object obj) { - return Math.min(freqA(obj), freqB(obj)); - } - - /** - * Returns the frequency of this object in collection A. - * - * @param obj the object - * @return the frequency of the object in collection A - */ - public int freqA(final Object obj) { - return getFreq(obj, cardinalityA); - } - - /** - * Returns the frequency of this object in collection B. - * - * @param obj the object - * @return the frequency of the object in collection B - */ - public int freqB(final Object obj) { - return getFreq(obj, cardinalityB); - } - - private int getFreq(final Object obj, final Map freqMap) { - final Integer count = freqMap.get(obj); - if (count != null) { - return count; - } - return 0; - } + private int getFreq(final Object obj, final Map freqMap) { + final Integer count = freqMap.get(obj); + if (count != null) { + return count; + } + return 0; } + } } diff --git a/src/main/java/com/javaquery/util/io/Console.java b/src/main/java/com/javaquery/util/io/Console.java index f337df5..1a64645 100644 --- a/src/main/java/com/javaquery/util/io/Console.java +++ b/src/main/java/com/javaquery/util/io/Console.java @@ -12,34 +12,37 @@ */ public final class Console { - private static final Logger LOGGER = LoggerFactory.getLogger(Console.class); + private static final Logger LOGGER = LoggerFactory.getLogger(Console.class); - /** - * Print object to output stream. Internally it uses System.out.println(obj); - * @param object object to print on console - */ - public static void log(Object object){ - System.out.println(object); - } + /** + * Print object to output stream. Internally it uses System.out.println(obj); + * + * @param object object to print on console + */ + public static void log(Object object) { + System.out.println(object); + } - /** - * Print object to output stream. Internally it uses System.err.println(obj); - * @param object object to print on console - */ - public static void error(Object object){ - System.err.println(object); - } + /** + * Print object to output stream. Internally it uses System.err.println(obj); + * + * @param object object to print on console + */ + public static void error(Object object) { + System.err.println(object); + } - /** - * Read String from console. - * @return String input provided in console - */ - public static String read(){ - try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))){ - return reader.readLine(); - }catch (Exception e){ - LOGGER.error(e.getMessage(), e); - } - return null; + /** + * Read String from console. + * + * @return String input provided in console + */ + public static String read() { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + return reader.readLine(); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); } + return null; + } } diff --git a/src/main/java/com/javaquery/util/io/Files.java b/src/main/java/com/javaquery/util/io/Files.java index 7a5fe58..91a8ae1 100644 --- a/src/main/java/com/javaquery/util/io/Files.java +++ b/src/main/java/com/javaquery/util/io/Files.java @@ -20,159 +20,152 @@ */ public final class Files { - private static final Logger LOGGER = LoggerFactory.getLogger(Files.class); + private static final Logger LOGGER = LoggerFactory.getLogger(Files.class); - /** - * Create new, empty file at specified path in {@link File} object. - * This method will also creates folder structure if not exists. - * - * Note: Exception is logged not thrown. - * - * @param file - file to create - * @param the type of class that extends {@link File} - * @return true if the named file does not exist and was - * successfully created; false if the named file - * already exists - */ - public static boolean createNewFile(T file) { - Assert.nonNull(file, NullPointerException::new); - if (!file.exists()) { - file.getParentFile().mkdirs(); - try { - return file.createNewFile(); - } catch (IOException e) { - LOGGER.error(e.getMessage(), e); - } - } - return false; + /** + * Create new, empty file at specified path in {@link File} object. This method will also creates + * folder structure if not exists. + * + *

Note: Exception is logged not thrown. + * + * @param file - file to create + * @param the type of class that extends {@link File} + * @return true if the named file does not exist and was successfully created; + * false if the named file already exists + */ + public static boolean createNewFile(T file) { + Assert.nonNull(file, NullPointerException::new); + if (!file.exists()) { + file.getParentFile().mkdirs(); + try { + return file.createNewFile(); + } catch (IOException e) { + LOGGER.error(e.getMessage(), e); + } } + return false; + } - /** - * Delete existing file and then Create new, empty file at - * specified path in {@link File} object. - * - * Note: Exception is logged not thrown. - * - * @param file - file to delete and create - * @param the type of class that extends {@link File} - * @return true if the named file deleted and was - * successfully created; false if the named file - * already exists - */ - public static boolean deleteAndCreateNewFile(T file) { - Assert.nonNull(file, NullPointerException::new); - if (file.exists()) { - file.delete(); - } - return createNewFile(file); + /** + * Delete existing file and then Create new, empty file at specified path in {@link File} object. + * + *

Note: Exception is logged not thrown. + * + * @param file - file to delete and create + * @param the type of class that extends {@link File} + * @return true if the named file deleted and was successfully created; false + * if the named file already exists + */ + public static boolean deleteAndCreateNewFile(T file) { + Assert.nonNull(file, NullPointerException::new); + if (file.exists()) { + file.delete(); } + return createNewFile(file); + } - /** - * Write data to provided file. - * - * Note: This method will also creates new file if not exist. - * Exception is logged not thrown. - * - * @param file file to write - * @param data data to write to file - * @param the type of class that extends {@link File} - */ - public static void writeToFile(T file, String data) { - Assert.nonNull(file, NullPointerException::new); - Assert.nonNull(data, NullPointerException::new); - if (!file.exists()) { - createNewFile(file); - } - try { - java.nio.file.Files.write(getPath(file), data.getBytes()); - } catch (IOException | InvalidPathException e) { - LOGGER.error(e.getMessage(), e); - } + /** + * Write data to provided file. + * + *

Note: This method will also creates new file if not exist. Exception is logged + * not thrown. + * + * @param file file to write + * @param data data to write to file + * @param the type of class that extends {@link File} + */ + public static void writeToFile(T file, String data) { + Assert.nonNull(file, NullPointerException::new); + Assert.nonNull(data, NullPointerException::new); + if (!file.exists()) { + createNewFile(file); } - - /** - * Append data to provided file - * - * Note: This method will also creates new file if not exist. - * Exception is logged not thrown. - * - * @param file file to write - * @param data data to append to file - * @param appendNewLine true to append new line at the end of data - * otherwise false. - * @param the type of class that extends {@link File} - */ - public static void appendToFile(T file, String data, boolean appendNewLine) { - Assert.nonNull(file, NullPointerException::new); - Assert.nonNull(data, NullPointerException::new); - if (!file.exists()) { - createNewFile(file); - } - data = appendNewLine ? (data + "\n") : data; - try { - java.nio.file.Files.write(getPath(file), data.getBytes(), StandardOpenOption.APPEND); - } catch (IOException | InvalidPathException e) { - LOGGER.error(e.getMessage(), e); - } + try { + java.nio.file.Files.write(getPath(file), data.getBytes()); + } catch (IOException | InvalidPathException e) { + LOGGER.error(e.getMessage(), e); } + } - /** - * Read String content of file. - * - * Note: Exception is logged not thrown. - * - * @param file file to read - * @param the type of class that extends {@link File} - * @return String data of file if exists otherwise null - */ - public static String readFromFile(T file) { - Assert.nonNull(file, NullPointerException::new); - if (file.exists()) { - try { - return new String(java.nio.file.Files.readAllBytes(getPath(file))); - } catch (IOException | InvalidPathException e) { - LOGGER.error(e.getMessage(), e); - } - } - return null; + /** + * Append data to provided file Note: This method will also creates new file + * if not exist. Exception is logged not thrown. + * + * @param file file to write + * @param data data to append to file + * @param appendNewLine true to append new line at the end of data otherwise + * false. + * @param the type of class that extends {@link File} + */ + public static void appendToFile(T file, String data, boolean appendNewLine) { + Assert.nonNull(file, NullPointerException::new); + Assert.nonNull(data, NullPointerException::new); + if (!file.exists()) { + createNewFile(file); } + data = appendNewLine ? (data + "\n") : data; + try { + java.nio.file.Files.write(getPath(file), data.getBytes(), StandardOpenOption.APPEND); + } catch (IOException | InvalidPathException e) { + LOGGER.error(e.getMessage(), e); + } + } - /** - * Path of file provided - * - * @param file file to get {@link Path}. - * @param the type of class that extends {@link File} - * @return {@link Path} of file - */ - private static Path getPath(T file) { - return Paths.get(file.getAbsolutePath()); + /** + * Read String content of file. + * + *

Note: Exception is logged not thrown. + * + * @param file file to read + * @param the type of class that extends {@link File} + * @return String data of file if exists otherwise null + */ + public static String readFromFile(T file) { + Assert.nonNull(file, NullPointerException::new); + if (file.exists()) { + try { + return new String(java.nio.file.Files.readAllBytes(getPath(file))); + } catch (IOException | InvalidPathException e) { + LOGGER.error(e.getMessage(), e); + } } + return null; + } + + /** + * Path of file provided + * + * @param file file to get {@link Path}. + * @param the type of class that extends {@link File} + * @return {@link Path} of file + */ + private static Path getPath(T file) { + return Paths.get(file.getAbsolutePath()); + } - /** - * Read any file from resources folder of project. - * For example, read demo.json from provided path `resources folder` /sample/demo.json - * - * @param path path to resource - * @return String data of file if exists otherwise null - */ - public String loadResource(String path) { - Assert.nonNull(path, NullPointerException::new); - if (!path.trim().isEmpty()) { - try ( - InputStream inputStream = getClass().getResourceAsStream(path); - BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)) - ) { - String fileLine; - StringBuilder stringBuilder = new StringBuilder(); + /** + * Read any file from resources folder of project. For example, read demo.json from provided path + * `resources folder` /sample/demo.json + * + * @param path path to resource + * @return String data of file if exists otherwise null + */ + public String loadResource(String path) { + Assert.nonNull(path, NullPointerException::new); + if (!path.trim().isEmpty()) { + try (InputStream inputStream = getClass().getResourceAsStream(path); + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) { + String fileLine; + StringBuilder stringBuilder = new StringBuilder(); - while ((fileLine = bufferedReader.readLine()) != null) { - stringBuilder.append(fileLine); - } - return stringBuilder.toString(); - } catch (IOException | NullPointerException e) { - LOGGER.error(e.getMessage(), e); - } + while ((fileLine = bufferedReader.readLine()) != null) { + stringBuilder.append(fileLine); } - return null; + return stringBuilder.toString(); + } catch (IOException | NullPointerException e) { + LOGGER.error(e.getMessage(), e); + } } + return null; + } } diff --git a/src/main/java/com/javaquery/util/io/JFile.java b/src/main/java/com/javaquery/util/io/JFile.java index dd0d128..6cd59aa 100644 --- a/src/main/java/com/javaquery/util/io/JFile.java +++ b/src/main/java/com/javaquery/util/io/JFile.java @@ -14,104 +14,89 @@ */ public final class JFile extends File { - private final Map attributes; + private final Map attributes; - public JFile(String pathname) { - super(pathname); - attributes = new HashMap<>(); - } + public JFile(String pathname) { + super(pathname); + attributes = new HashMap<>(); + } - /** - * @return file extension - */ - public String getExtension(){ - String name = getName(); - if(Strings.nonNullNonEmpty(name)){ - int lastIndexOfDot = name.lastIndexOf("."); - if(lastIndexOfDot > 0){ - return name.substring(lastIndexOfDot + 1); - } - } - return ""; + /** @return file extension */ + public String getExtension() { + String name = getName(); + if (Strings.nonNullNonEmpty(name)) { + int lastIndexOfDot = name.lastIndexOf("."); + if (lastIndexOfDot > 0) { + return name.substring(lastIndexOfDot + 1); + } } + return ""; + } - /** - * @param name a name to change for current file - * @return renamed file object if and only if the renaming succeeded; - * null otherwise - * - * @throws SecurityException - * If a security manager exists and its {@link - * java.lang.SecurityManager#checkWrite(java.lang.String)} - * method denies write access to either the old or new pathnames - * - * @throws NullPointerException - * If parameter dest is null - */ - public final JFile rename(String name){ - Assert.nonNull(name, NullPointerException::new); - if(exists()){ - boolean result = renameTo(new File(getParent() + File.separatorChar + name)); - if(result){ - return new JFile(getParent() + File.separatorChar + name); - } - } - return null; + /** + * @param name a name to change for current file + * @return renamed file object if and only if the renaming succeeded; null otherwise + * @throws SecurityException If a security manager exists and its {@link + * java.lang.SecurityManager#checkWrite(java.lang.String)} method denies write + * access to either the old or new pathnames + * @throws NullPointerException If parameter dest is null + */ + public final JFile rename(String name) { + Assert.nonNull(name, NullPointerException::new); + if (exists()) { + boolean result = renameTo(new File(getParent() + File.separatorChar + name)); + if (result) { + return new JFile(getParent() + File.separatorChar + name); + } } + return null; + } - /** - * @return String content of this file. - */ - public final String read(){ - return Files.readFromFile(this); - } + /** @return String content of this file. */ + public final String read() { + return Files.readFromFile(this); + } - /** - * @param data data to write to this file - */ - public final void write(String data) { - Files.writeToFile(this, data); - } + /** @param data data to write to this file */ + public final void write(String data) { + Files.writeToFile(this, data); + } - /** - * @param data to append to this file - * @param appendNewLine true to append new line at the end of data - * otherwise false - */ - public final void append(String data, boolean appendNewLine) { - Files.appendToFile(this, data, appendNewLine); - } + /** + * @param data to append to this file + * @param appendNewLine true to append new line at the end of data otherwise + * false + */ + public final void append(String data, boolean appendNewLine) { + Files.appendToFile(this, data, appendNewLine); + } - /** - * @return attributes of file - */ - public final Map getAttributes() { - return attributes; - } + /** @return attributes of file */ + public final Map getAttributes() { + return attributes; + } - /** - * @param key a key of attribute - * @param value a value of attribute - */ - public final void addAttribute(String key, String value){ - attributes.put(key, value); - } + /** + * @param key a key of attribute + * @param value a value of attribute + */ + public final void addAttribute(String key, String value) { + attributes.put(key, value); + } - /** - * @param attributes add attributes map to file - */ - public final void addAllAttribute(Map attributes){ - if(Collections.nonNullNonEmpty(attributes)){ - this.attributes.putAll(attributes); - } + /** @param attributes add attributes map to file */ + public final void addAllAttribute(Map attributes) { + if (Collections.nonNullNonEmpty(attributes)) { + this.attributes.putAll(attributes); } + } - /** - * @param key a key to find attribute - * @param defaultValue default value in case attribute not found - * @return attribute value if found otherwise defaultValue - */ - public final String optAttribute(String key, String defaultValue){ - return attributes.getOrDefault(key, defaultValue); - } + /** + * @param key a key to find attribute + * @param defaultValue default value in case attribute not found + * @return attribute value if found otherwise defaultValue + */ + public final String optAttribute(String key, String defaultValue) { + return attributes.getOrDefault(key, defaultValue); + } } diff --git a/src/main/java/com/javaquery/util/json/JSONObject.java b/src/main/java/com/javaquery/util/json/JSONObject.java index fafedcb..25aae49 100644 --- a/src/main/java/com/javaquery/util/json/JSONObject.java +++ b/src/main/java/com/javaquery/util/json/JSONObject.java @@ -2,10 +2,13 @@ import com.javaquery.util.Objects; import com.javaquery.util.string.Strings; +import com.javaquery.util.time.DateTimeFormat; +import com.javaquery.util.time.Dates; import org.json.JSONArray; import java.math.BigDecimal; import java.math.BigInteger; +import java.util.Date; import java.util.HashMap; import java.util.Map; @@ -15,395 +18,423 @@ */ public final class JSONObject { - private org.json.JSONObject ROOT; - private Map CACHED_OBJECT; - - /** - * @param json json string to prepare {@link JSONObject} - */ - public JSONObject(String json) { - this(new org.json.JSONObject(json)); - } - - /** - * @param jsonObject {@link org.json.JSONObject} to prepare {@link JSONObject} - */ - public JSONObject(org.json.JSONObject jsonObject){ - ROOT = jsonObject; - CACHED_OBJECT = new HashMap<>(); - } - - /** - * Get an optional boolean associated with a key. It returns false if there - * is no such key, or if the value is not Boolean.TRUE or the String "true". - * - * @param key A key string. - * @return The truth. - */ - public boolean optBoolean(String key) { - return optBoolean(key, false); - } - - /** - * Get an optional boolean associated with a key. It returns the - * defaultValue if there is no such key, or if it is not a Boolean or the - * String "true" or "false" (case insensitive). - * - * @param key A key string. - * @param defaultValue The default. - * @return The truth. - */ - public boolean optBoolean(String key, boolean defaultValue) { - KeyPath keyPath = new KeyPath(key); - return findByKey(keyPath).optBoolean(keyPath.key, defaultValue); + private static final org.json.JSONObject EMPTY_JSON = new org.json.JSONObject("{}"); + private org.json.JSONObject ROOT; + private Map CACHED_OBJECT; + + /** @param json json string to prepare {@link JSONObject} */ + public JSONObject(String json) { + this(new org.json.JSONObject(json)); + } + + /** @param jsonObject {@link org.json.JSONObject} to prepare {@link JSONObject} */ + public JSONObject(org.json.JSONObject jsonObject) { + ROOT = jsonObject; + CACHED_OBJECT = new HashMap<>(); + } + + /** + * Get an optional boolean associated with a key. It returns false if there is no such key, or if + * the value is not Boolean.TRUE or the String "true". + * + * @param key A key string. + * @return The truth. + */ + public boolean optBoolean(String key) { + return optBoolean(key, false); + } + + /** + * Get an optional boolean associated with a key. It returns the defaultValue if there is no such + * key, or if it is not a Boolean or the String "true" or "false" (case insensitive). + * + * @param key A key string. + * @param defaultValue The default. + * @return The truth. + */ + public boolean optBoolean(String key, boolean defaultValue) { + KeyPath keyPath = new KeyPath(key); + return findByKey(keyPath).optBoolean(keyPath.key, defaultValue); + } + + /** + * Get an optional BigDecimal associated with a key, or the defaultValue if there is no such key + * or if its value is not a number. If the value is a string, an attempt will be made to evaluate + * it as a number. If the value is float or double, then the {@link BigDecimal#BigDecimal(double)} + * constructor will be used. See notes on the constructor for conversion issues that may arise. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public BigDecimal optBigDecimal(String key, BigDecimal defaultValue) { + KeyPath keyPath = new KeyPath(key); + return findByKey(keyPath).optBigDecimal(keyPath.key, defaultValue); + } + + /** + * Get an optional BigInteger associated with a key, or the defaultValue if there is no such key + * or if its value is not a number. If the value is a string, an attempt will be made to evaluate + * it as a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public BigInteger optBigInteger(String key, BigInteger defaultValue) { + KeyPath keyPath = new KeyPath(key); + return findByKey(keyPath).optBigInteger(keyPath.key, defaultValue); + } + + /** + * Get an optional double associated with a key, or NaN if there is no such key or if its value is + * not a number. If the value is a string, an attempt will be made to evaluate it as a number. + * + * @param key A string which is the key. + * @return An object which is the value. + */ + public double optDouble(String key) { + return optDouble(key, Double.NaN); + } + + /** + * Get an optional double associated with a key, or the defaultValue if there is no such key or if + * its value is not a number. If the value is a string, an attempt will be made to evaluate it as + * a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public double optDouble(String key, double defaultValue) { + KeyPath keyPath = new KeyPath(key); + return findByKey(keyPath).optDouble(keyPath.key, defaultValue); + } + + /** + * Get an optional {@link Date} associated with a key, or current {@link Date} if there is no such + * key or if the value is not a {@link Date}. An attempt will be made to evaluate it as a {@link + * Date}. + * + * @param key A key string. + * @param dateTimeFormat date format to parse from String value. Use {@link + * com.javaquery.util.time.DatePattern}. + * @return An object which is the value. + */ + public Date optDate(String key, DateTimeFormat dateTimeFormat) { + return optDate(key, dateTimeFormat, new Date()); + } + + /** + * Get an optional {@link Date} associated with a key, or the defaultValue if there is no such key + * or if its value is not a Date. An attempt will be made to evaluate it as a {@link Date}. + * + * @param key A key string. + * @param dateTimeFormat date format to parse from String value. Use {@link + * com.javaquery.util.time.DatePattern}. + * @param defaultValue The default. + * @return An object which is the value. + */ + public Date optDate(String key, DateTimeFormat dateTimeFormat, Date defaultValue) { + String strDate = optString(key); + Date result = defaultValue; + if (Strings.nonNullNonEmpty(strDate)) { + Date parsedDate = Dates.parse(strDate, dateTimeFormat); + if (Objects.nonNull(parsedDate)) { + result = parsedDate; + } } - - /** - * Get an optional BigDecimal associated with a key, or the defaultValue if - * there is no such key or if its value is not a number. If the value is a - * string, an attempt will be made to evaluate it as a number. If the value - * is float or double, then the {@link BigDecimal#BigDecimal(double)} - * constructor will be used. See notes on the constructor for conversion - * issues that may arise. - * - * @param key A key string. - * @param defaultValue The default. - * @return An object which is the value. - */ - public BigDecimal optBigDecimal(String key, BigDecimal defaultValue) { - KeyPath keyPath = new KeyPath(key); - return findByKey(keyPath).optBigDecimal(keyPath.key, defaultValue); + return result; + } + + /** + * Get the enum value associated with a key. + * + * @param Enum Type + * @param clazz The type of enum to retrieve. + * @param key A key string. + * @return The enum value associated with the key or null if not found + */ + public > E optEnum(Class clazz, String key) { + return this.optEnum(clazz, key, null); + } + + /** + * Get the enum value associated with a key. + * + * @param Enum Type + * @param clazz The type of enum to retrieve. + * @param key A key string. + * @param defaultValue The default in case the value is not found + * @return The enum value associated with the key or defaultValue if the value is not found or + * cannot be assigned to clazz + */ + public > E optEnum(Class clazz, String key, E defaultValue) { + KeyPath keyPath = new KeyPath(key); + return findByKey(keyPath).optEnum(clazz, keyPath.key, defaultValue); + } + + /** + * Get the optional double value associated with an index. NaN is returned if there is no value + * for the index, or if the value is not a number and cannot be converted to a number. + * + * @param key A key string. + * @return The value. + */ + public float optFloat(String key) { + return optFloat(key, Float.NaN); + } + + /** + * Get the optional double value associated with an index. The defaultValue is returned if there + * is no value for the index, or if the value is not a number and cannot be converted to a number. + * + * @param key A key string. + * @param defaultValue The default value. + * @return The value. + */ + public float optFloat(String key, float defaultValue) { + KeyPath keyPath = new KeyPath(key); + return findByKey(keyPath).optFloat(keyPath.key, defaultValue); + } + + /** + * Get an optional int value associated with a key, or zero if there is no such key or if the + * value is not a number. If the value is a string, an attempt will be made to evaluate it as a + * number. + * + * @param key A key string. + * @return An object which is the value. + */ + public int optInt(String key) { + return optInt(key, 0); + } + + /** + * Get an optional int value associated with a key, or the default if there is no such key or if + * the value is not a number. If the value is a string, an attempt will be made to evaluate it as + * a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public int optInt(String key, int defaultValue) { + KeyPath keyPath = new KeyPath(key); + return findByKey(keyPath).optInt(keyPath.key, defaultValue); + } + + /** + * Get an optional long value associated with a key, or zero if there is no such key or if the + * value is not a number. If the value is a string, an attempt will be made to evaluate it as a + * number. + * + * @param key A key string. + * @return An object which is the value. + */ + public long optLong(String key) { + return optLong(key, 0); + } + + /** + * Get an optional long value associated with a key, or the default if there is no such key or if + * the value is not a number. If the value is a string, an attempt will be made to evaluate it as + * a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public long optLong(String key, long defaultValue) { + KeyPath keyPath = new KeyPath(key); + return findByKey(keyPath).optLong(keyPath.key, defaultValue); + } + + /** + * Get an optional {@link Number} value associated with a key, or null if there is no + * such key or if the value is not a number. If the value is a string, an attempt will be made to + * evaluate it as a number ({@link BigDecimal}). This method would be used in cases where type + * coercion of the number value is unwanted. + * + * @param key A key string. + * @return An object which is the value. + */ + public Number optNumber(String key) { + return optNumber(key, null); + } + + /** + * Get an optional {@link Number} value associated with a key, or the default if there is no such + * key or if the value is not a number. If the value is a string, an attempt will be made to + * evaluate it as a number. This method would be used in cases where type coercion of the number + * value is unwanted. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public Number optNumber(String key, Number defaultValue) { + KeyPath keyPath = new KeyPath(key); + return findByKey(keyPath).optNumber(keyPath.key, defaultValue); + } + + /** + * Get an optional string associated with a key. It returns an empty string if there is no such + * key. If the value is not a string and is not null, then it is converted to a string. + * + * @param key A key string. + * @return A string which is the value. + */ + public String optString(String key) { + return optString(key, ""); + } + + /** + * Get an optional string associated with a key. It returns the defaultValue if there is no such + * key. + * + * @param key A key string. + * @param defaultValue The default. + * @return A string which is the value. + */ + public String optString(String key, String defaultValue) { + KeyPath keyPath = new KeyPath(key); + return findByKey(keyPath).optString(keyPath.key, defaultValue); + } + + /** + * Get an optional JSONObject associated with a key. It returns null if there is no such key, or + * if its value is not a JSONObject. + * + * @param key A key string. + * @return A JSONObject which is the value. + */ + public org.json.JSONObject optJSONObject(String key) { + KeyPath keyPath = new KeyPath(key); + org.json.JSONObject jsonObject = findByKey(keyPath); + org.json.JSONObject result = jsonObject.optJSONObject(keyPath.key); + if (Objects.isNull(result) && keyPath.key.contains("[") && keyPath.key.endsWith("]")) { + result = arrayJSONObject(jsonObject, keyPath.key); } - - /** - * Get an optional BigInteger associated with a key, or the defaultValue if - * there is no such key or if its value is not a number. If the value is a - * string, an attempt will be made to evaluate it as a number. - * - * @param key A key string. - * @param defaultValue The default. - * @return An object which is the value. - */ - public BigInteger optBigInteger(String key, BigInteger defaultValue) { - KeyPath keyPath = new KeyPath(key); - return findByKey(keyPath).optBigInteger(keyPath.key, defaultValue); - } - - /** - * Get an optional double associated with a key, or NaN if there is no such - * key or if its value is not a number. If the value is a string, an attempt - * will be made to evaluate it as a number. - * - * @param key A string which is the key. - * @return An object which is the value. - */ - public double optDouble(String key) { - return optDouble(key, Double.NaN); - } - - /** - * Get an optional double associated with a key, or the defaultValue if - * there is no such key or if its value is not a number. If the value is a - * string, an attempt will be made to evaluate it as a number. - * - * @param key A key string. - * @param defaultValue The default. - * @return An object which is the value. - */ - public double optDouble(String key, double defaultValue) { - KeyPath keyPath = new KeyPath(key); - return findByKey(keyPath).optDouble(keyPath.key, defaultValue); - } - - /** - * Get the enum value associated with a key. - * - * @param Enum Type - * @param clazz The type of enum to retrieve. - * @param key A key string. - * @return The enum value associated with the key or null if not found - */ - public > E optEnum(Class clazz, String key) { - return this.optEnum(clazz, key, null); - } - - /** - * Get the enum value associated with a key. - * - * @param Enum Type - * @param clazz The type of enum to retrieve. - * @param key A key string. - * @param defaultValue The default in case the value is not found - * @return The enum value associated with the key or defaultValue - * if the value is not found or cannot be assigned to clazz - */ - public > E optEnum(Class clazz, String key, E defaultValue) { - KeyPath keyPath = new KeyPath(key); - return findByKey(keyPath).optEnum(clazz, keyPath.key, defaultValue); - } - - /** - * Get the optional double value associated with an index. NaN is returned - * if there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param key A key string. - * @return The value. - */ - public float optFloat(String key) { - return optFloat(key, Float.NaN); - } - - /** - * Get the optional double value associated with an index. The defaultValue - * is returned if there is no value for the index, or if the value is not a - * number and cannot be converted to a number. - * - * @param key A key string. - * @param defaultValue The default value. - * @return The value. - */ - public float optFloat(String key, float defaultValue) { - KeyPath keyPath = new KeyPath(key); - return findByKey(keyPath).optFloat(keyPath.key, defaultValue); - } - - /** - * Get an optional int value associated with a key, or zero if there is no - * such key or if the value is not a number. If the value is a string, an - * attempt will be made to evaluate it as a number. - * - * @param key A key string. - * @return An object which is the value. - */ - public int optInt(String key) { - return optInt(key, 0); - } - - /** - * Get an optional int value associated with a key, or the default if there - * is no such key or if the value is not a number. If the value is a string, - * an attempt will be made to evaluate it as a number. - * - * @param key A key string. - * @param defaultValue The default. - * @return An object which is the value. - */ - public int optInt(String key, int defaultValue) { - KeyPath keyPath = new KeyPath(key); - return findByKey(keyPath).optInt(keyPath.key, defaultValue); - } - - /** - * Get an optional long value associated with a key, or zero if there is no - * such key or if the value is not a number. If the value is a string, an - * attempt will be made to evaluate it as a number. - * - * @param key A key string. - * @return An object which is the value. - */ - public long optLong(String key) { - return optLong(key, 0); - } - - /** - * Get an optional long value associated with a key, or the default if there - * is no such key or if the value is not a number. If the value is a string, - * an attempt will be made to evaluate it as a number. - * - * @param key A key string. - * @param defaultValue The default. - * @return An object which is the value. - */ - public long optLong(String key, long defaultValue) { - KeyPath keyPath = new KeyPath(key); - return findByKey(keyPath).optLong(keyPath.key, defaultValue); - } - - /** - * Get an optional {@link Number} value associated with a key, or null - * if there is no such key or if the value is not a number. If the value is a string, - * an attempt will be made to evaluate it as a number ({@link BigDecimal}). This method - * would be used in cases where type coercion of the number value is unwanted. - * - * @param key A key string. - * @return An object which is the value. - */ - public Number optNumber(String key) { - return optNumber(key, null); - } - - /** - * Get an optional {@link Number} value associated with a key, or the default if there - * is no such key or if the value is not a number. If the value is a string, - * an attempt will be made to evaluate it as a number. This method - * would be used in cases where type coercion of the number value is unwanted. - * - * @param key A key string. - * @param defaultValue The default. - * @return An object which is the value. - */ - public Number optNumber(String key, Number defaultValue) { - KeyPath keyPath = new KeyPath(key); - return findByKey(keyPath).optNumber(keyPath.key, defaultValue); - } - - /** - * Get an optional string associated with a key. It returns an empty string - * if there is no such key. If the value is not a string and is not null, - * then it is converted to a string. - * - * @param key A key string. - * @return A string which is the value. - */ - public String optString(String key) { - return optString(key, ""); - } - - /** - * Get an optional string associated with a key. It returns the defaultValue - * if there is no such key. - * - * @param key A key string. - * @param defaultValue The default. - * @return A string which is the value. - */ - public String optString(String key, String defaultValue) { - KeyPath keyPath = new KeyPath(key); - return findByKey(keyPath).optString(keyPath.key, defaultValue); - } - - /** - * Get an optional JSONObject associated with a key. It returns null if - * there is no such key, or if its value is not a JSONObject. - * - * @param key A key string. - * @return A JSONObject which is the value. - */ - public org.json.JSONObject optJSONObject(String key) { - KeyPath keyPath = new KeyPath(key); - org.json.JSONObject jsonObject = findByKey(keyPath); - org.json.JSONObject result = jsonObject.optJSONObject(keyPath.key); - if (Objects.isNull(result) && keyPath.key.contains("[") && keyPath.key.endsWith("]")) { - result = arrayJSONObject(jsonObject, keyPath.key); - } - return result; - } - - /** - * Get an optional JSONArray associated with a key. It returns null if there - * is no such key, or if its value is not a JSONArray. - * - * @param key A key string. - * @return A JSONArray which is the value. - */ - public JSONArray optJSONArray(String key) { - KeyPath keyPath = new KeyPath(key); - return findByKey(keyPath).optJSONArray(keyPath.key); - } - - /** - * Find {@link org.json.JSONObject} at provided path - * @param keyPath object containg key and path of object - * @return A {@link org.json.JSONObject} which hold the value - */ - private org.json.JSONObject findByKey(KeyPath keyPath) { - if (Strings.nonNullNonEmpty(keyPath.path)) { - if (CACHED_OBJECT.containsKey(keyPath.path)) { - return CACHED_OBJECT.get(keyPath.path); - } else { - org.json.JSONObject result = (org.json.JSONObject) recursion(ROOT, keyPath.path); - CACHED_OBJECT.put(keyPath.path, result); - return result; - } + return result; + } + + /** + * Get an optional JSONArray associated with a key. It returns null if there is no such key, or if + * its value is not a JSONArray. + * + * @param key A key string. + * @return A JSONArray which is the value. + */ + public JSONArray optJSONArray(String key) { + KeyPath keyPath = new KeyPath(key); + return findByKey(keyPath).optJSONArray(keyPath.key); + } + + /** + * Find {@link org.json.JSONObject} at provided path + * + * @param keyPath object containing key and path of object + * @return A {@link org.json.JSONObject} which hold the value + */ + private org.json.JSONObject findByKey(KeyPath keyPath) { + if (Strings.nonNullNonEmpty(keyPath.path)) { + if (CACHED_OBJECT.containsKey(keyPath.path)) { + return CACHED_OBJECT.get(keyPath.path); + } else { + org.json.JSONObject result = (org.json.JSONObject) recursion(ROOT, keyPath.path); + if (Objects.nonNull(result)) { + CACHED_OBJECT.put(keyPath.path, result); } else { - return ROOT; - } - } - - /** - * Do a recursive call to fine Object at provided path - * - * @param jsonObject input {@link org.json.JSONObject} - * @param path a path to find object - * @return Object at provided path - */ - private Object recursion(org.json.JSONObject jsonObject, String path) { - if (path.contains(".")) { - int dotIndex = path.indexOf("."); - String subKey = path.substring(0, dotIndex); - String remainingKey = path.substring(dotIndex + 1); - - if (subKey.contains("[") && subKey.endsWith("]")) { - org.json.JSONObject jsonArrayValueObject = arrayJSONObject(jsonObject, subKey); - if (Objects.nonNull(jsonArrayValueObject)) { - return recursion(jsonArrayValueObject, remainingKey); - } - } - - Object object = jsonObject.opt(subKey); - if (object instanceof org.json.JSONObject) { - return recursion(jsonObject.optJSONObject(subKey), remainingKey); - } - } else { - if (path.contains("[") && path.endsWith("]")) { - return arrayJSONObject(jsonObject, path); - } - - return jsonObject.optJSONObject(path); + result = EMPTY_JSON; } - return jsonObject; + return result; + } + } else { + return ROOT; } - - /** - * Get {@link org.json.JSONObject} from {@link JSONArray} from provided index - * @param jsonObject input {@link org.json.JSONObject}. - * @param keyWithIndex String value of index i.e "[1]" - * @return org.json.JSONObject from {@link JSONArray} - */ - private org.json.JSONObject arrayJSONObject(org.json.JSONObject jsonObject, String keyWithIndex) { - if (keyWithIndex.contains("[") && keyWithIndex.endsWith("]")) { - int startBracket = keyWithIndex.indexOf("["); - int endBracket = keyWithIndex.indexOf("]"); - String arrayName = keyWithIndex.substring(0, startBracket); - int arrayIndex = Integer.parseInt(keyWithIndex.substring(startBracket + 1, endBracket)); - - JSONArray jsonArray = jsonObject.optJSONArray(arrayName); - if(Objects.nonNull(jsonArray)){ - return jsonArray.optJSONObject(arrayIndex); - } + } + + /** + * Do a recursive call to fine Object at provided path + * + * @param jsonObject input {@link org.json.JSONObject} + * @param path a path to find object + * @return Object at provided path + */ + private Object recursion(org.json.JSONObject jsonObject, String path) { + if (path.contains(".")) { + int dotIndex = path.indexOf("."); + String subKey = path.substring(0, dotIndex); + String remainingKey = path.substring(dotIndex + 1); + + if (subKey.contains("[") && subKey.endsWith("]")) { + org.json.JSONObject jsonArrayValueObject = arrayJSONObject(jsonObject, subKey); + if (Objects.nonNull(jsonArrayValueObject)) { + return recursion(jsonArrayValueObject, remainingKey); } - return null; + } + + Object object = jsonObject.opt(subKey); + if (object instanceof org.json.JSONObject) { + return recursion(jsonObject.optJSONObject(subKey), remainingKey); + } + } else { + if (path.contains("[") && path.endsWith("]")) { + return arrayJSONObject(jsonObject, path); + } + + return jsonObject.optJSONObject(path); } - - /** - * Nullify object for garbage collection - */ - public void flush() { - ROOT = null; - CACHED_OBJECT = null; + return jsonObject; + } + + /** + * Get {@link org.json.JSONObject} from {@link JSONArray} from provided index + * + * @param jsonObject input {@link org.json.JSONObject}. + * @param keyWithIndex String value of index i.e "[1]" + * @return org.json.JSONObject from {@link JSONArray} + */ + private org.json.JSONObject arrayJSONObject(org.json.JSONObject jsonObject, String keyWithIndex) { + if (keyWithIndex.contains("[") && keyWithIndex.endsWith("]")) { + int startBracket = keyWithIndex.indexOf("["); + int endBracket = keyWithIndex.indexOf("]"); + String arrayName = keyWithIndex.substring(0, startBracket); + int arrayIndex = Integer.parseInt(keyWithIndex.substring(startBracket + 1, endBracket)); + + JSONArray jsonArray = jsonObject.optJSONArray(arrayName); + if (Objects.nonNull(jsonArray)) { + return jsonArray.optJSONObject(arrayIndex); + } } - - /** - * To hold key and path to find object. - */ - private static class KeyPath { - private final String key; - private String path; - - public KeyPath(String key) { - int dotIndex = key.lastIndexOf("."); - if (dotIndex > 0) { - this.key = key.substring(dotIndex + 1); - this.path = key.substring(0, dotIndex); - } else { - this.key = key; - } - } - } - - @Override - public String toString() { - return ROOT.toString(); + return null; + } + + /** Nullify object for garbage collection */ + public void flush() { + ROOT = null; + CACHED_OBJECT = null; + } + + @Override + public String toString() { + return ROOT.toString(); + } + + /** To hold key and path to find object. */ + private static class KeyPath { + private final String key; + private String path; + + public KeyPath(String key) { + int dotIndex = key.lastIndexOf("."); + if (dotIndex > 0) { + this.key = key.substring(dotIndex + 1); + this.path = key.substring(0, dotIndex); + } else { + this.key = key; + } } + } } diff --git a/src/main/java/com/javaquery/util/string/Strings.java b/src/main/java/com/javaquery/util/string/Strings.java index 5c1a00e..445f07a 100644 --- a/src/main/java/com/javaquery/util/string/Strings.java +++ b/src/main/java/com/javaquery/util/string/Strings.java @@ -12,131 +12,131 @@ */ public final class Strings { - public static final String EMPTY_STRING = ""; - private static final String UNSUPPORTED_ASCII_PATTERN = "[^\\x20-\\x7e]"; - private static final String UNSUPPORTED_UNICODE_PATTERN = "[\\uD83C-\\uDBFF\\uDC00-\\uDFFF]+"; + public static final String EMPTY_STRING = ""; + private static final String UNSUPPORTED_ASCII_PATTERN = "[^\\x20-\\x7e]"; + private static final String UNSUPPORTED_UNICODE_PATTERN = "[\\uD83C-\\uDBFF\\uDC00-\\uDFFF]+"; - private Strings() { - } + private Strings() {} - /** - * Returns {@code true} if the provided String is {@code null} or empty otherwise - * returns {@code false}. - * - * @param str a String to be checked against {@code null} or empty - * @return {@code true} if the provided String is {@code null} or empty - * otherwise {@code false} - */ - public static boolean nullOrEmpty(String str) { - return Objects.isNull(str) || str.trim().isEmpty(); - } + /** + * Returns {@code true} if the provided String is {@code null} or empty otherwise returns {@code + * false}. + * + * @param str a String to be checked against {@code null} or empty + * @return {@code true} if the provided String is {@code null} or empty otherwise {@code false} + */ + public static boolean nullOrEmpty(String str) { + return Objects.isNull(str) || str.trim().isEmpty(); + } - /** - * Returns {@code true} if the provided String is non-{@code null} and non-empty otherwise - * returns {@code false}. - * - * @param str a String to be checked against non-{@code null} and non-empty - * @return {@code true} if the provided String is non-{@code null} and non-empty - * otherwise {@code false} - */ - public static boolean nonNullNonEmpty(String str) { - return Objects.nonNull(str) && !str.trim().isEmpty(); - } + /** + * Returns {@code true} if the provided String is non-{@code null} and non-empty otherwise returns + * {@code false}. + * + * @param str a String to be checked against non-{@code null} and non-empty + * @return {@code true} if the provided String is non-{@code null} and non-empty otherwise {@code + * false} + */ + public static boolean nonNullNonEmpty(String str) { + return Objects.nonNull(str) && !str.trim().isEmpty(); + } - /** - * Returns trimmed - * - * @param str a String to trim - * @return trimmed String if provided String is non-{@code null} otherwise null - */ - public static String trimString(String str) { - return Objects.nonNull(str) ? str.trim() : null; - } + /** + * Returns trimmed + * + * @param str a String to trim + * @return trimmed String if provided String is non-{@code null} otherwise null + */ + public static String trimString(String str) { + return Objects.nonNull(str) ? str.trim() : null; + } - /** - * Returns joined string with provided separator - * - * @param separator a String used for joining multiple Strings - * @param strings array of String to join - * @return joined String - */ - public static String joinStrings(String separator, String... strings) { - if (Objects.nonNull(separator)) { - StringJoiner stringJoiner = new StringJoiner(separator); - if (Objects.nonNull(strings)) { - for (String str : strings) { - if (nonNullNonEmpty(str)) { - stringJoiner.add(str); - } - } - } - return stringJoiner.toString(); + /** + * Returns joined string with provided separator + * + * @param separator a String used for joining multiple Strings + * @param strings array of String to join + * @return joined String + */ + public static String joinStrings(String separator, String... strings) { + if (Objects.nonNull(separator)) { + StringJoiner stringJoiner = new StringJoiner(separator); + if (Objects.nonNull(strings)) { + for (String str : strings) { + if (nonNullNonEmpty(str)) { + stringJoiner.add(str); + } } - return null; + } + return stringJoiner.toString(); } + return null; + } - /** - * Returns joined string with provided separator - * - * @param separator a String used for joining multiple Strings - * @param strings array of String to join - * @return joined String - */ - public static String joinStringList(String separator, List strings) { - if (Objects.nonNull(separator)) { - StringJoiner stringJoiner = new StringJoiner(separator); - if (Collections.nonNullNonEmpty(strings)) { - for (String str : strings) { - if (nonNullNonEmpty(str)) { - stringJoiner.add(str); - } - } - } - return stringJoiner.toString(); + /** + * Returns joined string with provided separator + * + * @param separator a String used for joining multiple Strings + * @param strings array of String to join + * @return joined String + */ + public static String joinStringList(String separator, List strings) { + if (Objects.nonNull(separator)) { + StringJoiner stringJoiner = new StringJoiner(separator); + if (Collections.nonNullNonEmpty(strings)) { + for (String str : strings) { + if (nonNullNonEmpty(str)) { + stringJoiner.add(str); + } } - return null; + } + return stringJoiner.toString(); } + return null; + } - /** - * Returns {@code true} if the provided String is equalsIgnoreCase to [true, yes, y, 1] otherwise - * returns {@code false}. - * - * @param str a String to be checked against equalsIgnoreCase [true, yes, y, 1] - * @return {@code true} if the provided String is equalsIgnoreCase to [true, yes, y, 1] - * otherwise {@code false} - */ - public static boolean optBooleanFromString(String str) { - return "true".equalsIgnoreCase(str) || "yes".equalsIgnoreCase(str) || "y".equalsIgnoreCase(str) - || "1".equalsIgnoreCase(str); - } + /** + * Returns {@code true} if the provided String is equalsIgnoreCase to [true, yes, y, 1] otherwise + * returns {@code false}. + * + * @param str a String to be checked against equalsIgnoreCase [true, yes, y, 1] + * @return {@code true} if the provided String is equalsIgnoreCase to [true, yes, y, 1] otherwise + * {@code false} + */ + public static boolean optBooleanFromString(String str) { + return "true".equalsIgnoreCase(str) + || "yes".equalsIgnoreCase(str) + || "y".equalsIgnoreCase(str) + || "1".equalsIgnoreCase(str); + } - /** - * Returns String after removing not supported ASCII characters - * - * @param str a String to be checked for non ASCII Characters - * @return Returns String after removing non ASCII characters - *

- * reference: https://stackoverflow.com/questions/10574289/remove-non-ascii-characters-from-string-in-java - */ - public static String removeNotSupportedASCIICharacters(String str) { - if (nonNullNonEmpty(str)) { - return str.replaceAll(UNSUPPORTED_ASCII_PATTERN, ""); - } - return null; + /** + * Returns String after removing not supported ASCII characters + * + * @param str a String to be checked for non ASCII Characters + * @return Returns String after removing non ASCII characters + *

reference: + * https://stackoverflow.com/questions/10574289/remove-non-ascii-characters-from-string-in-java + */ + public static String removeNotSupportedASCIICharacters(String str) { + if (nonNullNonEmpty(str)) { + return str.replaceAll(UNSUPPORTED_ASCII_PATTERN, ""); } + return null; + } - /** - * Returns String after removing not supported Unicode Characters - * - * @param str a String to be checked for not supported Unicode Characters - * @return Returns String after removing not supported Unicode Characters - *

- * reference: https://stackoverflow.com/questions/24840667/what-is-the-regex-to-extract-all-the-emojis-from-a-string - */ - public static String removeNotSupportedUnicodeCharacters(String str) { - if (nonNullNonEmpty(str)) { - return str.replaceAll(UNSUPPORTED_UNICODE_PATTERN, ""); - } - return null; + /** + * Returns String after removing not supported Unicode Characters + * + * @param str a String to be checked for not supported Unicode Characters + * @return Returns String after removing not supported Unicode Characters + *

reference: + * https://stackoverflow.com/questions/24840667/what-is-the-regex-to-extract-all-the-emojis-from-a-string + */ + public static String removeNotSupportedUnicodeCharacters(String str) { + if (nonNullNonEmpty(str)) { + return str.replaceAll(UNSUPPORTED_UNICODE_PATTERN, ""); } + return null; + } } diff --git a/src/main/java/com/javaquery/util/time/DatePattern.java b/src/main/java/com/javaquery/util/time/DatePattern.java index 037a919..c503cd7 100644 --- a/src/main/java/com/javaquery/util/time/DatePattern.java +++ b/src/main/java/com/javaquery/util/time/DatePattern.java @@ -4,45 +4,44 @@ * @author vicky.thakor * @since 1.0 */ -public enum DatePattern implements DateTimeFormat{ - - Y_M_D("yyyyMMdd"), - Y_M_D_HMS("yyyyMMddHHmmss"), - Y_M_D_T__HMSZ("yyyyMMdd'T'HHmmss'Z'"), - - Y_M_D_1("yyyy-MM-dd"), - Y_M_D__HMS("yyyy-MM-dd HH:mm:ss"), - Y_M_D_HM("yyyy-MM-dd HH:mm"), - Y_M_D_HMZ("yyyy-MM-dd HH:mm'Z'"), - Y_M_D_HMSZ("yyyy-MM-dd HH:mm:ssZ"), - Y_M_D_HMS_Z("yyyy-MM-dd HH:mm:ss'Z'"), - Y_M_D_T_HMS("yyyy-MM-dd'T'HH:mm:ss"), - Y_M_D_T_HMSX("yyyy-MM-dd'T'HH:mm:ssXXX"), - Y_M_D_T_HMSZ("yyyy-MM-dd'T'HH:mm:ss'Z'"), - Y_M_D_T_HMSSSSSSSZ("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"), - Y_M_D_T_HMSSSSSSSHM("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS-HH:MM"), - Y_M_D_T_HMSSSSSSSX("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSX"), - Y_M_D_T_HMSSSSZ("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"), - - M_D_Y("MM-dd-yyyy"), - M_D_Y_1("MM/dd/yyyy"), - M_D_Y_HMS("MM/dd/yyyy HH:mm:ss"), - M_D_Y_HMSA("M/dd/yyyy hh:mm:ss a"), - - D_M_Y("dd-MM-yyyy"), - D_M_Y_HMSA("dd MMM yyyy hh:mm:ss a"), - D_M_Y_HMS("dd/MM/yyyy HH:mm:ss"), - MMM_DD_YYYY("MMM dd, yyyy"), - E_D_M_Y_HMS("EEE, dd MMM yyyy HH:mm:ss +0000"); - - private final String value; - - DatePattern(String value) { - this.value = value; - } - - @Override - public String getValue() { - return value; - } +public enum DatePattern implements DateTimeFormat { + Y_M_D("yyyyMMdd"), + Y_M_D_HMS("yyyyMMddHHmmss"), + Y_M_D_T__HMSZ("yyyyMMdd'T'HHmmss'Z'"), + + Y_M_D_1("yyyy-MM-dd"), + Y_M_D__HMS("yyyy-MM-dd HH:mm:ss"), + Y_M_D_HM("yyyy-MM-dd HH:mm"), + Y_M_D_HMZ("yyyy-MM-dd HH:mm'Z'"), + Y_M_D_HMSZ("yyyy-MM-dd HH:mm:ssZ"), + Y_M_D_HMS_Z("yyyy-MM-dd HH:mm:ss'Z'"), + Y_M_D_T_HMS("yyyy-MM-dd'T'HH:mm:ss"), + Y_M_D_T_HMSX("yyyy-MM-dd'T'HH:mm:ssXXX"), + Y_M_D_T_HMSZ("yyyy-MM-dd'T'HH:mm:ss'Z'"), + Y_M_D_T_HMSSSSSSSZ("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"), + Y_M_D_T_HMSSSSSSSHM("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS-HH:MM"), + Y_M_D_T_HMSSSSSSSX("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSX"), + Y_M_D_T_HMSSSSZ("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"), + + M_D_Y("MM-dd-yyyy"), + M_D_Y_1("MM/dd/yyyy"), + M_D_Y_HMS("MM/dd/yyyy HH:mm:ss"), + M_D_Y_HMSA("M/dd/yyyy hh:mm:ss a"), + + D_M_Y("dd-MM-yyyy"), + D_M_Y_HMSA("dd MMM yyyy hh:mm:ss a"), + D_M_Y_HMS("dd/MM/yyyy HH:mm:ss"), + MMM_DD_YYYY("MMM dd, yyyy"), + E_D_M_Y_HMS("EEE, dd MMM yyyy HH:mm:ss +0000"); + + private final String value; + + DatePattern(String value) { + this.value = value; + } + + @Override + public String getValue() { + return value; + } } diff --git a/src/main/java/com/javaquery/util/time/DateRange.java b/src/main/java/com/javaquery/util/time/DateRange.java index b1268cf..34aa3fe 100644 --- a/src/main/java/com/javaquery/util/time/DateRange.java +++ b/src/main/java/com/javaquery/util/time/DateRange.java @@ -8,26 +8,25 @@ */ public final class DateRange { - private Date startDate; - private Date endDate; + private Date startDate; + private Date endDate; - private DateRange() { - } + private DateRange() {} - public DateRange(Date startDate, Date endDate) { - this.startDate = startDate; - this.endDate = endDate; - } + public DateRange(Date startDate, Date endDate) { + this.startDate = startDate; + this.endDate = endDate; + } - public DateRange(Date startDate) { - this(startDate, new Date()); - } + public DateRange(Date startDate) { + this(startDate, new Date()); + } - public Date getStartDate() { - return startDate; - } + public Date getStartDate() { + return startDate; + } - public Date getEndDate() { - return endDate; - } + public Date getEndDate() { + return endDate; + } } diff --git a/src/main/java/com/javaquery/util/time/DateTimeFormat.java b/src/main/java/com/javaquery/util/time/DateTimeFormat.java index 8777539..affaa84 100644 --- a/src/main/java/com/javaquery/util/time/DateTimeFormat.java +++ b/src/main/java/com/javaquery/util/time/DateTimeFormat.java @@ -7,9 +7,9 @@ */ public interface DateTimeFormat { - /** - * @see DatePattern - * @return date time pattern to parse or format - */ - String getValue(); + /** + * @see DatePattern + * @return date time pattern to parse or format + */ + String getValue(); } diff --git a/src/main/java/com/javaquery/util/time/Dates.java b/src/main/java/com/javaquery/util/time/Dates.java index 59b7f14..1463ddb 100644 --- a/src/main/java/com/javaquery/util/time/Dates.java +++ b/src/main/java/com/javaquery/util/time/Dates.java @@ -14,228 +14,247 @@ */ public final class Dates { - public static final TimeZone SYSTEM_TIMEZONE = TimeZone.getDefault(); - private static final Calendar CALENDAR = Calendar.getInstance(); + public static final TimeZone SYSTEM_TIMEZONE = TimeZone.getDefault(); + private static final Calendar CALENDAR = Calendar.getInstance(); - private Dates() { - } + private Dates() {} - /** - * @return current time in milliseconds by using System.currentTimeMillis() - */ - public static long currentTimeMillis() { - return System.currentTimeMillis(); - } + /** @return current time in milliseconds by using System.currentTimeMillis() */ + public static long currentTimeMillis() { + return System.currentTimeMillis(); + } - /** - * Adds or subtracts the specified amount of time to the given Date. - * For example, to subtract 5 days from - * the given {@code Date} you can achieve it by calling: - *

addInDate(new Date(), Calendar.DAY_OF_MONTH, -5). - * - * @param date a {@code Date} to Adds or subtracts the specified amount of time - * @param type the calendar field. For example, {@code Calendar.DAY_OF_MONTH} - * @param amount the amount of date or time to be added to the field. - * @return Returns {@code Date} with addition or subtraction - */ - public static Date addInDate(Date date, int type, int amount) { - Calendar calendar = Calendar.getInstance(); - if (Objects.nonNull(date)) { - calendar.setTime(date); - calendar.add(type, amount); - } - return calendar.getTime(); + /** + * Adds or subtracts the specified amount of time to the given Date. For example, to subtract 5 + * days from the given {@code Date} you can achieve it by calling: + * + *

addInDate(new Date(), Calendar.DAY_OF_MONTH, -5). + * + * @param date a {@code Date} to Adds or subtracts the specified amount of time + * @param type the calendar field. For example, {@code Calendar.DAY_OF_MONTH} + * @param amount the amount of date or time to be added to the field. + * @return Returns {@code Date} with addition or subtraction + */ + public static Date addInDate(Date date, int type, int amount) { + Calendar calendar = Calendar.getInstance(); + if (Objects.nonNull(date)) { + calendar.setTime(date); + calendar.add(type, amount); } + return calendar.getTime(); + } - /** - * Adds or subtracts the specified amount of time to current {@code Date}. - * For example, to subtract 5 days from - * current {@code Date} you can achieve it by calling: - *

addInCurrentDate(Calendar.DAY_OF_MONTH, -5). - * - * @param type the calendar field. For example, {@code Calendar.DAY_OF_MONTH} - * @param amount the amount of date or time to be added to the field. - * @return Returns current {@code Date} with addition or subtraction - */ - public static Date addInCurrentDate(int type, int amount) { - return addInDate(new Date(), type, amount); - } + /** + * Adds or subtracts the specified amount of time to current {@code Date}. For example, to + * subtract 5 days from current {@code Date} you can achieve it by calling: + * + *

addInCurrentDate(Calendar.DAY_OF_MONTH, -5). + * + * @param type the calendar field. For example, {@code Calendar.DAY_OF_MONTH} + * @param amount the amount of date or time to be added to the field. + * @return Returns current {@code Date} with addition or subtraction + */ + public static Date addInCurrentDate(int type, int amount) { + return addInDate(new Date(), type, amount); + } - /** - * Adds the specified amount of time to the given Date. - * For example, to add 5 days from - * the given {@code Date} you can achieve it by calling: - *

increment(new Date(), Calendar.DAY_OF_MONTH, 5). - * - * @param date a {@code Date} to Adds the specified amount of time - * @param type the calendar field. For example, {@code Calendar.DAY_OF_MONTH} - * @param amount the amount of date or time to be added to the field. - * @return Returns {@code Date} with addition - * @see Dates#addInDate(Date, int, int) - */ - public static Date increment(Date date, int type, int amount) { - return addInDate(date, type, Math.abs(amount)); - } + /** + * Adds the specified amount of time to the given Date. For example, to add 5 days from the given + * {@code Date} you can achieve it by calling: + * + *

increment(new Date(), Calendar.DAY_OF_MONTH, 5). + * + * @param date a {@code Date} to Adds the specified amount of time + * @param type the calendar field. For example, {@code Calendar.DAY_OF_MONTH} + * @param amount the amount of date or time to be added to the field. + * @return Returns {@code Date} with addition + * @see Dates#addInDate(Date, int, int) + */ + public static Date increment(Date date, int type, int amount) { + return addInDate(date, type, Math.abs(amount)); + } - /** - * Subtracts the specified amount of time to the given Date. - * For example, to subtracts -5 days from - * the given {@code Date} you can achieve it by calling: - *

increment(new Date(), Calendar.DAY_OF_MONTH, -5). - * - * @param date a {@code Date} to Subtracts the specified amount of time - * @param type the calendar field. For example, {@code Calendar.DAY_OF_MONTH} - * @param amount the amount of date or time to be subtracts to the field. - * @return Returns {@code Date} with subtraction. - * @see Dates#addInDate(Date, int, int) - */ - public static Date reduce(Date date, int type, int amount) { - return addInDate(date, type, -Math.abs(amount)); - } + /** + * Subtracts the specified amount of time to the given Date. For example, to subtracts -5 days + * from the given {@code Date} you can achieve it by calling: + * + *

increment(new Date(), Calendar.DAY_OF_MONTH, -5). + * + * @param date a {@code Date} to Subtracts the specified amount of time + * @param type the calendar field. For example, {@code Calendar.DAY_OF_MONTH} + * @param amount the amount of date or time to be subtracts to the field. + * @return Returns {@code Date} with subtraction. + * @see Dates#addInDate(Date, int, int) + */ + public static Date reduce(Date date, int type, int amount) { + return addInDate(date, type, -Math.abs(amount)); + } - /** - * Returns {@code SimpleDateFormat} with given {@code DateTimeFormat} and {@code Timezone} - * - * @param dateTimeFormat a {@code DateTimeFormat} to set for {@code SimpleDateFormat} - * @param timeZone a {@code Timezone} to set for {@code SimpleDateFormat} - * @return Returns {@code SimpleDateFormat} with given {@code DateTimeFormat} and {@code Timezone} - */ - private static SimpleDateFormat getSimpleDateFormat(DateTimeFormat dateTimeFormat, TimeZone timeZone) { - SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateTimeFormat.getValue()); - simpleDateFormat.setTimeZone(timeZone); - return simpleDateFormat; - } + /** + * Returns {@code SimpleDateFormat} with given {@code DateTimeFormat} and {@code Timezone} + * + * @param dateTimeFormat a {@code DateTimeFormat} to set for {@code SimpleDateFormat} + * @param timeZone a {@code Timezone} to set for {@code SimpleDateFormat} + * @return Returns {@code SimpleDateFormat} with given {@code DateTimeFormat} and {@code Timezone} + */ + private static SimpleDateFormat getSimpleDateFormat( + DateTimeFormat dateTimeFormat, TimeZone timeZone) { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateTimeFormat.getValue()); + simpleDateFormat.setTimeZone(timeZone); + return simpleDateFormat; + } - /** - * Returns Date object of given String date using provided timezone, in case of ParseException - * it returns {@code null}. - * - * @param date a String date to parse - * @param dateTimeFormat pattern to parse the date - * @param timeZone timezone to parse the date - * @return Returns Date object of given String date using provided timezone, in case of ParseException - * it returns {@code null}. - */ - public static Date parse(String date, DateTimeFormat dateTimeFormat, TimeZone timeZone) { - SimpleDateFormat simpleDateFormat = getSimpleDateFormat(dateTimeFormat, timeZone); - try { - return simpleDateFormat.parse(date); - } catch (ParseException e) {/* Silent exception */} - return null; + /** + * Returns Date object of given String date using provided timezone, in case of ParseException it + * returns {@code null}. + * + * @param date a String date to parse + * @param dateTimeFormat pattern to parse the date + * @param timeZone timezone to parse the date + * @return Returns Date object of given String date using provided timezone, in case of + * ParseException it returns {@code null}. + */ + public static Date parse(String date, DateTimeFormat dateTimeFormat, TimeZone timeZone) { + SimpleDateFormat simpleDateFormat = getSimpleDateFormat(dateTimeFormat, timeZone); + try { + return simpleDateFormat.parse(date); + } catch (ParseException e) { + /* Silent exception */ } + return null; + } - /** - * Returns Date object of given String date using system timezone, in case of ParseException - * it returns {@code null}. - * - * @param date a String date to parse - * @param dateTimeFormat pattern to parse the date - * @return Returns Date object of given String date using system timezone, in case of ParseException - * it returns {@code null}. - */ - public static Date parse(String date, DateTimeFormat dateTimeFormat) { - return parse(date, dateTimeFormat, SYSTEM_TIMEZONE); - } + /** + * Returns Date object of given String date using system timezone, in case of ParseException it + * returns {@code null}. + * + * @param date a String date to parse + * @param dateTimeFormat pattern to parse the date + * @return Returns Date object of given String date using system timezone, in case of + * ParseException it returns {@code null}. + */ + public static Date parse(String date, DateTimeFormat dateTimeFormat) { + return parse(date, dateTimeFormat, SYSTEM_TIMEZONE); + } - /** - * Returns {@code Date} object in String, formatted by given {@code DateTimeFormat} and {@code TimeZone} - * - * @param date a {@code Date} object to format - * @param dateTimeFormat pattern to format {@code Date} - * @param timeZone {@code TimeZone} to use while formatting {@code Date} - * @return Returns {@code Date} object in String, formatted by given {@code DateTimeFormat} and {@code TimeZone} - */ - public static String format(Date date, DateTimeFormat dateTimeFormat, TimeZone timeZone) { - SimpleDateFormat simpleDateFormat = getSimpleDateFormat(dateTimeFormat, timeZone); - return simpleDateFormat.format(date); - } + /** + * Returns {@code Date} object in String, formatted by given {@code DateTimeFormat} and {@code + * TimeZone} + * + * @param date a {@code Date} object to format + * @param dateTimeFormat pattern to format {@code Date} + * @param timeZone {@code TimeZone} to use while formatting {@code Date} + * @return Returns {@code Date} object in String, formatted by given {@code DateTimeFormat} and + * {@code TimeZone} + */ + public static String format(Date date, DateTimeFormat dateTimeFormat, TimeZone timeZone) { + SimpleDateFormat simpleDateFormat = getSimpleDateFormat(dateTimeFormat, timeZone); + return simpleDateFormat.format(date); + } - /** - * Returns {@code Date} object in String, formatted by given {@code DateTimeFormat} and using - * system {@code TimeZone} - * - * @param date a {@code Date} object to format - * @param dateTimeFormat pattern to format {@code Date} - * @return Returns {@code Date} object in String, formatted by given {@code DateTimeFormat} and using - * system {@code TimeZone} - */ - public static String format(Date date, DateTimeFormat dateTimeFormat) { - return format(date, dateTimeFormat, SYSTEM_TIMEZONE); - } + /** + * Returns {@code Date} object in String, formatted by given {@code DateTimeFormat} and using + * system {@code TimeZone} + * + * @param date a {@code Date} object to format + * @param dateTimeFormat pattern to format {@code Date} + * @return Returns {@code Date} object in String, formatted by given {@code DateTimeFormat} and + * using system {@code TimeZone} + */ + public static String format(Date date, DateTimeFormat dateTimeFormat) { + return format(date, dateTimeFormat, SYSTEM_TIMEZONE); + } - /** - * Returns String {@code Date} by performing two operation on {@code Date} object, - * {@link Dates#addInDate(Date, int, int)} and {@link Dates#format(Date, DateTimeFormat)} - * - * @param date a {@code Date} object to format - * @param type the calendar field. For example, {@code Calendar.DAY_OF_MONTH} - * @param amount the amount of date or time to be added to the field. - * @param dateTimeFormat pattern to format {@code Date} - * @return Returns String {@code Date} by performing two operation on {@code Date} object, - * {@link Dates#addInDate(Date, int, int)} and {@link Dates#format(Date, DateTimeFormat)} - * @see Dates#addInDate(Date, int, int) - * @see Dates#format(Date, DateTimeFormat) - */ - public static String addInDateAndFormat(Date date, int type, int amount, DateTimeFormat dateTimeFormat) { - return format(addInDate(date, type, amount), dateTimeFormat); - } + /** + * Returns String {@code Date} by performing two operation on {@code Date} object, {@link + * Dates#addInDate(Date, int, int)} and {@link Dates#format(Date, DateTimeFormat)} + * + * @param date a {@code Date} object to format + * @param type the calendar field. For example, {@code Calendar.DAY_OF_MONTH} + * @param amount the amount of date or time to be added to the field. + * @param dateTimeFormat pattern to format {@code Date} + * @return Returns String {@code Date} by performing two operation on {@code Date} object, {@link + * Dates#addInDate(Date, int, int)} and {@link Dates#format(Date, DateTimeFormat)} + * @see Dates#addInDate(Date, int, int) + * @see Dates#format(Date, DateTimeFormat) + */ + public static String addInDateAndFormat( + Date date, int type, int amount, DateTimeFormat dateTimeFormat) { + return format(addInDate(date, type, amount), dateTimeFormat); + } - /** - * Returns provided {@code Date} object's epoch seconds - * - * @param date a {@code Date} to get epoch seconds of. - * @return Returns provided {@code Date} object's epoch seconds - */ - public static long epochSeconds(Date date) { - return date.getTime() / 1000; - } + /** + * Returns provided {@code Date} object's epoch seconds + * + * @param date a {@code Date} to get epoch seconds of. + * @return Returns provided {@code Date} object's epoch seconds + */ + public static long epochSeconds(Date date) { + return date.getTime() / 1000; + } - /** - * Returns {@code Date} with given year, month, day, hour, minute, seconds - * - * @param year year to set in date - * @param month month to set in date. - * Month value is 1-12. e.g., 1 for January. - * @param day day to set in date - * @param hour hour to set in date - * @param minute minute to set in date - * @param seconds seconds to set in date - * @return Returns {@code Date} with given year, month, day, hour, minute, seconds - */ - public static Date getDate(int year, int month, int day, int hour, int minute, int seconds) { - CALENDAR.set(year, --month, day, hour, minute, seconds); - return CALENDAR.getTime(); - } + /** + * Returns {@code Date} with given year, month, day, hour, minute, seconds + * + * @param year year to set in date + * @param month month to set in date. Month value is 1-12. e.g., 1 for January. + * @param day day to set in date + * @param hour hour to set in date + * @param minute minute to set in date + * @param seconds seconds to set in date + * @return Returns {@code Date} with given year, month, day, hour, minute, seconds + */ + public static Date getDate(int year, int month, int day, int hour, int minute, int seconds) { + CALENDAR.set(year, --month, day, hour, minute, seconds); + return CALENDAR.getTime(); + } - /** - * Returns {@code Date} with given year, month, day - * - * @param year year to set in date - * @param month month to set in date - * @param day day to set in date - * @return Returns {@code Date} with given year, month, day - */ - public static Date getDate(int year, int month, int day) { - return getDate(year, month, day, 0, 0, 0); - } + /** + * @return current Date object; + */ + public static Date current(){ + return new Date(); + } + + /** + * Returns {@code Date} with given year, month, day + * + * @param year year to set in date + * @param month month to set in date + * @param day day to set in date + * @return Returns {@code Date} with given year, month, day + */ + public static Date getDate(int year, int month, int day) { + return getDate(year, month, day, 0, 0, 0); + } - public enum Month { - JANUARY(1), FEBRUARY(2), MARCH(3), APRIL(4), MAY(5), JUNE(6), JULY(7), AUGUST(8), SEPTEMBER(9), OCTOBER(10), NOVEMBER( - 11), DECEMBER(12); + public enum Month { + JANUARY(1), + FEBRUARY(2), + MARCH(3), + APRIL(4), + MAY(5), + JUNE(6), + JULY(7), + AUGUST(8), + SEPTEMBER(9), + OCTOBER(10), + NOVEMBER(11), + DECEMBER(12); - private final static Calendar calendar = Calendar.getInstance(); - private final int value; + private static final Calendar calendar = Calendar.getInstance(); + private final int value; - Month(int value) { - this.value = value; - } + Month(int value) { + this.value = value; + } - public static Month currentMonth() { - return Month.values()[calendar.get(Calendar.MONTH)]; - } + public static Month currentMonth() { + return Month.values()[calendar.get(Calendar.MONTH)]; + } - public int getValue() { - return value; - } + public int getValue() { + return value; } + } } diff --git a/src/test/java/com/javaquery/util/TestAssert.java b/src/test/java/com/javaquery/util/TestAssert.java index 17438ad..d37484b 100644 --- a/src/test/java/com/javaquery/util/TestAssert.java +++ b/src/test/java/com/javaquery/util/TestAssert.java @@ -11,77 +11,106 @@ class TestAssert { - private static final RuntimeException RUNTIME_EXCEPTION = new RuntimeException("exception"); - private static final Object NULL_OBJECT = null; - private static final Object NON_NULL_OBJECT = new Object(); - private static final Collection EMPTY_COLLECTION = new ArrayList<>(0); - private static final Collection NON_EMPTY_COLLECTION = Collections.singletonList(1); - private static final Map EMPTY_MAP = new HashMap<>(0); - private static final Map NON_EMPTY_MAP = Collections.singletonMap(1, "A"); + private static final RuntimeException RUNTIME_EXCEPTION = new RuntimeException("exception"); + private static final Object NULL_OBJECT = null; + private static final Object NON_NULL_OBJECT = new Object(); + private static final Collection EMPTY_COLLECTION = new ArrayList<>(0); + private static final Collection NON_EMPTY_COLLECTION = Collections.singletonList(1); + private static final Map EMPTY_MAP = new HashMap<>(0); + private static final Map NON_EMPTY_MAP = Collections.singletonMap(1, "A"); - @Test - void test_nonNull() { - Assertions.assertDoesNotThrow(() -> Assert.nonNull(NON_NULL_OBJECT, TestAssert::getRuntimeException)); - Assertions.assertThrows(RuntimeException.class, () -> Assert.nonNull(NULL_OBJECT, TestAssert::getRuntimeException)); - Assertions.assertThrows(NullPointerException.class, () -> Assert.nonNull(NULL_OBJECT, null)); - } + private static RuntimeException getRuntimeException() { + return RUNTIME_EXCEPTION; + } - @Test - void test_isNull() { - Assertions.assertDoesNotThrow(() -> Assert.isNull(NULL_OBJECT, TestAssert::getRuntimeException)); - Assertions.assertThrows(RuntimeException.class, () -> Assert.isNull(NON_NULL_OBJECT, TestAssert::getRuntimeException)); - Assertions.assertThrows(NullPointerException.class, () -> Assert.isNull(NON_NULL_OBJECT, null)); - } + @Test + void test_nonNull() { + Assertions.assertDoesNotThrow( + () -> Assert.nonNull(NON_NULL_OBJECT, TestAssert::getRuntimeException)); + Assertions.assertThrows( + RuntimeException.class, () -> Assert.nonNull(NULL_OBJECT, TestAssert::getRuntimeException)); + Assertions.assertThrows(NullPointerException.class, () -> Assert.nonNull(NULL_OBJECT, null)); + } - @Test - void test_isTrue() { - Assertions.assertDoesNotThrow(() -> Assert.isTrue(true, TestAssert::getRuntimeException)); - Assertions.assertThrows(RuntimeException.class, () -> Assert.isTrue(false, TestAssert::getRuntimeException)); - Assertions.assertThrows(NullPointerException.class, () -> Assert.isTrue(false, null)); - } + @Test + void test_isNull() { + Assertions.assertDoesNotThrow( + () -> Assert.isNull(NULL_OBJECT, TestAssert::getRuntimeException)); + Assertions.assertThrows( + RuntimeException.class, + () -> Assert.isNull(NON_NULL_OBJECT, TestAssert::getRuntimeException)); + Assertions.assertThrows(NullPointerException.class, () -> Assert.isNull(NON_NULL_OBJECT, null)); + } - @Test - void test_isFalse() { - Assertions.assertDoesNotThrow(() -> Assert.isFalse(false, TestAssert::getRuntimeException)); - Assertions.assertThrows(RuntimeException.class, () -> Assert.isFalse(true, TestAssert::getRuntimeException)); - Assertions.assertThrows(NullPointerException.class, () -> Assert.isFalse(true, null)); - } + @Test + void test_isTrue() { + Assertions.assertDoesNotThrow(() -> Assert.isTrue(true, TestAssert::getRuntimeException)); + Assertions.assertThrows( + RuntimeException.class, () -> Assert.isTrue(false, TestAssert::getRuntimeException)); + Assertions.assertThrows(NullPointerException.class, () -> Assert.isTrue(false, null)); + } - @Test - void test_nonNullNonEmpty() { - Assertions.assertDoesNotThrow(() -> Assert.nonNullNonEmpty(NON_EMPTY_COLLECTION, TestAssert::getRuntimeException)); - Assertions.assertThrows(RuntimeException.class, () -> Assert.nonNullNonEmpty(null, TestAssert::getRuntimeException)); - Assertions.assertThrows(NullPointerException.class, () -> Assert.nonNullNonEmpty(null, null)); - Assertions.assertThrows(RuntimeException.class, () -> Assert.nonNullNonEmpty(EMPTY_COLLECTION, TestAssert::getRuntimeException)); - Assertions.assertThrows(NullPointerException.class, () -> Assert.nonNullNonEmpty(EMPTY_COLLECTION, null)); - } + @Test + void test_isFalse() { + Assertions.assertDoesNotThrow(() -> Assert.isFalse(false, TestAssert::getRuntimeException)); + Assertions.assertThrows( + RuntimeException.class, () -> Assert.isFalse(true, TestAssert::getRuntimeException)); + Assertions.assertThrows(NullPointerException.class, () -> Assert.isFalse(true, null)); + } - @Test - void test_nullOrEmpty() { - Assertions.assertDoesNotThrow(() -> Assert.nullOrEmpty(null, TestAssert::getRuntimeException)); - Assertions.assertDoesNotThrow(() -> Assert.nullOrEmpty(EMPTY_COLLECTION, TestAssert::getRuntimeException)); - Assertions.assertThrows(RuntimeException.class, () -> Assert.nullOrEmpty(NON_EMPTY_COLLECTION, TestAssert::getRuntimeException)); - Assertions.assertThrows(NullPointerException.class, () -> Assert.nullOrEmpty(NON_EMPTY_COLLECTION, null)); - } + @Test + void test_nonNullNonEmpty() { + Assertions.assertDoesNotThrow( + () -> Assert.nonNullNonEmpty(NON_EMPTY_COLLECTION, TestAssert::getRuntimeException)); + Assertions.assertThrows( + RuntimeException.class, + () -> Assert.nonNullNonEmpty(null, TestAssert::getRuntimeException)); + Assertions.assertThrows(NullPointerException.class, () -> Assert.nonNullNonEmpty(null, null)); + Assertions.assertThrows( + RuntimeException.class, + () -> Assert.nonNullNonEmpty(EMPTY_COLLECTION, TestAssert::getRuntimeException)); + Assertions.assertThrows( + NullPointerException.class, () -> Assert.nonNullNonEmpty(EMPTY_COLLECTION, null)); + } - @Test - void test_nonNullNonEmptyMap() { - Assertions.assertDoesNotThrow(() -> Assert.nonNullNonEmptyMap(NON_EMPTY_MAP, TestAssert::getRuntimeException)); - Assertions.assertThrows(RuntimeException.class, () -> Assert.nonNullNonEmptyMap(null, TestAssert::getRuntimeException)); - Assertions.assertThrows(NullPointerException.class, () -> Assert.nonNullNonEmptyMap(null, null)); - Assertions.assertThrows(RuntimeException.class, () -> Assert.nonNullNonEmptyMap(EMPTY_MAP, TestAssert::getRuntimeException)); - Assertions.assertThrows(NullPointerException.class, () -> Assert.nonNullNonEmptyMap(EMPTY_MAP, null)); - } + @Test + void test_nullOrEmpty() { + Assertions.assertDoesNotThrow(() -> Assert.nullOrEmpty(null, TestAssert::getRuntimeException)); + Assertions.assertDoesNotThrow( + () -> Assert.nullOrEmpty(EMPTY_COLLECTION, TestAssert::getRuntimeException)); + Assertions.assertThrows( + RuntimeException.class, + () -> Assert.nullOrEmpty(NON_EMPTY_COLLECTION, TestAssert::getRuntimeException)); + Assertions.assertThrows( + NullPointerException.class, () -> Assert.nullOrEmpty(NON_EMPTY_COLLECTION, null)); + } - @Test - void test_nullOrEmptyMap() { - Assertions.assertDoesNotThrow(() -> Assert.nullOrEmptyMap(null, TestAssert::getRuntimeException)); - Assertions.assertDoesNotThrow(() -> Assert.nullOrEmptyMap(EMPTY_MAP, TestAssert::getRuntimeException)); - Assertions.assertThrows(RuntimeException.class, () -> Assert.nullOrEmptyMap(NON_EMPTY_MAP, TestAssert::getRuntimeException)); - Assertions.assertThrows(NullPointerException.class, () -> Assert.nullOrEmptyMap(NON_EMPTY_MAP, null)); - } + @Test + void test_nonNullNonEmptyMap() { + Assertions.assertDoesNotThrow( + () -> Assert.nonNullNonEmptyMap(NON_EMPTY_MAP, TestAssert::getRuntimeException)); + Assertions.assertThrows( + RuntimeException.class, + () -> Assert.nonNullNonEmptyMap(null, TestAssert::getRuntimeException)); + Assertions.assertThrows( + NullPointerException.class, () -> Assert.nonNullNonEmptyMap(null, null)); + Assertions.assertThrows( + RuntimeException.class, + () -> Assert.nonNullNonEmptyMap(EMPTY_MAP, TestAssert::getRuntimeException)); + Assertions.assertThrows( + NullPointerException.class, () -> Assert.nonNullNonEmptyMap(EMPTY_MAP, null)); + } - private static RuntimeException getRuntimeException() { - return RUNTIME_EXCEPTION; - } + @Test + void test_nullOrEmptyMap() { + Assertions.assertDoesNotThrow( + () -> Assert.nullOrEmptyMap(null, TestAssert::getRuntimeException)); + Assertions.assertDoesNotThrow( + () -> Assert.nullOrEmptyMap(EMPTY_MAP, TestAssert::getRuntimeException)); + Assertions.assertThrows( + RuntimeException.class, + () -> Assert.nullOrEmptyMap(NON_EMPTY_MAP, TestAssert::getRuntimeException)); + Assertions.assertThrows( + NullPointerException.class, () -> Assert.nullOrEmptyMap(NON_EMPTY_MAP, null)); + } } diff --git a/src/test/java/com/javaquery/util/TestObjects.java b/src/test/java/com/javaquery/util/TestObjects.java index cfb0ef7..093d420 100644 --- a/src/test/java/com/javaquery/util/TestObjects.java +++ b/src/test/java/com/javaquery/util/TestObjects.java @@ -9,11 +9,20 @@ */ public class TestObjects { - @Test public void test_isNull() { - Assertions.assertTrue(Objects.isNull(null)); - } + @Test + public void test_isNull() { + Assertions.assertTrue(Objects.isNull(null)); + } - @Test public void test_NonNull() { - Assertions.assertTrue(Objects.nonNull(new Object())); - } + @Test + public void test_NonNull() { + Assertions.assertTrue(Objects.nonNull(new Object())); + } + + @Test + public void test_equals() { + Assertions.assertTrue(Objects.equals("a", "a")); + Assertions.assertTrue(Objects.equals(10, 10)); + Assertions.assertFalse(Objects.equals(10, 20)); + } } diff --git a/src/test/java/com/javaquery/util/TestRegex.java b/src/test/java/com/javaquery/util/TestRegex.java index 36b2de0..827753a 100644 --- a/src/test/java/com/javaquery/util/TestRegex.java +++ b/src/test/java/com/javaquery/util/TestRegex.java @@ -9,27 +9,30 @@ */ public class TestRegex { - @Test public void test_isNumber() { - Assertions.assertTrue(Regex.isNumber("0")); - Assertions.assertTrue(Regex.isNumber("25.34")); - Assertions.assertTrue(Regex.isNumber("-98.98")); - Assertions.assertFalse(Regex.isNumber("123AB")); - Assertions.assertFalse(Regex.isNumber(null)); - } + @Test + public void test_isNumber() { + Assertions.assertTrue(Regex.isNumber("0")); + Assertions.assertTrue(Regex.isNumber("25.34")); + Assertions.assertTrue(Regex.isNumber("-98.98")); + Assertions.assertFalse(Regex.isNumber("123AB")); + Assertions.assertFalse(Regex.isNumber(null)); + } - @Test public void test_isAlphaNumeric() { - Assertions.assertTrue(Regex.isAlphaNumeric("123AB")); - Assertions.assertTrue(Regex.isAlphaNumeric("123")); - Assertions.assertTrue(Regex.isAlphaNumeric("AB")); - Assertions.assertFalse(Regex.isAlphaNumeric("123#AB")); - Assertions.assertFalse(Regex.isAlphaNumeric("123 AB")); - } + @Test + public void test_isAlphaNumeric() { + Assertions.assertTrue(Regex.isAlphaNumeric("123AB")); + Assertions.assertTrue(Regex.isAlphaNumeric("123")); + Assertions.assertTrue(Regex.isAlphaNumeric("AB")); + Assertions.assertFalse(Regex.isAlphaNumeric("123#AB")); + Assertions.assertFalse(Regex.isAlphaNumeric("123 AB")); + } - @Test public void test_isValidEmail() { - Assertions.assertTrue(Regex.isValidEmail("vicky.thakor@javaquery.com")); - Assertions.assertTrue(Regex.isValidEmail("vicky.thakor@123.com")); - Assertions.assertFalse(Regex.isValidEmail("vicky.thakor@javaquery com")); - Assertions.assertFalse(Regex.isValidEmail("vicky.thakor@javaquery")); - Assertions.assertTrue(Regex.isValidEmail("fogawa@js6.so-net.ne.jp")); - } + @Test + public void test_isValidEmail() { + Assertions.assertTrue(Regex.isValidEmail("vicky.thakor@javaquery.com")); + Assertions.assertTrue(Regex.isValidEmail("vicky.thakor@123.com")); + Assertions.assertFalse(Regex.isValidEmail("vicky.thakor@javaquery com")); + Assertions.assertFalse(Regex.isValidEmail("vicky.thakor@javaquery")); + Assertions.assertTrue(Regex.isValidEmail("fogawa@js6.so-net.ne.jp")); + } } diff --git a/src/test/java/com/javaquery/util/TestUniqueIdGenerator.java b/src/test/java/com/javaquery/util/TestUniqueIdGenerator.java index 409d3b2..d6c3fb3 100644 --- a/src/test/java/com/javaquery/util/TestUniqueIdGenerator.java +++ b/src/test/java/com/javaquery/util/TestUniqueIdGenerator.java @@ -9,8 +9,8 @@ */ public class TestUniqueIdGenerator { - @Test - public void test_generate(){ - Assertions.assertNotNull(UniqueIdGenerator.generate()); - } + @Test + public void test_generate() { + Assertions.assertNotNull(UniqueIdGenerator.generate()); + } } diff --git a/src/test/java/com/javaquery/util/collection/TestCollections.java b/src/test/java/com/javaquery/util/collection/TestCollections.java index 0fff861..ea55724 100644 --- a/src/test/java/com/javaquery/util/collection/TestCollections.java +++ b/src/test/java/com/javaquery/util/collection/TestCollections.java @@ -18,135 +18,140 @@ */ public class TestCollections { - private static final List EMPTY_LIST = new ArrayList<>(1); - private static final List NULL_LIST = null; - private static final Set EMPTY_SET = new HashSet<>(1); - private static final Map EMPTY_MAP = new HashMap<>(1); - private static final Map NULL_MAP = null; - - @Test - public void test_nullOrEmpty() { - Assertions.assertTrue(Collections.nullOrEmpty(NULL_LIST)); - Assertions.assertTrue(Collections.nullOrEmpty(EMPTY_LIST)); - Assertions.assertFalse(Collections.nullOrEmpty(java.util.Collections.singletonList("A"))); - Assertions.assertTrue(Collections.nullOrEmpty(NULL_MAP)); - Assertions.assertTrue(Collections.nullOrEmpty(EMPTY_MAP)); - } - - @Test - public void test_nullOrEmpty_2() { - Map map = new HashMap<>(1); - map.put("Hello", "World"); - Assertions.assertFalse(Collections.nullOrEmpty(map)); - } - - @Test - public void test_nonNullNonEmpty() { - Assertions.assertTrue(Collections.nonNullNonEmpty(java.util.Collections.singletonList("A"))); - Assertions.assertFalse(Collections.nonNullNonEmpty(NULL_LIST)); - Assertions.assertFalse(Collections.nonNullNonEmpty(EMPTY_SET)); - } - - @Test - public void test_nonNullNonEmptyMap() { - Map map = new HashMap<>(1); - map.put("Hello", "World"); - Assertions.assertTrue(Collections.nonNullNonEmpty(map)); - - Assertions.assertFalse(Collections.nonNullNonEmpty(NULL_MAP)); - Assertions.assertFalse(Collections.nonNullNonEmpty(EMPTY_MAP)); - } - - @Test - public void test_batches_1() { - List listABCD = new ArrayList<>(); - listABCD.add("A"); - listABCD.add("B"); - listABCD.add("C"); - listABCD.add("D"); - listABCD.add("E"); - - AtomicInteger batchCounter = new AtomicInteger(0); - List result = new ArrayList<>(5); - Collections.batches(listABCD, 2).forEach(listOfString -> { - batchCounter.getAndIncrement(); - result.addAll(listOfString); - }); - Assertions.assertEquals(3, batchCounter.get()); - Assertions.assertEquals(5, result.size()); - Assertions.assertTrue(result.contains("E")); - } - - @Test - public void test_batches_2() { - List listABCD = new ArrayList<>(); - listABCD.add("A"); - listABCD.add("B"); - - AtomicInteger batchCounter = new AtomicInteger(0); - List result = new ArrayList<>(2); - Collections.batches(listABCD, 0).forEach(listOfString -> { - batchCounter.getAndIncrement(); - result.addAll(listOfString); - }); - Assertions.assertEquals(1, batchCounter.get()); - Assertions.assertEquals(2, result.size()); - Assertions.assertTrue(result.contains("A")); - } - - @Test - public void test_batches_3() { - Stream> stringStream = Collections.batches(EMPTY_LIST, 1); - Assertions.assertEquals(0, stringStream.count()); - - Assertions.assertThrows(IllegalArgumentException.class, () -> Collections.batches(null, 2)); - Assertions.assertThrows(IllegalArgumentException.class, () -> Collections.batches(EMPTY_LIST, -2)); - } - - @Test - public void test_isCollectionEqual() { - List listOne = new ArrayList<>(); - listOne.add("apple"); - - List listTwo = new ArrayList<>(); - listTwo.add("apple"); - - Assertions.assertTrue(Collections.isCollectionEqual(listOne, listTwo)); - } - - @Test - public void test_isCollectionEqual_1() { - Set setOne = new HashSet<>(); - setOne.add("apple"); - setOne.add("orange"); - - Set setTwo = new HashSet<>(); - setTwo.add("apple"); - - Assertions.assertFalse(Collections.isCollectionEqual(setOne, setTwo)); - } - - @Test - public void test_isCollectionEqual_2() { - Set setOne = new HashSet<>(); - setOne.add("orange"); - - Set setTwo = new HashSet<>(); - setTwo.add("apple"); - - Assertions.assertFalse(Collections.isCollectionEqual(setOne, setTwo)); - } - - @Test - public void test_isCollectionEqual_3() { - List setOne = new ArrayList<>(); - setOne.add("orange"); - setOne.add("orange"); - - Set setTwo = new HashSet<>(); - setTwo.add(null); - setTwo.add("apple"); - - Assertions.assertFalse(Collections.isCollectionEqual(setOne, setTwo)); - } + private static final List EMPTY_LIST = new ArrayList<>(1); + private static final List NULL_LIST = null; + private static final Set EMPTY_SET = new HashSet<>(1); + private static final Map EMPTY_MAP = new HashMap<>(1); + private static final Map NULL_MAP = null; + + @Test + public void test_nullOrEmpty() { + Assertions.assertTrue(Collections.nullOrEmpty(NULL_LIST)); + Assertions.assertTrue(Collections.nullOrEmpty(EMPTY_LIST)); + Assertions.assertFalse(Collections.nullOrEmpty(java.util.Collections.singletonList("A"))); + Assertions.assertTrue(Collections.nullOrEmpty(NULL_MAP)); + Assertions.assertTrue(Collections.nullOrEmpty(EMPTY_MAP)); + } + + @Test + public void test_nullOrEmpty_2() { + Map map = new HashMap<>(1); + map.put("Hello", "World"); + Assertions.assertFalse(Collections.nullOrEmpty(map)); + } + + @Test + public void test_nonNullNonEmpty() { + Assertions.assertTrue(Collections.nonNullNonEmpty(java.util.Collections.singletonList("A"))); + Assertions.assertFalse(Collections.nonNullNonEmpty(NULL_LIST)); + Assertions.assertFalse(Collections.nonNullNonEmpty(EMPTY_SET)); + } + + @Test + public void test_nonNullNonEmptyMap() { + Map map = new HashMap<>(1); + map.put("Hello", "World"); + Assertions.assertTrue(Collections.nonNullNonEmpty(map)); + + Assertions.assertFalse(Collections.nonNullNonEmpty(NULL_MAP)); + Assertions.assertFalse(Collections.nonNullNonEmpty(EMPTY_MAP)); + } + + @Test + public void test_batches_1() { + List listABCD = new ArrayList<>(); + listABCD.add("A"); + listABCD.add("B"); + listABCD.add("C"); + listABCD.add("D"); + listABCD.add("E"); + + AtomicInteger batchCounter = new AtomicInteger(0); + List result = new ArrayList<>(5); + Collections.batches(listABCD, 2) + .forEach( + listOfString -> { + batchCounter.getAndIncrement(); + result.addAll(listOfString); + }); + Assertions.assertEquals(3, batchCounter.get()); + Assertions.assertEquals(5, result.size()); + Assertions.assertTrue(result.contains("E")); + } + + @Test + public void test_batches_2() { + List listABCD = new ArrayList<>(); + listABCD.add("A"); + listABCD.add("B"); + + AtomicInteger batchCounter = new AtomicInteger(0); + List result = new ArrayList<>(2); + Collections.batches(listABCD, 0) + .forEach( + listOfString -> { + batchCounter.getAndIncrement(); + result.addAll(listOfString); + }); + Assertions.assertEquals(1, batchCounter.get()); + Assertions.assertEquals(2, result.size()); + Assertions.assertTrue(result.contains("A")); + } + + @Test + public void test_batches_3() { + Stream> stringStream = Collections.batches(EMPTY_LIST, 1); + Assertions.assertEquals(0, stringStream.count()); + + Assertions.assertThrows(IllegalArgumentException.class, () -> Collections.batches(null, 2)); + Assertions.assertThrows( + IllegalArgumentException.class, () -> Collections.batches(EMPTY_LIST, -2)); + } + + @Test + public void test_isCollectionEqual() { + List listOne = new ArrayList<>(); + listOne.add("apple"); + + List listTwo = new ArrayList<>(); + listTwo.add("apple"); + + Assertions.assertTrue(Collections.isCollectionEqual(listOne, listTwo)); + } + + @Test + public void test_isCollectionEqual_1() { + Set setOne = new HashSet<>(); + setOne.add("apple"); + setOne.add("orange"); + + Set setTwo = new HashSet<>(); + setTwo.add("apple"); + + Assertions.assertFalse(Collections.isCollectionEqual(setOne, setTwo)); + } + + @Test + public void test_isCollectionEqual_2() { + Set setOne = new HashSet<>(); + setOne.add("orange"); + + Set setTwo = new HashSet<>(); + setTwo.add("apple"); + + Assertions.assertFalse(Collections.isCollectionEqual(setOne, setTwo)); + } + + @Test + public void test_isCollectionEqual_3() { + List setOne = new ArrayList<>(); + setOne.add("orange"); + setOne.add("orange"); + + Set setTwo = new HashSet<>(); + setTwo.add(null); + setTwo.add("apple"); + + Assertions.assertFalse(Collections.isCollectionEqual(setOne, setTwo)); + } } diff --git a/src/test/java/com/javaquery/util/io/TestConsole.java b/src/test/java/com/javaquery/util/io/TestConsole.java index c171633..a0a961b 100644 --- a/src/test/java/com/javaquery/util/io/TestConsole.java +++ b/src/test/java/com/javaquery/util/io/TestConsole.java @@ -8,13 +8,13 @@ */ public class TestConsole { - @Test - public void test_log(){ - Console.log("Hello World!"); - } + @Test + public void test_log() { + Console.log("Hello World!"); + } - @Test - public void test_error(){ - Console.error("Hello World!"); - } + @Test + public void test_error() { + Console.error("Hello World!"); + } } diff --git a/src/test/java/com/javaquery/util/io/TestFiles.java b/src/test/java/com/javaquery/util/io/TestFiles.java index 7044460..1a5c1f9 100644 --- a/src/test/java/com/javaquery/util/io/TestFiles.java +++ b/src/test/java/com/javaquery/util/io/TestFiles.java @@ -12,137 +12,148 @@ */ public class TestFiles { - private static final String TMP_DIR = System.getProperty("java.io.tmpdir"); - private static final String TEMP_DATA = "Hello World"; - private static final String INVALID_PATH = "T2:" + File.separatorChar + "javaquery.txt"; - private static final String DEMO_JSON_DATA = "{\"name\": \"vicky thakor\"}"; - - @Test - public void test_createNewFile() { - File file = new File(getTemporaryFilePath()); - Assertions.assertTrue(Files.createNewFile(file)); - file.delete(); - } - - @Test - public void test_createNewFile_1() { - Assertions.assertFalse(Files.createNewFile(new File(INVALID_PATH))); - } - - @Test - public void test_createNewFile_2() { - Assertions.assertThrows(NullPointerException.class, () -> Files.createNewFile(null)); - } - - @Test - public void test_deleteAndCreateNewFile() { - File file = new File(getTemporaryFilePath()); - Files.createNewFile(file); - Assertions.assertTrue(Files.deleteAndCreateNewFile(file)); - file.delete(); - } - - @Test - public void test_deleteAndCreateNewFile_1() { - Assertions.assertThrows(NullPointerException.class, () -> Files.deleteAndCreateNewFile(null)); - } - - @Test - public void test_writeToFile() { - File file = new File(getTemporaryFilePath()); - Files.writeToFile(file, TEMP_DATA); - String result = Files.readFromFile(file); - Assertions.assertEquals(TEMP_DATA, result); - file.delete(); - } - - @Test - public void test_writeToFile_1() { - // Silent exception logged and for code coverage - Files.writeToFile(new File(INVALID_PATH), TEMP_DATA); - } - - @Test - public void test_writeToFile_2() { - Assertions.assertThrows(NullPointerException.class, () -> Files.writeToFile(null, TEMP_DATA)); - Assertions.assertThrows(NullPointerException.class, () -> Files.writeToFile(new File(getTemporaryFilePath()), null)); - } - - @Test - public void test_appendToFile() { - File file = new File(getTemporaryFilePath()); - Files.writeToFile(file, "Hello"); - Files.appendToFile(file, " World", false); - String result = Files.readFromFile(file); - Assertions.assertEquals(TEMP_DATA, result); - file.delete(); - } - - @Test - public void test_appendToFile_1() { - File file = new File(getTemporaryFilePath()); - Files.appendToFile(file, "Hello", true); - Files.appendToFile(file, "World", false); - String result = Files.readFromFile(file); - Assertions.assertEquals("Hello\nWorld", result); - file.delete(); - } - - @Test - public void test_appendToFile_2() { - // Silent exception logged and for code coverage - Files.appendToFile(new File(INVALID_PATH), TEMP_DATA, false); - } - - @Test - public void test_appendToFile_3() { - Assertions.assertThrows(NullPointerException.class, () -> Files.appendToFile(null, TEMP_DATA, false)); - Assertions.assertThrows(NullPointerException.class, () -> Files.appendToFile(new File(getTemporaryFilePath()), null, false)); - } - - @Test - public void test_readFromFile() { - File file = new File(getTemporaryFilePath()); - Files.writeToFile(file, TEMP_DATA); - String result = Files.readFromFile(file); - Assertions.assertEquals(TEMP_DATA, result); - file.delete(); - } - - @Test - public void test_readFromFile_1() { - // Silent exception logged and for code coverage - String result = Files.readFromFile(new File(INVALID_PATH)); - Assertions.assertNull(result); - } - - @Test - public void test_readFromFile_2() { - Assertions.assertThrows(NullPointerException.class, () -> Files.readFromFile(null)); - } - - @Test - public void test_loadResource(){ - String result = new Files().loadResource("/sample/demo.json"); - Assertions.assertEquals(DEMO_JSON_DATA, result); - } - - @Test - public void test_loadResource_1(){ - Assertions.assertNull(new Files().loadResource("file-not-exist.json")); - } - - @Test - public void test_loadResource_2(){ - Assertions.assertThrows(NullPointerException.class, ()-> new Files().loadResource(null)); - } - - @Test - public void test_loadResource_3(){ - Assertions.assertNull(new Files().loadResource(" ")); - } - - private String getTemporaryFilePath() { - return TMP_DIR + File.separatorChar + "javaquery" + File.separatorChar + "javaquery_" + UUID.randomUUID().toString() + ".txt"; - } + private static final String TMP_DIR = System.getProperty("java.io.tmpdir"); + private static final String TEMP_DATA = "Hello World"; + private static final String INVALID_PATH = "T2:" + File.separatorChar + "javaquery.txt"; + private static final String DEMO_JSON_DATA = "{\"name\": \"vicky thakor\"}"; + + @Test + public void test_createNewFile() { + File file = new File(getTemporaryFilePath()); + Assertions.assertTrue(Files.createNewFile(file)); + file.delete(); + } + + @Test + public void test_createNewFile_1() { + Assertions.assertFalse(Files.createNewFile(new File(INVALID_PATH))); + } + + @Test + public void test_createNewFile_2() { + Assertions.assertThrows(NullPointerException.class, () -> Files.createNewFile(null)); + } + + @Test + public void test_deleteAndCreateNewFile() { + File file = new File(getTemporaryFilePath()); + Files.createNewFile(file); + Assertions.assertTrue(Files.deleteAndCreateNewFile(file)); + file.delete(); + } + + @Test + public void test_deleteAndCreateNewFile_1() { + Assertions.assertThrows(NullPointerException.class, () -> Files.deleteAndCreateNewFile(null)); + } + + @Test + public void test_writeToFile() { + File file = new File(getTemporaryFilePath()); + Files.writeToFile(file, TEMP_DATA); + String result = Files.readFromFile(file); + Assertions.assertEquals(TEMP_DATA, result); + file.delete(); + } + + @Test + public void test_writeToFile_1() { + // Silent exception logged and for code coverage + Files.writeToFile(new File(INVALID_PATH), TEMP_DATA); + } + + @Test + public void test_writeToFile_2() { + Assertions.assertThrows(NullPointerException.class, () -> Files.writeToFile(null, TEMP_DATA)); + Assertions.assertThrows( + NullPointerException.class, + () -> Files.writeToFile(new File(getTemporaryFilePath()), null)); + } + + @Test + public void test_appendToFile() { + File file = new File(getTemporaryFilePath()); + Files.writeToFile(file, "Hello"); + Files.appendToFile(file, " World", false); + String result = Files.readFromFile(file); + Assertions.assertEquals(TEMP_DATA, result); + file.delete(); + } + + @Test + public void test_appendToFile_1() { + File file = new File(getTemporaryFilePath()); + Files.appendToFile(file, "Hello", true); + Files.appendToFile(file, "World", false); + String result = Files.readFromFile(file); + Assertions.assertEquals("Hello\nWorld", result); + file.delete(); + } + + @Test + public void test_appendToFile_2() { + // Silent exception logged and for code coverage + Files.appendToFile(new File(INVALID_PATH), TEMP_DATA, false); + } + + @Test + public void test_appendToFile_3() { + Assertions.assertThrows( + NullPointerException.class, () -> Files.appendToFile(null, TEMP_DATA, false)); + Assertions.assertThrows( + NullPointerException.class, + () -> Files.appendToFile(new File(getTemporaryFilePath()), null, false)); + } + + @Test + public void test_readFromFile() { + File file = new File(getTemporaryFilePath()); + Files.writeToFile(file, TEMP_DATA); + String result = Files.readFromFile(file); + Assertions.assertEquals(TEMP_DATA, result); + file.delete(); + } + + @Test + public void test_readFromFile_1() { + // Silent exception logged and for code coverage + String result = Files.readFromFile(new File(INVALID_PATH)); + Assertions.assertNull(result); + } + + @Test + public void test_readFromFile_2() { + Assertions.assertThrows(NullPointerException.class, () -> Files.readFromFile(null)); + } + + @Test + public void test_loadResource() { + String result = new Files().loadResource("/sample/demo.json"); + Assertions.assertEquals(DEMO_JSON_DATA, result); + } + + @Test + public void test_loadResource_1() { + Assertions.assertNull(new Files().loadResource("file-not-exist.json")); + } + + @Test + public void test_loadResource_2() { + Assertions.assertThrows(NullPointerException.class, () -> new Files().loadResource(null)); + } + + @Test + public void test_loadResource_3() { + Assertions.assertNull(new Files().loadResource(" ")); + } + + private String getTemporaryFilePath() { + return TMP_DIR + + File.separatorChar + + "javaquery" + + File.separatorChar + + "javaquery_" + + UUID.randomUUID().toString() + + ".txt"; + } } diff --git a/src/test/java/com/javaquery/util/io/TestJFile.java b/src/test/java/com/javaquery/util/io/TestJFile.java index 0f236f2..f3fe6fe 100644 --- a/src/test/java/com/javaquery/util/io/TestJFile.java +++ b/src/test/java/com/javaquery/util/io/TestJFile.java @@ -15,70 +15,70 @@ */ public class TestJFile { - private static final String TEMP_DIR = System.getProperty("java.io.tmpdir"); + private static final String TEMP_DIR = System.getProperty("java.io.tmpdir"); - @Test - public void test_getExtension(){ - JFile jFile = new JFile(TEMP_DIR + File.separatorChar + randomFileName(".txt")); - Assertions.assertEquals("txt", jFile.getExtension()); - } + @Test + public void test_getExtension() { + JFile jFile = new JFile(TEMP_DIR + File.separatorChar + randomFileName(".txt")); + Assertions.assertEquals("txt", jFile.getExtension()); + } - @Test - public void test_getExtension_1(){ - JFile jFile = new JFile(TEMP_DIR + File.separatorChar + randomFileName(null)); - Assertions.assertEquals("", jFile.getExtension()); - } + @Test + public void test_getExtension_1() { + JFile jFile = new JFile(TEMP_DIR + File.separatorChar + randomFileName(null)); + Assertions.assertEquals("", jFile.getExtension()); + } - @Test - public void test_rename() throws IOException { - String renameFile = "hello-world.log"; - JFile jFile = new JFile(TEMP_DIR + File.separatorChar + randomFileName(".txt")); - if(jFile.createNewFile()){ - jFile = jFile.rename(renameFile); - Assertions.assertEquals(renameFile, jFile.getName()); - } - jFile.delete(); + @Test + public void test_rename() throws IOException { + String renameFile = "hello-world.log"; + JFile jFile = new JFile(TEMP_DIR + File.separatorChar + randomFileName(".txt")); + if (jFile.createNewFile()) { + jFile = jFile.rename(renameFile); + Assertions.assertEquals(renameFile, jFile.getName()); } + jFile.delete(); + } - @Test - public void test_rename_1() { - JFile jFile = new JFile(TEMP_DIR + File.separatorChar + randomFileName(".txt")); - Assertions.assertThrows(NullPointerException.class, () -> jFile.rename(null)); - } + @Test + public void test_rename_1() { + JFile jFile = new JFile(TEMP_DIR + File.separatorChar + randomFileName(".txt")); + Assertions.assertThrows(NullPointerException.class, () -> jFile.rename(null)); + } - @Test - public void test_rename_2() { - JFile jFile = new JFile(TEMP_DIR + File.separatorChar + randomFileName(".txt")); - Assertions.assertNull(jFile.rename("hello-world.log")); - } + @Test + public void test_rename_2() { + JFile jFile = new JFile(TEMP_DIR + File.separatorChar + randomFileName(".txt")); + Assertions.assertNull(jFile.rename("hello-world.log")); + } - @Test - public void test_write_read_append() { - JFile jFile = new JFile(TEMP_DIR + File.separatorChar + randomFileName(".txt")); - jFile.write("hello"); + @Test + public void test_write_read_append() { + JFile jFile = new JFile(TEMP_DIR + File.separatorChar + randomFileName(".txt")); + jFile.write("hello"); - String data = jFile.read(); - Assertions.assertEquals("hello", data); + String data = jFile.read(); + Assertions.assertEquals("hello", data); - jFile.append("world!", false); - String appendedData = jFile.read(); - Assertions.assertEquals("helloworld!", appendedData); - jFile.delete(); - } + jFile.append("world!", false); + String appendedData = jFile.read(); + Assertions.assertEquals("helloworld!", appendedData); + jFile.delete(); + } - @Test - public void test_attributes() { - JFile jFile = new JFile(TEMP_DIR + File.separatorChar + randomFileName(".txt")); - jFile.addAttribute("hello", "world"); - Assertions.assertEquals("world", jFile.optAttribute("hello", "oh snap!")); + @Test + public void test_attributes() { + JFile jFile = new JFile(TEMP_DIR + File.separatorChar + randomFileName(".txt")); + jFile.addAttribute("hello", "world"); + Assertions.assertEquals("world", jFile.optAttribute("hello", "oh snap!")); - Map map = new HashMap<>(1); - map.put("1", "2"); - jFile.addAllAttribute(map); - Assertions.assertEquals(2, jFile.getAttributes().size()); - } + Map map = new HashMap<>(1); + map.put("1", "2"); + jFile.addAllAttribute(map); + Assertions.assertEquals(2, jFile.getAttributes().size()); + } - private String randomFileName(String suffix){ - return UUID.randomUUID().toString().replace("-", "") + suffix; - } + private String randomFileName(String suffix) { + return UUID.randomUUID().toString().replace("-", "") + suffix; + } } diff --git a/src/test/java/com/javaquery/util/json/TestJSONEnum.java b/src/test/java/com/javaquery/util/json/TestJSONEnum.java index df589ad..92794e0 100644 --- a/src/test/java/com/javaquery/util/json/TestJSONEnum.java +++ b/src/test/java/com/javaquery/util/json/TestJSONEnum.java @@ -5,5 +5,6 @@ * @since 1.0.4 */ public enum TestJSONEnum { - Regular, Chocolate + Regular, + Chocolate } diff --git a/src/test/java/com/javaquery/util/json/TestJSONObject.java b/src/test/java/com/javaquery/util/json/TestJSONObject.java index 59654f4..5c5eaaa 100644 --- a/src/test/java/com/javaquery/util/json/TestJSONObject.java +++ b/src/test/java/com/javaquery/util/json/TestJSONObject.java @@ -1,6 +1,7 @@ package com.javaquery.util.json; -import com.javaquery.util.io.Console; +import com.javaquery.util.time.DatePattern; +import com.javaquery.util.time.Dates; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -8,6 +9,7 @@ import java.math.BigDecimal; import java.math.BigInteger; +import java.util.Date; /** * @author vicky.thakor @@ -15,101 +17,124 @@ */ @TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestJSONObject { - private static final String STRING_JSON_OBJECT = "{\"author\":\"vicky\",\"items\":{\"item\":[{\"ppu\":0.55,\"batters\":{\"batter\":[{\"available\":true,\"id\":\"1001\",\"type\":\"Regular\"},{\"available\":false,\"id\":\"1002\",\"type\":\"Chocolate\"},{\"id\":\"1003\",\"type\":\"Blueberry\"},{\"id\":\"1004\",\"type\":\"Devil's Food\"}]},\"name\":\"Cake\",\"id\":\"0001\",\"type\":\"donut\",\"topping\":[{\"id\":\"5001\",\"type\":\"None\"},{\"id\":\"5002\",\"type\":\"Glazed\"},{\"id\":\"5005\",\"type\":\"Sugar\",\"kg\":652398},{\"id\":\"5007\",\"type\":\"Powdered Sugar\",\"kg\":875},{\"id\":\"5006\",\"type\":\"Chocolate with Sprinkles\"},{\"id\":\"5003\",\"type\":\"Chocolate\"},{\"id\":\"5004\",\"type\":\"Maple\"}]}]}}"; - private static final JSONObject JSONOBJECT = new JSONObject(STRING_JSON_OBJECT); - - @Test - public void test_optBoolean() { - Assertions.assertTrue(JSONOBJECT.optBoolean("items.item[0].batters.batter[0].available")); - Assertions.assertTrue(JSONOBJECT.optBoolean("items.item[0].batters.batter[2].available", true)); - } - - @Test - public void test_optBigDecimal() { - Assertions.assertEquals(new BigDecimal(652398), JSONOBJECT.optBigDecimal("items.item[0].topping[2].kg", new BigDecimal(0))); - Assertions.assertEquals(new BigDecimal(-1), JSONOBJECT.optBigDecimal("items.item[0].topping[2].gm", new BigDecimal(-1))); - } - - @Test - public void test_optBigInteger() { - Assertions.assertEquals(BigInteger.valueOf(652398L), JSONOBJECT.optBigInteger("items.item[0].topping[2].kg", BigInteger.valueOf(0L))); - Assertions.assertEquals(BigInteger.valueOf(-1), JSONOBJECT.optBigInteger("items.item[0].topping[2].gm", BigInteger.valueOf(-1L))); - } - - @Test - public void test_optDouble() { - Assertions.assertEquals(875d, JSONOBJECT.optDouble("items.item[0].topping[3].kg")); - Assertions.assertEquals(-1d, JSONOBJECT.optDouble("items.item[0].topping[2].gm", -1)); - } - - @Test - public void test_optEnum() { - Assertions.assertEquals(TestJSONEnum.Regular, JSONOBJECT.optEnum(TestJSONEnum.class, "items.item[0].batters.batter[0].type")); - Assertions.assertEquals(TestJSONEnum.Chocolate, JSONOBJECT.optEnum(TestJSONEnum.class, "items.item[0].batters.batter[2].type", TestJSONEnum.Chocolate)); - } - - @Test - public void test_optFloat() { - Assertions.assertEquals(875f, JSONOBJECT.optFloat("items.item[0].topping[3].kg")); - Assertions.assertEquals(-1f, JSONOBJECT.optFloat("items.item[0].topping[2].gm", -1)); - } - - @Test - public void test_optInt() { - Assertions.assertEquals(875, JSONOBJECT.optInt("items.item[0].topping[3].kg")); - Assertions.assertEquals(-1, JSONOBJECT.optInt("items.item[0].topping[2].gm", -1)); - } - - @Test - public void test_optLong() { - Assertions.assertEquals(875L, JSONOBJECT.optLong("items.item[0].topping[3].kg")); - Assertions.assertEquals(-1L, JSONOBJECT.optLong("items.item[0].topping[2].gm", -1)); - } - - @Test - public void test_optNumber() { - Assertions.assertEquals(875, JSONOBJECT.optNumber("items.item[0].topping[3].kg")); - Assertions.assertEquals(-1, JSONOBJECT.optNumber("items.item[0].topping[2].gm", -1)); - } - - @Test - public void test_optString() { - Assertions.assertEquals("donut", JSONOBJECT.optString("items.item[0].type")); - Assertions.assertEquals("test", JSONOBJECT.optString("items.item[0].topping[1].value", "test")); - Assertions.assertEquals("vicky", JSONOBJECT.optString("author")); - } - - @Test - public void test_optJSONObject() { - org.json.JSONObject jsonObject = JSONOBJECT.optJSONObject("items.item[0].batters.batter[0]"); - Assertions.assertEquals("Regular", jsonObject.optString("type")); - } - - @Test - public void test_optJSONObject_1() { - org.json.JSONObject jsonObject = JSONOBJECT.optJSONObject("items.dummy[0].batters.batter[0]"); - Assertions.assertNull(jsonObject); - } - - @Test - public void test_optJSONObject_2() { - org.json.JSONObject jsonObject = JSONOBJECT.optJSONObject("items.item.batters.batter[0]"); - Assertions.assertNull(jsonObject); - } - - @Test - public void test_optJSONArray() { - org.json.JSONArray jsonArray = JSONOBJECT.optJSONArray("items.item[0].batters.batter"); - Assertions.assertEquals(4, jsonArray.length()); - } - - @Test - public void test_toString(){ - Assertions.assertEquals(STRING_JSON_OBJECT, JSONOBJECT.toString()); - } - - @AfterAll - public void test_flush(){ - JSONOBJECT.flush(); - } + private static final String STRING_JSON_OBJECT = + "{\"author\":\"vicky\",\"created\":\"2021-01-20 10:00:10\",\"items\":{\"item\":[{\"ppu\":0.55,\"batters\":{\"batter\":[{\"available\":true,\"id\":\"1001\",\"type\":\"Regular\"},{\"available\":false,\"id\":\"1002\",\"type\":\"Chocolate\"},{\"id\":\"1003\",\"type\":\"Blueberry\"},{\"id\":\"1004\",\"type\":\"Devil's Food\"}]},\"name\":\"Cake\",\"id\":\"0001\",\"type\":\"donut\",\"topping\":[{\"id\":\"5001\",\"type\":\"None\"},{\"id\":\"5002\",\"type\":\"Glazed\"},{\"id\":\"5005\",\"type\":\"Sugar\",\"kg\":652398},{\"id\":\"5007\",\"type\":\"Powdered Sugar\",\"kg\":875},{\"id\":\"5006\",\"type\":\"Chocolate with Sprinkles\"},{\"id\":\"5003\",\"type\":\"Chocolate\"},{\"id\":\"5004\",\"type\":\"Maple\"}]}]}}"; + private static final JSONObject JSONOBJECT = new JSONObject(STRING_JSON_OBJECT); + + @Test + public void test_optBoolean() { + Assertions.assertTrue(JSONOBJECT.optBoolean("items.item[0].batters.batter[0].available")); + Assertions.assertTrue(JSONOBJECT.optBoolean("items.item[0].batters.batter[2].available", true)); + } + + @Test + public void test_optBigDecimal() { + Assertions.assertEquals( + new BigDecimal(652398), + JSONOBJECT.optBigDecimal("items.item[0].topping[2].kg", new BigDecimal(0))); + Assertions.assertEquals( + new BigDecimal(-1), + JSONOBJECT.optBigDecimal("items.item[0].topping[2].gm", new BigDecimal(-1))); + } + + @Test + public void test_optBigInteger() { + Assertions.assertEquals( + BigInteger.valueOf(652398L), + JSONOBJECT.optBigInteger("items.item[0].topping[2].kg", BigInteger.valueOf(0L))); + Assertions.assertEquals( + BigInteger.valueOf(-1), + JSONOBJECT.optBigInteger("items.item[0].topping[2].gm", BigInteger.valueOf(-1L))); + } + + @Test + public void test_optDouble() { + Assertions.assertEquals(875d, JSONOBJECT.optDouble("items.item[0].topping[3].kg")); + Assertions.assertEquals(-1d, JSONOBJECT.optDouble("items.item[0].topping[2].gm", -1)); + } + + @Test + public void test_optDate() { + Date date = Dates.parse("2021-01-20 10:00:10", DatePattern.Y_M_D__HMS); + Assertions.assertNotNull(JSONOBJECT.optDate("item.created", DatePattern.Y_M_D__HMS)); + Assertions.assertEquals(date, JSONOBJECT.optDate("created", DatePattern.Y_M_D__HMS)); + Assertions.assertEquals( + date, JSONOBJECT.optDate("items.created", DatePattern.Y_M_D__HMS, date)); + } + + @Test + public void test_optEnum() { + Assertions.assertEquals( + TestJSONEnum.Regular, + JSONOBJECT.optEnum(TestJSONEnum.class, "items.item[0].batters.batter[0].type")); + Assertions.assertEquals( + TestJSONEnum.Chocolate, + JSONOBJECT.optEnum( + TestJSONEnum.class, "items.item[0].batters.batter[2].type", TestJSONEnum.Chocolate)); + } + + @Test + public void test_optFloat() { + Assertions.assertEquals(875f, JSONOBJECT.optFloat("items.item[0].topping[3].kg")); + Assertions.assertEquals(-1f, JSONOBJECT.optFloat("items.item[0].topping[2].gm", -1)); + } + + @Test + public void test_optInt() { + Assertions.assertEquals(875, JSONOBJECT.optInt("items.item[0].topping[3].kg")); + Assertions.assertEquals(-1, JSONOBJECT.optInt("items.item[0].topping[2].gm", -1)); + } + + @Test + public void test_optLong() { + Assertions.assertEquals(875L, JSONOBJECT.optLong("items.item[0].topping[3].kg")); + Assertions.assertEquals(-1L, JSONOBJECT.optLong("items.item[0].topping[2].gm", -1)); + } + + @Test + public void test_optNumber() { + Assertions.assertEquals(875, JSONOBJECT.optNumber("items.item[0].topping[3].kg")); + Assertions.assertEquals(-1, JSONOBJECT.optNumber("items.item[0].topping[2].gm", -1)); + } + + @Test + public void test_optString() { + Assertions.assertEquals("donut", JSONOBJECT.optString("items.item[0].type")); + Assertions.assertEquals("test", JSONOBJECT.optString("items.item[0].topping[1].value", "test")); + Assertions.assertEquals("vicky", JSONOBJECT.optString("author")); + } + + @Test + public void test_optJSONObject() { + org.json.JSONObject jsonObject = JSONOBJECT.optJSONObject("items.item[0].batters.batter[0]"); + Assertions.assertEquals("Regular", jsonObject.optString("type")); + } + + @Test + public void test_optJSONObject_1() { + org.json.JSONObject jsonObject = JSONOBJECT.optJSONObject("items.dummy[0].batters.batter[0]"); + Assertions.assertNull(jsonObject); + } + + @Test + public void test_optJSONObject_2() { + org.json.JSONObject jsonObject = JSONOBJECT.optJSONObject("items.item.batters.batter[0]"); + Assertions.assertNull(jsonObject); + } + + @Test + public void test_optJSONArray() { + org.json.JSONArray jsonArray = JSONOBJECT.optJSONArray("items.item[0].batters.batter"); + Assertions.assertEquals(4, jsonArray.length()); + } + + @Test + public void test_toString() { + Assertions.assertEquals(STRING_JSON_OBJECT, JSONOBJECT.toString()); + } + + @AfterAll + public void test_flush() { + JSONOBJECT.flush(); + } } diff --git a/src/test/java/com/javaquery/util/sample/demo.json b/src/test/java/com/javaquery/util/sample/demo.json index ea8a97f..e36949e 100644 --- a/src/test/java/com/javaquery/util/sample/demo.json +++ b/src/test/java/com/javaquery/util/sample/demo.json @@ -1 +1,3 @@ -{"name": "vicky thakor"} \ No newline at end of file +{ + "name": "vicky thakor" +} \ No newline at end of file diff --git a/src/test/java/com/javaquery/util/string/TestStrings.java b/src/test/java/com/javaquery/util/string/TestStrings.java index b1df54b..d6c5538 100644 --- a/src/test/java/com/javaquery/util/string/TestStrings.java +++ b/src/test/java/com/javaquery/util/string/TestStrings.java @@ -11,58 +11,68 @@ */ public class TestStrings { - private static final String HELLO = "Hello World!"; - - @Test public void test_nullOrEmpty() { - Assertions.assertTrue(Strings.nullOrEmpty(null)); - Assertions.assertTrue(Strings.nullOrEmpty("")); - Assertions.assertFalse(Strings.nullOrEmpty(HELLO)); - } - - @Test public void test_nonNullNonEmpty() { - Assertions.assertTrue(Strings.nonNullNonEmpty(HELLO)); - Assertions.assertFalse(Strings.nonNullNonEmpty(null)); - Assertions.assertFalse(Strings.nonNullNonEmpty("")); - } - - @Test public void test_trimString() { - String str = " Hello World! "; - Assertions.assertEquals(HELLO, Strings.trimString(str)); - } - - @Test public void test_joinStrings() { - String result = "Hello,World,!"; - Assertions.assertEquals(result, Strings.joinStrings(",", "Hello", "World", "!")); - - Assertions.assertNull(Strings.joinStrings(null, "Hello", "World", "!")); - Assertions.assertEquals("", Strings.joinStrings(",")); - } - - @Test public void test_joinStringList() { - String result = "Hello,World,!"; - Assertions.assertEquals(result, Strings.joinStringList(",", Arrays.asList("Hello", "World", "!"))); - - Assertions.assertNull(Strings.joinStringList(null, Arrays.asList("Hello", "World", "!"))); - Assertions.assertEquals("", Strings.joinStringList(",", null)); - } - - @Test public void test_optBooleanFromString() { - Assertions.assertTrue(Strings.optBooleanFromString("TRUE")); - Assertions.assertTrue(Strings.optBooleanFromString("yes")); - Assertions.assertFalse(Strings.optBooleanFromString(HELLO)); - } - - @Test public void test_removeNotSupportedASCIICharacters() { - String str = "�ttrigeSomerzischeruchtanb"; - Assertions.assertEquals("ttrigeSomerzischeruchtanb", Strings.removeNotSupportedASCIICharacters(str)); - - Assertions.assertNull(Strings.removeNotSupportedASCIICharacters(null)); - } - - @Test public void test_removeNotSupportedUnicodeCharacters() { - String str = "Thats a nice joke\uD83D\uDE06\uD83D\uDE06\uD83D\uDE06 \uD83D\uDE1B"; - Assertions.assertEquals("Thats a nice joke ", Strings.removeNotSupportedUnicodeCharacters(str)); - - Assertions.assertNull(null, Strings.removeNotSupportedUnicodeCharacters(null)); - } + private static final String HELLO = "Hello World!"; + + @Test + public void test_nullOrEmpty() { + Assertions.assertTrue(Strings.nullOrEmpty(null)); + Assertions.assertTrue(Strings.nullOrEmpty("")); + Assertions.assertFalse(Strings.nullOrEmpty(HELLO)); + } + + @Test + public void test_nonNullNonEmpty() { + Assertions.assertTrue(Strings.nonNullNonEmpty(HELLO)); + Assertions.assertFalse(Strings.nonNullNonEmpty(null)); + Assertions.assertFalse(Strings.nonNullNonEmpty("")); + } + + @Test + public void test_trimString() { + String str = " Hello World! "; + Assertions.assertEquals(HELLO, Strings.trimString(str)); + } + + @Test + public void test_joinStrings() { + String result = "Hello,World,!"; + Assertions.assertEquals(result, Strings.joinStrings(",", "Hello", "World", "!")); + + Assertions.assertNull(Strings.joinStrings(null, "Hello", "World", "!")); + Assertions.assertEquals("", Strings.joinStrings(",")); + } + + @Test + public void test_joinStringList() { + String result = "Hello,World,!"; + Assertions.assertEquals( + result, Strings.joinStringList(",", Arrays.asList("Hello", "World", "!"))); + + Assertions.assertNull(Strings.joinStringList(null, Arrays.asList("Hello", "World", "!"))); + Assertions.assertEquals("", Strings.joinStringList(",", null)); + } + + @Test + public void test_optBooleanFromString() { + Assertions.assertTrue(Strings.optBooleanFromString("TRUE")); + Assertions.assertTrue(Strings.optBooleanFromString("yes")); + Assertions.assertFalse(Strings.optBooleanFromString(HELLO)); + } + + @Test + public void test_removeNotSupportedASCIICharacters() { + String str = "�ttrigeSomerzischeruchtanb"; + Assertions.assertEquals( + "ttrigeSomerzischeruchtanb", Strings.removeNotSupportedASCIICharacters(str)); + + Assertions.assertNull(Strings.removeNotSupportedASCIICharacters(null)); + } + + @Test + public void test_removeNotSupportedUnicodeCharacters() { + String str = "Thats a nice joke\uD83D\uDE06\uD83D\uDE06\uD83D\uDE06 \uD83D\uDE1B"; + Assertions.assertEquals("Thats a nice joke ", Strings.removeNotSupportedUnicodeCharacters(str)); + + Assertions.assertNull(null, Strings.removeNotSupportedUnicodeCharacters(null)); + } } diff --git a/src/test/java/com/javaquery/util/time/TestDateRange.java b/src/test/java/com/javaquery/util/time/TestDateRange.java index 3f3bda7..b35e4df 100644 --- a/src/test/java/com/javaquery/util/time/TestDateRange.java +++ b/src/test/java/com/javaquery/util/time/TestDateRange.java @@ -11,22 +11,22 @@ */ public class TestDateRange { - @Test - public void test_constructor() { - Date startDate = new Date(); - Date endDate = new Date(); + @Test + public void test_constructor() { + Date startDate = new Date(); + Date endDate = new Date(); - DateRange dateRange = new DateRange(startDate, endDate); - Assertions.assertEquals(startDate, dateRange.getStartDate()); - Assertions.assertEquals(endDate, dateRange.getEndDate()); - } + DateRange dateRange = new DateRange(startDate, endDate); + Assertions.assertEquals(startDate, dateRange.getStartDate()); + Assertions.assertEquals(endDate, dateRange.getEndDate()); + } - @Test - public void test_constructor_1() { - Date startDate = new Date(); + @Test + public void test_constructor_1() { + Date startDate = new Date(); - DateRange dateRange = new DateRange(startDate); - Assertions.assertEquals(startDate, dateRange.getStartDate()); - Assertions.assertNotNull(dateRange.getEndDate()); - } + DateRange dateRange = new DateRange(startDate); + Assertions.assertEquals(startDate, dateRange.getStartDate()); + Assertions.assertNotNull(dateRange.getEndDate()); + } } diff --git a/src/test/java/com/javaquery/util/time/TestDates.java b/src/test/java/com/javaquery/util/time/TestDates.java index 3cd87e0..84a11cf 100644 --- a/src/test/java/com/javaquery/util/time/TestDates.java +++ b/src/test/java/com/javaquery/util/time/TestDates.java @@ -13,168 +13,177 @@ */ public class TestDates { - private static final Calendar CALENDAR = Calendar.getInstance(); - - @Test - public void test_currentTimeMillis() { - long expected = System.currentTimeMillis(); - long result = Dates.currentTimeMillis(); - long difference = result - expected; - Assertions.assertTrue(difference >= 0 && difference < 5); - } - - @Test - public void test_addInDate() { - Date date = Dates.parse("2021-01-19", DatePattern.Y_M_D_1); - Date expected = Dates.parse("2021-01-20", DatePattern.Y_M_D_1); - - Date result = Dates.addInDate(date, Calendar.DATE, 1); - Assertions.assertEquals(expected, result); - } - - @Test - public void test_addInDate_1() { - Date date = Dates.parse("2021-01-19", DatePattern.Y_M_D_1); - Date expected = Dates.parse("2020-12-19", DatePattern.Y_M_D_1); - - Date result = Dates.addInDate(date, Calendar.MONTH, -1); - Assertions.assertEquals(expected, result); - } - - @Test - public void test_increment() { - Date date = Dates.parse("2021-01-20 10:10:00", DatePattern.Y_M_D__HMS); - Date expected = Dates.parse("2021-01-20 10:20:00", DatePattern.Y_M_D__HMS); - - Date result = Dates.increment(date, Calendar.MINUTE, 10); - Assertions.assertEquals(expected, result); - } - - @Test - public void test_increment_1() { - Date date = Dates.parse("2021-01-20 10:10:00", DatePattern.Y_M_D__HMS); - Date expected = Dates.parse("2021-01-20 10:10:10", DatePattern.Y_M_D__HMS); - - Date result = Dates.increment(date, Calendar.SECOND, -10); - Assertions.assertEquals(expected, result); - } - - @Test - public void test_reduce() { - Date date = Dates.parse("2021-01-20 10:00:00", DatePattern.Y_M_D__HMS); - Date expected = Dates.parse("2021-01-20 09:50:00", DatePattern.Y_M_D__HMS); - - Date result = Dates.reduce(date, Calendar.MINUTE, -10); - Assertions.assertEquals(expected, result); - } - - @Test - public void test_reduce_1() { - Date date = Dates.parse("2021-01-20 10:00:10", DatePattern.Y_M_D__HMS); - Date expected = Dates.parse("2021-01-20 10:00:00", DatePattern.Y_M_D__HMS); - - Date result = Dates.reduce(date, Calendar.SECOND, 10); - Assertions.assertEquals(expected, result); - } - - @Test - public void test_addInCurrentDate() { - Date date = Dates.addInCurrentDate(Calendar.YEAR, 1); - CALENDAR.setTime(date); - - int currentYear = Calendar.getInstance().get(Calendar.YEAR); - - Assertions.assertEquals(currentYear + 1, CALENDAR.get(Calendar.YEAR)); - } - - @Test - public void test_addInCurrentDate_1() { - Date date = Dates.addInCurrentDate(Calendar.YEAR, -5); - CALENDAR.setTime(date); - - int currentYear = Calendar.getInstance().get(Calendar.YEAR); - - Assertions.assertEquals(currentYear - 5, CALENDAR.get(Calendar.YEAR)); - } - - @Test - public void test_parse() { - Date date = Dates.parse("2021-01-20T10:10:00+05:30", DatePattern.Y_M_D_T_HMSX, TimeZone.getTimeZone("UTC")); - CALENDAR.setTime(date); //Output: Wed Jan 20 04:40:00 UTC 2021 - - Assertions.assertEquals(2021, CALENDAR.get(Calendar.YEAR)); - Assertions.assertEquals(1, CALENDAR.get(Calendar.MONTH) + 1); - Assertions.assertEquals(20, CALENDAR.get(Calendar.DATE)); - Assertions.assertEquals(4, CALENDAR.get(Calendar.HOUR)); - Assertions.assertEquals(40, CALENDAR.get(Calendar.MINUTE)); - Assertions.assertEquals(0, CALENDAR.get(Calendar.SECOND)); - } - - @Test - public void test_parse_1() { - Date date = Dates.parse("2021-01-19", DatePattern.Y_M_D_1); - CALENDAR.setTime(date); - - Assertions.assertEquals(2021, CALENDAR.get(Calendar.YEAR)); - Assertions.assertEquals(1, CALENDAR.get(Calendar.MONTH) + 1); - Assertions.assertEquals(19, CALENDAR.get(Calendar.DATE)); - } - - @Test - public void test_parse_2() { - Date date = Dates.parse("2021-19", DatePattern.Y_M_D_1); - Assertions.assertNull(date); - } - - @Test - public void test_format() { - Date date = Dates.parse("2021-01-20T04:40:00+00:00", DatePattern.Y_M_D_T_HMSX, TimeZone.getTimeZone("UTC")); - String result = Dates.format(date, DatePattern.Y_M_D_T_HMSX, TimeZone.getTimeZone("IST")); - Assertions.assertEquals("2021-01-20T10:10:00+05:30", result); - } - - @Test - public void test_format_1() { - Date date = Dates.parse("2021-01-20T10:10:00", DatePattern.Y_M_D_T_HMS); - String result = Dates.format(date, DatePattern.Y_M_D_HMS); - Assertions.assertEquals("20210120101000", result); - } - - @Test - public void test_addInDateAndFormat() { - Date date = Dates.parse("2021-01-20T10:10:00", DatePattern.Y_M_D_T_HMS); - String result = Dates.addInDateAndFormat(date, Calendar.MONTH, -1, DatePattern.Y_M_D_HMS); - Assertions.assertEquals("20201220101000", result); - } - - @Test - public void test_dateToEpochSeconds() { - Date date = Dates.parse("2021-01-20T10:10:00", DatePattern.Y_M_D_T_HMS); - long result = Dates.epochSeconds(date); - Assertions.assertEquals(1611137400, result); - } - - @Test - public void test_getDate() { - Date result = Dates.getDate(2020, 1, 20, 10, 10, 10); - Assertions.assertEquals("Mon Jan 20 10:10:10 UTC 2020", result.toString()); - } - - @Test - public void test_getDate_1() { - Date result = Dates.getDate(2020, 1, 20); - Assertions.assertEquals("Mon Jan 20 00:00:00 UTC 2020", result.toString()); - } - - @Test - public void test_Month() { - Assertions.assertEquals(1, Dates.Month.JANUARY.getValue()); - } - - @Test - public void test_Month_currentMonth() { - int expected = Calendar.getInstance().get(Calendar.MONTH) + 1; - - Assertions.assertEquals(expected, Dates.Month.currentMonth().getValue()); - } + private static final Calendar CALENDAR = Calendar.getInstance(); + + @Test + public void test_currentTimeMillis() { + long expected = System.currentTimeMillis(); + long result = Dates.currentTimeMillis(); + long difference = result - expected; + Assertions.assertTrue(difference >= 0 && difference < 5); + } + + @Test + public void test_addInDate() { + Date date = Dates.parse("2021-01-19", DatePattern.Y_M_D_1); + Date expected = Dates.parse("2021-01-20", DatePattern.Y_M_D_1); + + Date result = Dates.addInDate(date, Calendar.DATE, 1); + Assertions.assertEquals(expected, result); + } + + @Test + public void test_addInDate_1() { + Date date = Dates.parse("2021-01-19", DatePattern.Y_M_D_1); + Date expected = Dates.parse("2020-12-19", DatePattern.Y_M_D_1); + + Date result = Dates.addInDate(date, Calendar.MONTH, -1); + Assertions.assertEquals(expected, result); + } + + @Test + public void test_increment() { + Date date = Dates.parse("2021-01-20 10:10:00", DatePattern.Y_M_D__HMS); + Date expected = Dates.parse("2021-01-20 10:20:00", DatePattern.Y_M_D__HMS); + + Date result = Dates.increment(date, Calendar.MINUTE, 10); + Assertions.assertEquals(expected, result); + } + + @Test + public void test_increment_1() { + Date date = Dates.parse("2021-01-20 10:10:00", DatePattern.Y_M_D__HMS); + Date expected = Dates.parse("2021-01-20 10:10:10", DatePattern.Y_M_D__HMS); + + Date result = Dates.increment(date, Calendar.SECOND, -10); + Assertions.assertEquals(expected, result); + } + + @Test + public void test_reduce() { + Date date = Dates.parse("2021-01-20 10:00:00", DatePattern.Y_M_D__HMS); + Date expected = Dates.parse("2021-01-20 09:50:00", DatePattern.Y_M_D__HMS); + + Date result = Dates.reduce(date, Calendar.MINUTE, -10); + Assertions.assertEquals(expected, result); + } + + @Test + public void test_reduce_1() { + Date date = Dates.parse("2021-01-20 10:00:10", DatePattern.Y_M_D__HMS); + Date expected = Dates.parse("2021-01-20 10:00:00", DatePattern.Y_M_D__HMS); + + Date result = Dates.reduce(date, Calendar.SECOND, 10); + Assertions.assertEquals(expected, result); + } + + @Test + public void test_addInCurrentDate() { + Date date = Dates.addInCurrentDate(Calendar.YEAR, 1); + CALENDAR.setTime(date); + + int currentYear = Calendar.getInstance().get(Calendar.YEAR); + + Assertions.assertEquals(currentYear + 1, CALENDAR.get(Calendar.YEAR)); + } + + @Test + public void test_addInCurrentDate_1() { + Date date = Dates.addInCurrentDate(Calendar.YEAR, -5); + CALENDAR.setTime(date); + + int currentYear = Calendar.getInstance().get(Calendar.YEAR); + + Assertions.assertEquals(currentYear - 5, CALENDAR.get(Calendar.YEAR)); + } + + @Test + public void test_parse() { + Date date = + Dates.parse( + "2021-01-20T10:10:00+05:30", DatePattern.Y_M_D_T_HMSX, TimeZone.getTimeZone("UTC")); + CALENDAR.setTime(date); // Output: Wed Jan 20 04:40:00 UTC 2021 + + Assertions.assertEquals(2021, CALENDAR.get(Calendar.YEAR)); + Assertions.assertEquals(1, CALENDAR.get(Calendar.MONTH) + 1); + Assertions.assertEquals(20, CALENDAR.get(Calendar.DATE)); + Assertions.assertEquals(4, CALENDAR.get(Calendar.HOUR)); + Assertions.assertEquals(40, CALENDAR.get(Calendar.MINUTE)); + Assertions.assertEquals(0, CALENDAR.get(Calendar.SECOND)); + } + + @Test + public void test_parse_1() { + Date date = Dates.parse("2021-01-19", DatePattern.Y_M_D_1); + CALENDAR.setTime(date); + + Assertions.assertEquals(2021, CALENDAR.get(Calendar.YEAR)); + Assertions.assertEquals(1, CALENDAR.get(Calendar.MONTH) + 1); + Assertions.assertEquals(19, CALENDAR.get(Calendar.DATE)); + } + + @Test + public void test_parse_2() { + Date date = Dates.parse("2021-19", DatePattern.Y_M_D_1); + Assertions.assertNull(date); + } + + @Test + public void test_format() { + Date date = + Dates.parse( + "2021-01-20T04:40:00+00:00", DatePattern.Y_M_D_T_HMSX, TimeZone.getTimeZone("UTC")); + String result = Dates.format(date, DatePattern.Y_M_D_T_HMSX, TimeZone.getTimeZone("IST")); + Assertions.assertEquals("2021-01-20T10:10:00+05:30", result); + } + + @Test + public void test_format_1() { + Date date = Dates.parse("2021-01-20T10:10:00", DatePattern.Y_M_D_T_HMS); + String result = Dates.format(date, DatePattern.Y_M_D_HMS); + Assertions.assertEquals("20210120101000", result); + } + + @Test + public void test_addInDateAndFormat() { + Date date = Dates.parse("2021-01-20T10:10:00", DatePattern.Y_M_D_T_HMS); + String result = Dates.addInDateAndFormat(date, Calendar.MONTH, -1, DatePattern.Y_M_D_HMS); + Assertions.assertEquals("20201220101000", result); + } + + @Test + public void test_dateToEpochSeconds() { + Date date = Dates.parse("2021-01-20T10:10:00", DatePattern.Y_M_D_T_HMS); + long result = Dates.epochSeconds(date); + Assertions.assertEquals(1611137400, result); + } + + @Test + public void test_getDate() { + Date result = Dates.getDate(2020, 1, 20, 10, 10, 10); + Assertions.assertEquals("Mon Jan 20 10:10:10 UTC 2020", result.toString()); + } + + @Test + public void test_getDate_1() { + Date result = Dates.getDate(2020, 1, 20); + Assertions.assertEquals("Mon Jan 20 00:00:00 UTC 2020", result.toString()); + } + + @Test + public void test_current(){ + Assertions.assertNotNull(Dates.current()); + } + + @Test + public void test_Month() { + Assertions.assertEquals(1, Dates.Month.JANUARY.getValue()); + } + + @Test + public void test_Month_currentMonth() { + int expected = Calendar.getInstance().get(Calendar.MONTH) + 1; + + Assertions.assertEquals(expected, Dates.Month.currentMonth().getValue()); + } }