Add project and libra and more

This commit is contained in:
Sambo Chea 2020-07-03 10:53:34 +07:00
parent 5a1be6524c
commit f06acfd177
21 changed files with 1092 additions and 0 deletions

33
.gitignore vendored Normal file
View File

@ -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/

View File

@ -0,0 +1,4 @@
### CUBETIQ Commom Utils Module
- [x] Utils for Java and Kotlin
- [x] Custom Extension for Kotlin
- [ ] More...

48
build.gradle Normal file
View File

@ -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)
}
}
}
}

3
gradle.properties.sample Normal file
View File

@ -0,0 +1,3 @@
nexusUrl=https://oss-internal.cubetiqs.com
nexusUsername=user
nexusPassword=pass

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -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

185
gradlew vendored Executable file
View File

@ -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" "$@"

104
gradlew.bat vendored Normal file
View File

@ -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

5
scripts/push Executable file
View File

@ -0,0 +1,5 @@
#!/bin/bash
git push origin master
git push github master

3
scripts/upload Executable file
View File

@ -0,0 +1,3 @@
#!/usr/bin/env bash
gradle upload

1
settings.gradle Normal file
View File

@ -0,0 +1 @@
rootProject.name = 'cubetiq-common-utils'

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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());
}
}

View File

@ -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<String> splitting(String value, char splitter) {
if (!isEmpty(value)) {
return Arrays.asList(value.trim().split("\\s*" + splitter + "\\s*"));
}
return new ArrayList<>();
}
public static List<String> splitting(String data, String regex) {
if (!isEmpty(data)) {
return Arrays.asList(data.trim().split(regex));
}
return new ArrayList<>();
}
public static List<String> 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<String, String> mapFields(String fields) {
List<String> rawFields = splitFields(fields, ";");
Map<String, String> finalFields = new Hashtable<>();
rawFields.forEach(
i -> {
List<String> 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<String> splittingAsHashSet(String data, char splitter) {
return new HashSet<>(splitting(data, splitter));
}
public static String implode(List<String> 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<String, Object>
* @param separator String.
* @return String
*/
public static String replacer(
String template, Map<String, Object> 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<String, Object> replacement = new Hashtable<>();
replacement.put(replaceKey, replaceValue);
return replacer(template, replacement);
}
/**
* Replacer with Template.
*
* @param template String
* @param replacement Map<String, Object>
* @return String
*/
public static String replacer(String template, Map<String, Object> replacement) {
return replacer(template, replacement, "%");
}
/**
* Find Specific Values by {want} delimiter.
*
* @param template String
* @param sequence CharSequence
* @return List of String.
*/
public static List<String> 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<String> findValues(String template, CharSequence sequenceStart, CharSequence sequenceEnd) {
List<String> 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<String> collection) {
return join(collection, ',');
}
public static String join(Collection<String> 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<String> iterable, char separator, StringBuilder sb) {
join(iterable, separator, (x) -> x, sb);
}
public static <T> void join(T[] array, char separator, Function<T, String> function, StringBuilder sb) {
if (isNull(array)) {
return;
}
join(Arrays.asList(array), separator, function, sb);
}
public static <T> void join(Iterable<T> iterable, char separator, Function<T, String> 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());
}
}

View File

@ -0,0 +1,18 @@
package com.cubetiqs.util
private val charPool: List<Char> = ('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)
}

View File

@ -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<String> = 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
)
}
}

View File

@ -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)

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>

View File

@ -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));
}
}

View File

@ -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)
}
}