diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4834363 --- /dev/null +++ b/.gitignore @@ -0,0 +1,33 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/** +!**/src/test/** +gradle.properties + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/README.md b/README.md index e69de29..b7d5976 100644 --- a/README.md +++ b/README.md @@ -0,0 +1,4 @@ +### CUBETIQ Commom Utils Module +- [x] Utils for Java and Kotlin +- [x] Custom Extension for Kotlin +- [ ] More... \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..ee9882d --- /dev/null +++ b/build.gradle @@ -0,0 +1,48 @@ +plugins { + id 'java' + id 'org.jetbrains.kotlin.jvm' version '1.3.72' + id 'maven' +} + +group 'com.cubetiqs' +version '1.0-SNAPSHOT' + +repositories { + mavenCentral() + maven { + url "https://oss-internal.cubetiqs.com/repository/maven-public/" + } +} + +dependencies { + implementation project(':cubetiq-parent') + implementation project(':cubetiq-logging') + + // required by :cubetiq-logging module + implementation 'org.apache.logging.log4j:log4j-core:2.13.3' + implementation 'org.apache.commons:commons-text:1.8' + + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8" + + testCompile group: 'junit', name: 'junit', version: '4.12' +} + +compileKotlin { + kotlinOptions.jvmTarget = "1.8" +} +compileTestKotlin { + kotlinOptions.jvmTarget = "1.8" +} + +uploadArchives { + repositories { + mavenDeployer { + repository(url: "${nexusUrl}/repository/maven-releases/") { + authentication(userName: nexusUsername, password: nexusPassword) + } + snapshotRepository(url: "${nexusUrl}/repository/maven-snapshots") { + authentication(userName: nexusUsername, password: nexusPassword) + } + } + } +} \ No newline at end of file diff --git a/gradle.properties.sample b/gradle.properties.sample new file mode 100644 index 0000000..6494df5 --- /dev/null +++ b/gradle.properties.sample @@ -0,0 +1,3 @@ +nexusUrl=https://oss-internal.cubetiqs.com +nexusUsername=user +nexusPassword=pass \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..f3d88b1 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..d2353c6 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,10 @@ +#Mon Jun 08 15:30:03 ICT 2020 +distributionUrl=https\://services.gradle.org/distributions/gradle-6.4.1-all.zip +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStorePath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME + +nexusUrl=https://oss-internal.cubetiqs.com +nexusUsername=cubetiq +nexusPassword=cube17tiq \ No newline at end of file diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..fbd7c51 --- /dev/null +++ b/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..a9f778a --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,104 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/scripts/push b/scripts/push new file mode 100755 index 0000000..e8ae0cd --- /dev/null +++ b/scripts/push @@ -0,0 +1,5 @@ +#!/bin/bash + +git push origin master +git push github master + diff --git a/scripts/upload b/scripts/upload new file mode 100755 index 0000000..4bfad26 --- /dev/null +++ b/scripts/upload @@ -0,0 +1,3 @@ +#!/usr/bin/env bash + +gradle upload \ No newline at end of file diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..858fb67 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'cubetiq-common-utils' diff --git a/src/main/java/com/cubetiqs/util/MathUtils.java b/src/main/java/com/cubetiqs/util/MathUtils.java new file mode 100644 index 0000000..78efce0 --- /dev/null +++ b/src/main/java/com/cubetiqs/util/MathUtils.java @@ -0,0 +1,49 @@ +package com.cubetiqs.util; + +import org.jetbrains.annotations.NotNull; + +import java.math.RoundingMode; + +/** + * Math Libra helper + * + * @author sombochea + * @since 1.0 + */ +public final class MathUtils { + /** + * Math Float Round for Double. + * Example: 9.999999 ... n => 10 + * 9.99 => 9.99 + */ + public static Double fround(Number value, int precision, RoundingMode roundingMode) { + if (StringUtils.isNull(value)) { + return 0D; + } + if (StringUtils.isNull(roundingMode)) { + roundingMode = RoundingMode.HALF_DOWN; + } + return ParserUtils.toDouble(NumberUtils.toDecimalPrecision(value, precision, roundingMode)); + } + + public static Double getPrecisionValue(Number value) { + if (StringUtils.isNull(value)) { + return 0D; + } + + return ParserUtils.toDouble(value) - ParserUtils.toInt(value); + } + + @NotNull + public static Double minus(Number value1, Number value2) { + if (StringUtils.isNull(value1)) { + return 0D; + } + + if (StringUtils.isNull(value2)) { + return 0D; + } + + return ParserUtils.toDouble(value1) - ParserUtils.toDouble(value2); + } +} diff --git a/src/main/java/com/cubetiqs/util/NumberUtils.java b/src/main/java/com/cubetiqs/util/NumberUtils.java new file mode 100644 index 0000000..6bd9714 --- /dev/null +++ b/src/main/java/com/cubetiqs/util/NumberUtils.java @@ -0,0 +1,49 @@ +package com.cubetiqs.util; + +import java.math.RoundingMode; +import java.text.DecimalFormat; + +/** + * Number Libra helper + * + * @author sombochea + * @since 1.0 + */ +public final class NumberUtils { + private static final String DECIMAL_PATTERN = "#.##"; + private static final String ROUNDING_DECIMAL_PATTERN = "##0"; + + public static String toStringDecimal(Number value, String pattern) { + if (pattern == null || pattern.isEmpty()) { + pattern = DECIMAL_PATTERN; + } + return new DecimalFormat(pattern).format(value); + } + + public static String toDecimalPrecision(Number value, int precision, RoundingMode roundingMode) { + if (value == null) { + return null; + } + + StringBuilder pattern = new StringBuilder(ROUNDING_DECIMAL_PATTERN); + + if (precision > 0) { + pattern.append("."); + } + + while (precision > 0) { + pattern.append("0"); + precision--; + } + + DecimalFormat decimalFormat = new DecimalFormat(pattern.toString()); + + if (roundingMode == null) { + roundingMode = RoundingMode.HALF_EVEN; + } + + decimalFormat.setRoundingMode(roundingMode); + + return decimalFormat.format(value); + } +} diff --git a/src/main/java/com/cubetiqs/util/ParserUtils.java b/src/main/java/com/cubetiqs/util/ParserUtils.java new file mode 100644 index 0000000..228fad6 --- /dev/null +++ b/src/main/java/com/cubetiqs/util/ParserUtils.java @@ -0,0 +1,81 @@ +package com.cubetiqs.util; + +import org.jetbrains.annotations.NotNull; + +/** + * Parser Libra helper + * + * @author sombochea + * @see Integer + * @see Double + * @see Number + * @see StringUtils + * @since 1.o + */ +public final class ParserUtils { + @NotNull + public static Integer toInt(String value) { + if (value == null || value.isEmpty()) { + return 0; + } + return Integer.parseInt(value); + } + + public static Integer toInt(String value, Integer fallback) { + if (StringUtils.isNullOrEmpty(value)) { + return fallback; + } + return Integer.parseInt(value); + } + + @NotNull + public static Integer toInt(Number value) { + if (StringUtils.isNull(value)) { + return 0; + } + + return Integer.parseInt(value.toString()); + } + + public static Integer toInt(Number value, Integer fallback) { + if (StringUtils.isNull(value)) { + return fallback; + } + + return Integer.parseInt(value.toString()); + } + + @NotNull + public static Double toDouble(String value) { + if (StringUtils.isNull(value)) { + return 0D; + } + + return Double.parseDouble(value); + } + + public static Double toDouble(String value, Double fallback) { + if (StringUtils.isNull(value)) { + return fallback; + } + + return Double.parseDouble(value); + } + + @NotNull + public static Double toDouble(Number value) { + if (StringUtils.isNull(value)) { + return 0D; + } + + return Double.parseDouble(value.toString()); + } + + public static Double toDouble(Number value, Double fallback) { + if (StringUtils.isNull(value)) { + return fallback; + } + + return Double.parseDouble(value.toString()); + } +} diff --git a/src/main/java/com/cubetiqs/util/StringUtils.java b/src/main/java/com/cubetiqs/util/StringUtils.java new file mode 100644 index 0000000..b9541d7 --- /dev/null +++ b/src/main/java/com/cubetiqs/util/StringUtils.java @@ -0,0 +1,384 @@ +package com.cubetiqs.util; + +import com.cubetiqs.logging.Log; +import org.apache.commons.text.StringEscapeUtils; +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.NotNull; + +import java.util.*; +import java.util.function.Function; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import static java.util.regex.Pattern.compile; + +/** + * String Utilities and Libra helper + * + * @author sombochea + * @see Pattern + * @see Matcher + * @see Collectors + * @see Function + * @since 1.0 + */ +public final class StringUtils { + private static final String EMPTY_STRING = ""; + private static final String ALPHA_REGEX = "^[a-zA-Z]+$"; + private static final String NUMERIC_REGEX = "^[0-9]+$"; + private static final String ALPHA_NUMERIC_REGEX = "^[a-zA-Z0-9]+$"; + private static final String ALPHA_NUMERIC_SPACE_REGEX = "^[a-zA-Z0-9 ]+$"; + private static final Logger logger = Log.getLogger(StringUtils.class); + + public StringUtils() { + // nothing to do here + } + + public static boolean isNull(Object value) { + return value == null; + } + + public static boolean isNotNull(Object value) { + return !isNull(value); + } + + public static boolean isEmpty(String value) { + return value.length() == 0; + } + + public static String ifEmptyNull(String value) { + if (!isNull(value) && isEmpty(value)) { + return null; + } + return value; + } + + public static String ifNullEmpty(String value) { + if (isNull(value)) { + return EMPTY_STRING; + } + return value; + } + + public static boolean isNullOrEmpty(String value) { + return isNull(value) || isEmpty(value); + } + + public static String getOrDefault(String text, String fallback) { + if (isNull(text) || isEmpty(text)) { + return fallback; + } + return text; + } + + @NotNull + public static String getOrEmpty(String text) { + return getOrDefault(text, EMPTY_STRING); + } + + public static String fromSpaceToUnderScoreAndUpperCase(String value) { + if (isNull(value)) { + return null; + } + return value.replace(' ', '_').toUpperCase(); + } + + public static boolean isAllCaps(String value) { + if (isNull(value)) { + return false; + } + + return value.matches(".*[a-z].*"); + } + + public static boolean regex(String value, String regex) { + if (isNull(value)) { + return false; + } + + if (isNull(regex)) { + return false; + } + + Pattern pattern = Pattern.compile(regex); + Matcher matcher = pattern.matcher(value); + return matcher.matches(); + } + + public boolean isAlpha(String value) { + return regex(value, ALPHA_REGEX); + } + + public boolean notAlpha(String value) { + return !isAlpha(value); + } + + public boolean isNumeric(String value) { + return regex(value, NUMERIC_REGEX); + } + + public boolean notNumeric(String value) { + return !isNumeric(value); + } + + public boolean isAlphaNumeric(String value) { + return regex(value, ALPHA_NUMERIC_REGEX); + } + + public boolean isAlphaNumeric(String value, boolean space) { + String regex = ALPHA_NUMERIC_REGEX; + if (space) { + regex = ALPHA_NUMERIC_SPACE_REGEX; + } + return regex(value, regex); + } + + public boolean isAlphaNumeric(String value, CharSequence sequence) { + String regex = ALPHA_NUMERIC_REGEX; + if (isNotNull(sequence)) { + regex = "^[a-zA-Z0-9" + sequence + "]+$"; + } + return regex(value, regex); + } + + public boolean isSymbol(String value) { + return notAlpha(value) && notNumeric(value); + } + + public static List splitting(String value, char splitter) { + if (!isEmpty(value)) { + return Arrays.asList(value.trim().split("\\s*" + splitter + "\\s*")); + } + + return new ArrayList<>(); + } + + public static List splitting(String data, String regex) { + if (!isEmpty(data)) { + return Arrays.asList(data.trim().split(regex)); + } + + return new ArrayList<>(); + } + + public static List splitFields(String data, String delimiters) { + if (!isEmpty(data)) { + return Arrays.stream(data.split("[" + delimiters + "]")) + .map(String::trim) + .collect(Collectors.toList()); + } + + return new ArrayList<>(); + } + + public static Map mapFields(String fields) { + List rawFields = splitFields(fields, ";"); + Map finalFields = new Hashtable<>(); + rawFields.forEach( + i -> { + List subFields = splitting(i, ':'); + if (subFields.size() > 0) { + if (splitting(subFields.get(0), ',').size() > 1) { + // more logic + finalFields.put("default", i.trim()); + } else { + subFields.forEach(j -> finalFields.put(subFields.get(0).trim(), j.trim())); + } + } + }); + + return finalFields; + } + + public static Set splittingAsHashSet(String data, char splitter) { + return new HashSet<>(splitting(data, splitter)); + } + + public static String implode(List data, CharSequence separator) { + return String.join(separator, data); + } + + public static String implode(String[] data, CharSequence separator) { + return String.join(separator, data); + } + + public static String[] explode(String data, String splitter) { + return data.split(splitter); + } + + public static String concat(String[] data) { + + StringBuilder ext = new StringBuilder(); + for (String a : data) { + ext.append(a); + } + + return ext.toString(); + } + + /** + * Replacer with Template and Separator. + * + * @param template String + * @param replacement Map + * @param separator String. + * @return String + */ + public static String replacer( + String template, Map replacement, CharSequence separator) { + String patternString = + separator + "(" + StringUtils.join(replacement.keySet(), '|') + ")" + separator; + Pattern pattern = compile(patternString); + Matcher matcher = pattern.matcher(template); + StringBuffer stringBuffer = new StringBuffer(); + while (matcher.find()) { + try { + matcher.appendReplacement(stringBuffer, "\\" + replacement.get(matcher.group(1)) + ""); + } catch (Exception ex) { + logger.error(ex.getMessage()); + } + } + matcher.appendTail(stringBuffer); + + return stringBuffer + ""; + } + + /** + * Replacer with Template. + * + * @param template String + * @param replaceKey String | Key to replace value with + * @param replaceValue String | Value to replace. + * @return String + */ + public static String replacer(String template, String replaceKey, Object replaceValue) { + Map replacement = new Hashtable<>(); + replacement.put(replaceKey, replaceValue); + return replacer(template, replacement); + } + + /** + * Replacer with Template. + * + * @param template String + * @param replacement Map + * @return String + */ + public static String replacer(String template, Map replacement) { + return replacer(template, replacement, "%"); + } + + /** + * Find Specific Values by {want} delimiter. + * + * @param template String + * @param sequence CharSequence + * @return List of String. + */ + public static List findValues(String template, CharSequence sequence) { + return findValues(template, sequence, sequence); + } + + /** + * Find Specific Values by {want} delimiter. + * + * @param template String + * @param sequenceStart CharSequence + * @param sequenceEnd CharSequence + * @return List of String. + */ + public static List findValues(String template, CharSequence sequenceStart, CharSequence sequenceEnd) { + List data = new ArrayList<>(); + Pattern pattern = compile(escape4Regex(sequenceStart) + "(.*?)" + escape4Regex(sequenceEnd)); + Matcher matcher = pattern.matcher(template); + while (matcher.find()) { + data.add(matcher.group(1)); + } + + return data; + } + + public static String escape4Regex(CharSequence sequence) { + return escape4Regex(sequence.toString()); + } + + public static String escape4Regex(String text) { + return text.replaceAll("([\\\\+*?\\[\\](){}|.^$])", "\\\\$1"); + } + + public static String join(String[] array) { + if (isNull(array)) { + return EMPTY_STRING; + } + + return join(Arrays.asList(array)); + } + + + public static void join(String[] array, char separator, StringBuilder sb) { + if (isNull(array)) { + return; + } + + join(Arrays.asList(array), separator, sb); + } + + + public static String join(Collection collection) { + return join(collection, ','); + } + + + public static String join(Collection collection, char separator) { + if (isNull(collection) || collection.isEmpty()) { + return EMPTY_STRING; + } + + StringBuilder result = new StringBuilder(); + join(collection, separator, result); + + return result.toString(); + } + + + public static void join(Iterable iterable, char separator, StringBuilder sb) { + join(iterable, separator, (x) -> x, sb); + } + + public static void join(T[] array, char separator, Function function, StringBuilder sb) { + if (isNull(array)) { + return; + } + + join(Arrays.asList(array), separator, function, sb); + } + + + public static void join(Iterable iterable, char separator, Function function, StringBuilder sb) { + if (isNull(iterable)) { + return; + } + boolean first = true; + for (T value : iterable) { + if (first) { + first = false; + } else { + sb.append(separator); + } + sb.append(function.apply(value)); + } + } + + /** + * Text is equal or not + * Without case-sensitive + * + * @param s1 String + * @param s2 String + * @return boolean + */ + public static boolean isEquals(String s1, String s2) { + return (s1 + "".toUpperCase()).equals(s2 + "".toUpperCase()); + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/cubetiqs/util/StringUtils.kt b/src/main/kotlin/com/cubetiqs/util/StringUtils.kt new file mode 100644 index 0000000..7392acc --- /dev/null +++ b/src/main/kotlin/com/cubetiqs/util/StringUtils.kt @@ -0,0 +1,18 @@ +package com.cubetiqs.util + +private val charPool: List = ('a'..'z') + ('A'..'Z') + ('0'..'9') + +fun randomStringFromLength(length: Int = 2, separator: String = ""): String { + return (1..length) + .map { kotlin.random.Random.nextInt(0, charPool.size) } + .map(charPool::get) + .joinToString(separator) +} + +fun String?.randomString(): String { + return randomStringFromLength(this?.length ?: 2) +} + +fun Int?.randomString(): String { + return randomStringFromLength(this ?: 2) +} diff --git a/src/main/kotlin/com/cubetiqs/util/base64/ImageBase64Utils.kt b/src/main/kotlin/com/cubetiqs/util/base64/ImageBase64Utils.kt new file mode 100644 index 0000000..13c7a12 --- /dev/null +++ b/src/main/kotlin/com/cubetiqs/util/base64/ImageBase64Utils.kt @@ -0,0 +1,61 @@ +package com.cubetiqs.util.base64 + +import com.cubetiqs.exception.RIOException +import java.awt.image.BufferedImage +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.io.IOException +import java.util.Base64 +import javax.imageio.ImageIO +import javax.xml.bind.DatatypeConverter + +/** + * Image Base64 Libra helper + * + * @author sombochea + * @since 1.0 + */ +object ImageBase64Utils { + private fun base64Trimmer(base64String: String): String? { + val data: List = try { + base64String.split(",") + } catch (ex: Exception) { + listOf() + } + return if (data.size > 1) { + data[1] + } else { + base64String + } + } + + @Throws(RIOException::class) + @JvmStatic + fun toImageBytes(base64String: String): ByteArray { + var image: BufferedImage? = null + try { + ByteArrayInputStream( + Base64.getMimeDecoder().decode(base64Trimmer(base64String)) + ).use { inputStream -> image = ImageIO.read(inputStream) } + } catch (ex: IOException) { + ex.printStackTrace() + throw RIOException(ex) + } + try { + ByteArrayOutputStream().use { outputStream -> + ImageIO.write(image, "png", outputStream) + return outputStream.toByteArray() + } + } catch (ex: IOException) { + ex.printStackTrace() + throw RIOException(ex) + } + } + + @JvmStatic + fun toBytes(base64String: String, useTrimmer: Boolean): ByteArray { + return if (useTrimmer) DatatypeConverter.parseBase64Binary(base64Trimmer(base64String)) else DatatypeConverter.parseBase64Binary( + base64String + ) + } +} diff --git a/src/main/kotlin/com/cubetiqs/util/extension/StringExtension.kt b/src/main/kotlin/com/cubetiqs/util/extension/StringExtension.kt new file mode 100644 index 0000000..bea8e04 --- /dev/null +++ b/src/main/kotlin/com/cubetiqs/util/extension/StringExtension.kt @@ -0,0 +1,6 @@ +package com.cubetiqs.util.extension + +import com.cubetiqs.util.StringUtils + +fun String?.getOrDefault(fallback: String? = null): String = StringUtils.getOrDefault(this, fallback) +fun String?.getOrEmpty(): String = StringUtils.getOrEmpty(this) \ No newline at end of file diff --git a/src/main/resources/log4j2.xml b/src/main/resources/log4j2.xml new file mode 100644 index 0000000..d96007b --- /dev/null +++ b/src/main/resources/log4j2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/java/com/cubetiqs/util/test/StringHelperTests.java b/src/test/java/com/cubetiqs/util/test/StringHelperTests.java new file mode 100644 index 0000000..e4187fe --- /dev/null +++ b/src/test/java/com/cubetiqs/util/test/StringHelperTests.java @@ -0,0 +1,13 @@ +package com.cubetiqs.util.test; + +import com.cubetiqs.util.StringUtils; +import org.junit.Assert; +import org.junit.Test; + +public class StringHelperTests { + @Test + public void getOrEmptyString() { + Assert.assertEquals("Hello", StringUtils.getOrEmpty("Hello")); + Assert.assertEquals("", StringUtils.getOrEmpty(null)); + } +} diff --git a/src/test/kotlin/StringUtilsTests.kt b/src/test/kotlin/StringUtilsTests.kt new file mode 100644 index 0000000..6bf4ed8 --- /dev/null +++ b/src/test/kotlin/StringUtilsTests.kt @@ -0,0 +1,22 @@ +package com.cubetiqs.util.test + +import com.cubetiqs.logging.Log +import com.cubetiqs.util.randomString +import com.cubetiqs.util.randomStringFromLength +import org.junit.Assert +import org.junit.Test + +class StringUtilsTests { + val logger = Log.getLogger(javaClass) + + @Test + fun testRandomString() { + val rand = "ANC".randomString() + logger.fatal("String random is {}", rand) + Assert.assertNotNull("string is null", rand) + + val rand2 = randomStringFromLength(10) + logger.error("String random is {}", rand2) + Assert.assertTrue("is not true", rand2.length == 10) + } +} \ No newline at end of file