├── .gitignore ├── LICENSE.md ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── libs ├── core-3.3.0.jar └── javase-3.3.0.jar ├── misc ├── build.gradle └── src │ ├── main │ └── java │ │ └── com │ │ └── github │ │ └── mattnicee7 │ │ └── mattlib │ │ ├── adapter │ │ ├── Adapter.java │ │ └── Restorable.java │ │ ├── console │ │ └── ConsoleUtil.java │ │ ├── cooldown │ │ └── CooldownMap.java │ │ ├── date │ │ └── DateUtil.java │ │ ├── document │ │ ├── DocumentChecker.java │ │ ├── impl │ │ │ ├── CNPJChecker.java │ │ │ └── CPFChecker.java │ │ └── util │ │ │ └── DocumentUtil.java │ │ ├── email │ │ ├── EmailContent.java │ │ ├── EmailCredentials.java │ │ ├── EmailHostType.java │ │ └── EmailService.java │ │ ├── file │ │ └── FileUtils.java │ │ ├── logger │ │ ├── LogLevel.java │ │ └── Logger.java │ │ ├── password │ │ ├── PasswordVerifier.java │ │ └── PasswordVerifierBuilder.java │ │ ├── qrcode │ │ ├── QRCodeGenerator.java │ │ └── QRCodeReader.java │ │ ├── random │ │ └── RandomUtils.java │ │ ├── singlemap │ │ ├── Pair.java │ │ ├── Quadruple.java │ │ ├── Quintuple.java │ │ └── Triple.java │ │ ├── stopwatch │ │ └── StopWatch.java │ │ ├── string │ │ ├── Replacer.java │ │ └── StringUtil.java │ │ └── time │ │ ├── TimeFormat.java │ │ ├── TimeFormatter.java │ │ └── TimeFormatterBuilder.java │ └── test │ └── java │ └── com │ └── github │ └── mattnicee7 │ └── mattlib │ └── cooldown │ └── CooldownMapTest.java ├── settings.gradle ├── spigot ├── build.gradle └── src │ └── main │ └── java │ └── com │ └── github │ └── mattnicee7 │ └── util │ ├── chat │ └── ChatUtils.java │ ├── player │ └── PlayerUtils.java │ └── serializer │ └── location │ └── LocationSerializer.java └── sql ├── build.gradle └── src └── main └── java └── com └── github └── mattnicee7 └── mattlib ├── credentials ├── DatabaseCredentials.java └── impl │ ├── MariaDBCredentials.java │ ├── MySQLCredentials.java │ ├── PostgreSQLCredentials.java │ └── SQLiteCredentials.java ├── datasource ├── DataSource.java ├── factory │ └── DataSourceFactory.java └── impl │ ├── MariaDB.java │ ├── MySQL.java │ ├── PostgreSQL.java │ └── SQLite.java ├── exception ├── DatabaseConnectionException.java └── DatabaseDriverNotFoundException.java └── util └── PreparedStatementBuilder.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.toptal.com/developers/gitignore/api/java 2 | # Edit at https://www.toptal.com/developers/gitignore?templates=java 3 | 4 | ### Java ### 5 | # Compiled class file 6 | *.class 7 | 8 | # Log file 9 | *.log 10 | 11 | # BlueJ files 12 | *.ctxt 13 | 14 | # Mobile Tools for Java (J2ME) 15 | .mtj.tmp/ 16 | 17 | # Package Files # 18 | *.jar 19 | *.war 20 | *.nar 21 | *.ear 22 | *.zip 23 | *.tar.gz 24 | *.rar 25 | 26 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 27 | hs_err_pid* 28 | replay_pid* 29 | 30 | # End of https://www.toptal.com/developers/gitignore/api/java -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Copyright © 2022 mattnicee7 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MattLib 2 | 3 | [![GitHub stars](https://img.shields.io/github/stars/mattnicee7/mattlib)](https://github.com/mattnicee7/MattLib/stargazers) 4 | [![CodeFactor](https://www.codefactor.io/repository/github/mattnicee7/mattlib/badge/master)](https://www.codefactor.io/repository/github/mattnicee7/mattlib/overview/master) 5 | [![wakatime](https://wakatime.com/badge/user/3408feff-bd97-4f32-be4d-77a253fdf982/project/e5620731-e5df-419d-9658-2e63a79dfa40.svg)](https://wakatime.com/badge/user/3408feff-bd97-4f32-be4d-77a253fdf982/project/e5620731-e5df-419d-9658-2e63a79dfa40) 6 | 7 | Uma biblioteca completa para seus projetos, com funções que abrangem desde de banco de dados como MySQL, SQLite, PostgreSQL, MariaDB a verificação de documentos como CPF/CNPJ. Além de um código limpo e robusto facilitando o uso. Issues e Pull-Requests são bem vindos nesse repositório. 8 | 9 | # Recursos 10 | 11 | Lista dos principais recursos disponíveis na biblioteca: 12 | 13 | ✱ Projeto multi-modulo dividido entre misc, sql e spigot. Você pode escolher o módulo que você quer usar. 14 | 15 | ✱ Verificador de documentos (CPF e CNPJ). 16 | 17 | ✱ Serviço de envio de e-mails automatico. 18 | 19 | ✱ Verificador de segurança de senhas. 20 | 21 | ✱ Sistema para geração e leitura de QR code. 22 | 23 | ✱ Conector de SQL com opções de 4 database: MySQL, SQLite, PostgreSQL, MariaDB. 24 | 25 | ✱ Formatador de tempo. 26 | 27 | ✱ E muito mais... 28 | 29 | # Maven 30 | 31 | ```xml 32 | 33 | 34 | jitpack.io 35 | https://jitpack.io 36 | 37 | 38 | 39 | 40 | 41 | com.github.mattnicee7.mattlib 42 | MODULE 43 | VERSION 44 | 45 | 46 | ``` 47 | 48 | # Gradle 49 | 50 | ```gradle 51 | repositories { 52 | maven { url 'https://jitpack.io' } 53 | } 54 | 55 | dependencies { 56 | implementation 'com.github.mattnicee7.mattlib:MODULE:VERSION' 57 | } 58 | ``` 59 | 60 | # TO-DO List 61 | 62 | * Relocate in some dependencies 63 | * Add more features (misc, sql) 64 | * Add features in spigot (utils, builders) 65 | * Add ConsoleReader in console package 66 | 67 | # Exemplos de usos 68 | 69 | # Bibliotecas utilizadas 70 | 71 | ✱ [Lombok](https://projectlombok.org/) 72 | 73 | ✱ [Javax Mail](https://mvnrepository.com/artifact/javax.mail) 74 | 75 | ✱ [Jetbrains Annotation](https://www.jetbrains.com/help/idea/annotating-source-code.html) 76 | 77 | ✱ MySQL, PostgreSQL, MariaDB, SQLite Drivers. 78 | 79 | # Contribuidores 80 | 81 | ✱ [mattnicee7](https://github.com/mattnicee7/) 82 | 83 | ✱ [zGumeloBr](https://github.com/zGumeloBr) 84 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'com.github.johnrengelman.shadow' version '7.1.0' 4 | id 'maven-publish' 5 | } 6 | 7 | allprojects { 8 | group = 'com.github.mattnicee7.mattlib' 9 | version = '1.2.2' 10 | 11 | apply plugin: 'java' 12 | apply plugin: 'com.github.johnrengelman.shadow' 13 | 14 | repositories { 15 | mavenCentral() 16 | } 17 | 18 | dependencies { 19 | // Lombok 20 | compileOnly('org.projectlombok:lombok:1.18.24') 21 | annotationProcessor('org.projectlombok:lombok:1.18.24') 22 | 23 | // JetBrains Annotations 24 | implementation('org.jetbrains:annotations:23.0.0') 25 | 26 | // Junit 27 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1' 28 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1' 29 | } 30 | 31 | test { 32 | useJUnitPlatform() 33 | } 34 | } 35 | 36 | subprojects { 37 | apply plugin: 'maven-publish' 38 | 39 | publishing { 40 | publications { 41 | maven(MavenPublication) { 42 | groupId project.group 43 | artifactId project.name 44 | version project.version 45 | from components.java 46 | } 47 | } 48 | } 49 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mattnicee7/MattLib/b86f7345e31be276c63f99d2b82920eef5f5d631/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MSYS* | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /libs/core-3.3.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mattnicee7/MattLib/b86f7345e31be276c63f99d2b82920eef5f5d631/libs/core-3.3.0.jar -------------------------------------------------------------------------------- /libs/javase-3.3.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mattnicee7/MattLib/b86f7345e31be276c63f99d2b82920eef5f5d631/libs/javase-3.3.0.jar -------------------------------------------------------------------------------- /misc/build.gradle: -------------------------------------------------------------------------------- 1 | repositories { 2 | mavenCentral() 3 | 4 | flatDir { 5 | dirs("libs") 6 | } 7 | } 8 | 9 | dependencies { 10 | // Zxing core, javase (QRCode) 11 | implementation("com.google.zxing:core:3.5.0") 12 | implementation("com.google.zxing:javase:3.5.0") 13 | 14 | // Javax Mail 15 | implementation("javax.mail:mail:1.4.7") 16 | } -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/adapter/Adapter.java: -------------------------------------------------------------------------------- 1 | package com.github.mattnicee7.mattlib.adapter; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | 5 | public interface Adapter { 6 | 7 | V adapt(@NotNull K k); 8 | 9 | } 10 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/adapter/Restorable.java: -------------------------------------------------------------------------------- 1 | package com.github.mattnicee7.mattlib.adapter; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | 5 | public interface Restorable { 6 | 7 | V restore(@NotNull K k); 8 | 9 | } 10 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/console/ConsoleUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.console; 26 | 27 | public class ConsoleUtil { 28 | 29 | public static final String ANSI_RESET = "\u001B[0m"; 30 | public static final String ANSI_BLACK_BACKGROUND = "\u001B[40m"; 31 | public static final String ANSI_RED_BACKGROUND = "\u001B[41m"; 32 | public static final String ANSI_GREEN_BACKGROUND = "\u001B[42m"; 33 | public static final String ANSI_YELLOW_BACKGROUND = "\u001B[43m"; 34 | public static final String ANSI_BLUE_BACKGROUND = "\u001B[44m"; 35 | public static final String ANSI_PURPLE_BACKGROUND = "\u001B[45m"; 36 | public static final String ANSI_CYAN_BACKGROUND = "\u001B[46m"; 37 | public static final String ANSI_WHITE_BACKGROUND = "\u001B[47m"; 38 | 39 | public static void clear() { 40 | System.out.print("\033[H\033[2J"); 41 | System.out.flush(); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/cooldown/CooldownMap.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.cooldown; 26 | 27 | import com.github.mattnicee7.mattlib.time.TimeFormatter; 28 | import com.github.mattnicee7.mattlib.time.TimeFormatterBuilder; 29 | import lombok.val; 30 | import org.jetbrains.annotations.NotNull; 31 | 32 | import java.util.HashMap; 33 | import java.util.Map; 34 | 35 | /** 36 | * Make a cooldown collection with this class. 37 | * Put your objects on cooldown whenever you want. 38 | * 39 | *

Example Usage: 40 | * 41 | *
 42 |  *     {@code
 43 |  *     public static void main(String[] args) {
 44 |  *         val cooldownMap = CooldownMap.of(User.class);
 45 |  *
 46 |  *         // Do what you want with the cooldown map (...)
 47 |  *     }}
48 | * 49 | */ 50 | public class CooldownMap { 51 | 52 | /** 53 | * Collection responsible for keeping objects on cooldown 54 | */ 55 | private final Map inCooldown = new HashMap<>(); 56 | 57 | /** 58 | * Get a CooldownMap from a class. 59 | * 60 | *

Example Usage: 61 | * 62 | *
 63 |      *     {@code
 64 |      *     public static void main(String[] args) {
 65 |      *         val cooldownMap = CooldownMap.of(String.class);
 66 |      *
 67 |      *         cooldownMap.add("Matt", 10000L);
 68 |      *     }}
69 | * 70 | * @param clazz 71 | * The generic type class you want in the cooldown map. 72 | * 73 | * @return A cooldown map with the given generic class type. 74 | */ 75 | public static CooldownMap of(@NotNull Class clazz) { 76 | return new CooldownMap(); 77 | } 78 | 79 | /** 80 | * Add the object in the cooldown. 81 | * 82 | * @param key 83 | * Object to put in cooldown. 84 | * 85 | * @param time 86 | * Cooldown time in millis. (Example: 10000L = 10 Seconds). 87 | * 88 | */ 89 | public void put(@NotNull T key, @NotNull Long time) { 90 | inCooldown.put(key, System.currentTimeMillis() + time); 91 | } 92 | 93 | /** 94 | * Remove the object from cooldown. 95 | * 96 | * @param key 97 | * Object to remove from cooldown. 98 | * 99 | */ 100 | public void remove(@NotNull T key) { 101 | inCooldown.remove(key); 102 | } 103 | 104 | /** 105 | * Check if the object is in cooldown. 106 | * 107 | * @param key 108 | * Object to check if present on cooldown. 109 | * 110 | * @return If the object is present in cooldown, true, else, false. 111 | * 112 | */ 113 | public boolean isInCooldown(@NotNull T key) { 114 | if (!inCooldown.containsKey(key)) 115 | return false; 116 | 117 | if (inCooldown.get(key) < System.currentTimeMillis()) 118 | remove(key); 119 | 120 | return inCooldown.containsKey(key); 121 | } 122 | 123 | /** 124 | * Get remaining cooldown time of the object. 125 | * 126 | * @param key 127 | * Object to get remaining time in cooldown. 128 | * 129 | * @return Remaining time in millis. 130 | * */ 131 | public long getRemainingTime(@NotNull T key) { 132 | if (!inCooldown.containsKey(key)) 133 | return 0L; 134 | 135 | return inCooldown.get(key) - System.currentTimeMillis(); 136 | } 137 | 138 | /** 139 | * Get formatted remaining cooldown time of the object with default time formatter. 140 | * 141 | * @param key 142 | * Object to get formatted remaining time in cooldown. 143 | * 144 | * @return A formatted string with remaining time cooldown and the default time formatter. 145 | */ 146 | public String getRemainingTimeFormatted(@NotNull T key) { 147 | return getRemainingTimeFormatted(key, TimeFormatterBuilder.getDefaultTimeFormatter()); 148 | } 149 | 150 | public String getRemainingTimeFormatted(@NotNull T key, @NotNull TimeFormatter timeFormatter) { 151 | if (!inCooldown.containsKey(key)) 152 | return ""; 153 | 154 | val millis = getRemainingTime(key); 155 | 156 | return timeFormatter.format(millis); 157 | } 158 | 159 | } 160 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/date/DateUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.date; 26 | 27 | import org.jetbrains.annotations.NotNull; 28 | 29 | import java.time.LocalDateTime; 30 | import java.time.format.DateTimeFormatter; 31 | 32 | /** 33 | * Utility class for dates. 34 | */ 35 | public class DateUtil { 36 | 37 | /** 38 | * Default time formatter for the time stamps. 39 | * Example return: 18/01/2004 23:00:00 40 | */ 41 | private static final DateTimeFormatter DEFAULT_TIME_FORMATTER = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"); 42 | 43 | /** 44 | * Not instantiable 45 | */ 46 | private DateUtil() { 47 | throw new UnsupportedOperationException("This class is not instantiable"); 48 | } 49 | 50 | /** 51 | * Get the now timestamp with the default time formatter. 52 | * 53 | * @return The now timestamp formatted with the default time formatter. 54 | */ 55 | public static String getNowTimeStamp() { 56 | return DEFAULT_TIME_FORMATTER.format(LocalDateTime.now()); 57 | } 58 | 59 | /** 60 | * Get the now timestamp with the your time formatter. 61 | * 62 | * @param dateTimeFormatter 63 | * The yours time formatter 64 | * 65 | * @return The now timestamp formatted with your time formatter. 66 | */ 67 | public static String getNowTimeStamp(@NotNull DateTimeFormatter dateTimeFormatter) { 68 | return dateTimeFormatter.format(LocalDateTime.now()); 69 | } 70 | 71 | /** 72 | * Get timestamp from specified date with the default time formatter. 73 | * 74 | * @param localDateTime 75 | * The date you want the timestamp. 76 | * 77 | * @return The timestamp formatted with default time formatter. 78 | */ 79 | public static String getTimeStamp(@NotNull LocalDateTime localDateTime) { 80 | return DEFAULT_TIME_FORMATTER.format(localDateTime); 81 | } 82 | 83 | /** 84 | * Get timestamp from specified date with the your time formatter. 85 | * 86 | * @param localDateTime 87 | * The date you want the timestamp. 88 | * 89 | * @param dateTimeFormatter 90 | * The yours time formatter 91 | * 92 | * @return The timestamp formatted with yours time formatter. 93 | */ 94 | public static String getTimeStamp(@NotNull LocalDateTime localDateTime, @NotNull DateTimeFormatter dateTimeFormatter) { 95 | return dateTimeFormatter.format(localDateTime); 96 | } 97 | 98 | } 99 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/document/DocumentChecker.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.document; 26 | 27 | import org.jetbrains.annotations.NotNull; 28 | 29 | /** 30 | * The DocumentChecker is used to check if a Document is valid. 31 | * */ 32 | public interface DocumentChecker { 33 | 34 | boolean check(@NotNull T t); 35 | 36 | } 37 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/document/impl/CNPJChecker.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.document.impl; 26 | 27 | import com.github.mattnicee7.mattlib.document.DocumentChecker; 28 | import org.jetbrains.annotations.NotNull; 29 | 30 | import java.util.ArrayList; 31 | import java.util.List; 32 | import java.util.regex.Pattern; 33 | 34 | /** 35 | * This class is responsible to check if a CNPJ is valid. 36 | * Attention: it does not verify if the CNPJ exists, only if it is valid, through verifications in the verification codes. 37 | * 38 | *

Available formats

39 | *
    40 | *
  • xxxxxxxxxxxxxx
  • 41 | *
  • xx.xxx.xxx/xxxx-xx
  • 42 | *
43 | * 44 | * See more about this calculation here. 45 | **/ 46 | public class CNPJChecker implements DocumentChecker { 47 | 48 | /** Pattern: 12345678901234 */ 49 | private static final Pattern ONLY_NUMBERS_PATTERN = Pattern.compile("(\\d{14})"); 50 | /** Pattern: 12.345.678/9012-34 */ 51 | private static final Pattern SEPARATE_NUMBERS_PATTERN = Pattern.compile("(\\d{2}\\.\\d{3}\\.\\d{3}/\\d{4}-\\d{2})"); 52 | 53 | @Override 54 | public boolean check(@NotNull String string) { 55 | if (!SEPARATE_NUMBERS_PATTERN.matcher(string).matches() && !ONLY_NUMBERS_PATTERN.matcher(string).matches()) 56 | return false; 57 | 58 | final List cnpjCode = new ArrayList<>(); 59 | final List verificationCodes = new ArrayList<>(); 60 | final String[] cnpjFullSplit = string.replace(".", "") 61 | .replace("/", "") 62 | .replace("-", "") 63 | .split(""); 64 | 65 | for (int i = 0; i < 12; i++) 66 | cnpjCode.add(Integer.parseInt(cnpjFullSplit[i])); 67 | 68 | for (int i = 12; i < 14; i++) 69 | verificationCodes.add(Integer.parseInt(cnpjFullSplit[i])); 70 | 71 | return verificationCodesMatches(cnpjCode, verificationCodes); 72 | } 73 | 74 | /** 75 | * Get verification code of a cnpj by multiplier. 76 | * 77 | * @param multiplier 78 | * The multiplier that you want to verify. 79 | * 80 | * @param cnpjCode 81 | * The cnpj codes. 82 | * 83 | * @return The verification code. 84 | */ 85 | private int getVerificationCode(int multiplier, List cnpjCode) { 86 | double result = 0.0; 87 | int index = 0; 88 | 89 | for (int i = multiplier; i >= 2; i--) { 90 | result += cnpjCode.get(index) * i; 91 | index++; 92 | } 93 | 94 | for (int i = 9; i >= 2; i--) { 95 | result += cnpjCode.get(index) * i; 96 | index++; 97 | } 98 | 99 | int verificationCode = (result % 11 < 2) ? 0 : 11 - (int) Math.round(result % 11); 100 | cnpjCode.add(verificationCode); 101 | 102 | return verificationCode; 103 | } 104 | 105 | /** 106 | * Verify if cnpj codes matches with verification codes informed. 107 | * 108 | * @param cnpjCode 109 | * The cnpj codes. 110 | * 111 | * @param verificationCodes 112 | * The verification codes informed. 113 | * 114 | * @return If the verification codes matches. 115 | */ 116 | private boolean verificationCodesMatches(List cnpjCode, List verificationCodes) { 117 | return getVerificationCode(5, cnpjCode) == verificationCodes.get(0) && 118 | getVerificationCode(6, cnpjCode) == verificationCodes.get(1); 119 | } 120 | 121 | } 122 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/document/impl/CPFChecker.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.document.impl; 26 | 27 | import com.github.mattnicee7.mattlib.document.DocumentChecker; 28 | import org.jetbrains.annotations.NotNull; 29 | 30 | import java.util.ArrayList; 31 | import java.util.List; 32 | import java.util.regex.Pattern; 33 | 34 | /** 35 | * This class is responsible to check if a CPF is valid. 36 | * Attention: it does not verify if the CPF exists, only if it is valid, through verifications in the verification codes. 37 | * 38 | *

Available formats

39 | *
    40 | *
  • xxxxxxxxxxx
  • 41 | *
  • xxx.xxx.xxx-xx
  • 42 | *
43 | * 44 | * See more about this calculation here. 45 | */ 46 | public class CPFChecker implements DocumentChecker { 47 | 48 | /* Pattern: 12345678901 */ 49 | private static final Pattern ONLY_NUMBERS_PATTERN = Pattern.compile("(\\d{11})"); 50 | /* Pattern: 123.456.789-01 */ 51 | private static final Pattern SEPARATE_NUMBERS_PATTERN = Pattern.compile("(\\d{3}\\.\\d{3}\\.\\d{3}-\\d{2})"); 52 | 53 | @Override 54 | public boolean check(@NotNull String string) { 55 | if (!ONLY_NUMBERS_PATTERN.matcher(string).matches() && !SEPARATE_NUMBERS_PATTERN.matcher(string).matches()) 56 | return false; 57 | 58 | final List verificationCodes = new ArrayList<>(); 59 | final List cpfCode = new ArrayList<>(); 60 | final String[] cpfFullSplit = string.replace("-", "") 61 | .replace(".", "") 62 | .split(""); 63 | 64 | for (int i = 0; i < 9; i++) 65 | cpfCode.add(Integer.parseInt(cpfFullSplit[i])); 66 | 67 | for (int i = 9; i < 11; i++) 68 | verificationCodes.add(Integer.parseInt(cpfFullSplit[i])); 69 | 70 | return verificationCodesMatches(cpfCode, verificationCodes); 71 | } 72 | 73 | private int getVerificationCode(int multiplier, List cpfCode) { 74 | double result = 0.0; 75 | for (Integer code : cpfCode) { 76 | result += (code * multiplier--); 77 | } 78 | 79 | int verificationCode = (result % 11 < 2) ? 0 : (int) Math.round(11 - (result % 11)); 80 | cpfCode.add(verificationCode); 81 | 82 | return verificationCode; 83 | } 84 | 85 | private boolean verificationCodesMatches(List cpfCode, List verificationCodes) { 86 | return getVerificationCode(10, cpfCode) == verificationCodes.get(0) && 87 | getVerificationCode(11, cpfCode) == verificationCodes.get(1); 88 | } 89 | 90 | } 91 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/document/util/DocumentUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.document.util; 26 | 27 | import com.github.mattnicee7.mattlib.document.impl.CPFChecker; 28 | import com.github.mattnicee7.mattlib.document.DocumentChecker; 29 | import com.github.mattnicee7.mattlib.document.impl.CNPJChecker; 30 | 31 | /** 32 | * Utility class to documents. 33 | * */ 34 | public class DocumentUtil { 35 | 36 | /** The CPF Checker instance. */ 37 | private static final DocumentChecker CPF_CHECKER = new CPFChecker(); 38 | /** The CNPJ Checker instance. */ 39 | private static final DocumentChecker CNPJ_CHECKER = new CNPJChecker(); 40 | 41 | /** 42 | * Not instantiable 43 | */ 44 | private DocumentUtil() { 45 | throw new UnsupportedOperationException("This class is not instantiable"); 46 | } 47 | 48 | /** 49 | * Return if the cpf informed is valid. 50 | * 51 | * @param cpf 52 | * The cpf you want to know if it's valid 53 | * 54 | * @return If cpf informed is valid 55 | */ 56 | public static boolean isCPFValid(String cpf) { 57 | return CPF_CHECKER.check(cpf); 58 | } 59 | 60 | /** 61 | * Return if the cnpj informed is valid. 62 | * 63 | * @param cnpj 64 | * The cnpj you want to know if it's valid 65 | * 66 | * @return If the cnpj informed is valid 67 | */ 68 | public static boolean isCNPJValid(String cnpj) { 69 | return CNPJ_CHECKER.check(cnpj); 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/email/EmailContent.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.email; 26 | 27 | import lombok.Getter; 28 | import lombok.val; 29 | import org.jetbrains.annotations.NotNull; 30 | import org.jetbrains.annotations.Nullable; 31 | 32 | import javax.mail.Session; 33 | import javax.mail.internet.MimeMessage; 34 | 35 | /** 36 | * Class responsible to manage the email content. 37 | * */ 38 | @Getter 39 | public class EmailContent { 40 | 41 | private final String subject; 42 | private String message; 43 | 44 | public EmailContent(@NotNull String subject, @NotNull String message) { 45 | this.subject = subject; 46 | this.message = message; 47 | } 48 | 49 | public static EmailContent of(@NotNull String subject, @NotNull String message) { 50 | return new EmailContent(subject, message); 51 | } 52 | 53 | /** 54 | * Concat message into the current message. 55 | * 56 | * @param message 57 | * the message to concat. 58 | * 59 | * @return this. 60 | * */ 61 | public EmailContent concat(@NotNull String message) { 62 | this.message += message; 63 | return this; 64 | } 65 | 66 | /** 67 | * Build message to a MimeMessage. 68 | * 69 | * @param session 70 | * the session to use. 71 | * 72 | * @return the MimeMessage. 73 | * */ 74 | @Nullable 75 | protected MimeMessage build(@NotNull Session session) { 76 | try { 77 | val mimeMessage = new MimeMessage(session); 78 | mimeMessage.setSubject(subject); 79 | mimeMessage.setText(message); 80 | 81 | return mimeMessage; 82 | } catch (Exception exception) { 83 | exception.printStackTrace(); 84 | } 85 | 86 | return null; 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/email/EmailCredentials.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.email; 26 | 27 | import lombok.AccessLevel; 28 | import lombok.Getter; 29 | import lombok.val; 30 | import org.jetbrains.annotations.NotNull; 31 | 32 | import javax.mail.Authenticator; 33 | import javax.mail.PasswordAuthentication; 34 | import javax.mail.Session; 35 | import java.util.Properties; 36 | 37 | /** 38 | * Class responsible to storage and provide access to email credentials. 39 | * */ 40 | @Getter(AccessLevel.PACKAGE) 41 | public class EmailCredentials { 42 | 43 | private final String email; 44 | private final String password; 45 | private final EmailHostType emailHostType; 46 | 47 | private final Session session; 48 | 49 | public EmailCredentials(@NotNull String email, @NotNull String password, @NotNull EmailHostType emailHostType) { 50 | this.email = email; 51 | this.password = password; 52 | this.emailHostType = emailHostType; 53 | 54 | val properties = new Properties(); 55 | properties.put("mail.smtp.user", email); 56 | properties.put("mail.smtp.host", emailHostType.getSmtp()); 57 | properties.put("mail.smtp.port", emailHostType.getPort()); 58 | properties.put("mail.smtp.starttls.enable", "true"); 59 | properties.put("mail.smtp.auth", "true"); 60 | properties.put("mail.smtp.socketFactory.port", emailHostType.getPort()); 61 | properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); 62 | properties.put("mail.smtp.socketFactory.fallback", "false"); 63 | 64 | final Authenticator authenticator = new Authenticator() { 65 | @Override 66 | protected PasswordAuthentication getPasswordAuthentication() { 67 | return new PasswordAuthentication(email, password); 68 | } 69 | }; 70 | 71 | this.session = Session.getInstance(properties, authenticator); 72 | } 73 | 74 | public static EmailCredentials of(@NotNull String email, @NotNull String password, @NotNull EmailHostType emailHostType) { 75 | return new EmailCredentials(email, password, emailHostType); 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/email/EmailHostType.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.email; 26 | 27 | import lombok.AccessLevel; 28 | import lombok.Getter; 29 | import org.jetbrains.annotations.NotNull; 30 | import org.jetbrains.annotations.Nullable; 31 | 32 | import java.util.Arrays; 33 | 34 | /** 35 | * Enum responsible to storage the all options of email-hosts to use. 36 | * */ 37 | @Getter(AccessLevel.PACKAGE) 38 | public enum EmailHostType { 39 | 40 | GMAIL("smtp.gmail.com", "465"); 41 | 42 | private final String smtp; 43 | private final String port; 44 | 45 | EmailHostType(String smtp, String port) { 46 | this.smtp = smtp; 47 | this.port = port; 48 | } 49 | 50 | /** 51 | * It takes a string and returns an enum value if the string matches the enum value's name 52 | * 53 | * @param emailHostTypeString 54 | * The string representation of the email host type. 55 | * 56 | * @return The host type if it matches, null otherwise. 57 | */ 58 | @Nullable 59 | public EmailHostType of(@NotNull String emailHostTypeString) { 60 | return Arrays.stream(values()) 61 | .filter(emailHostType -> emailHostType.toString().equalsIgnoreCase(emailHostTypeString)) 62 | .findFirst() 63 | .orElse(null); 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/email/EmailService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.email; 26 | 27 | import lombok.val; 28 | import org.jetbrains.annotations.NotNull; 29 | 30 | import javax.mail.Message; 31 | import javax.mail.Transport; 32 | import javax.mail.internet.InternetAddress; 33 | import javax.mail.internet.MimeMessage; 34 | import java.util.Arrays; 35 | import java.util.List; 36 | 37 | /** 38 | * Class responsible to storage email credentials and send emails. 39 | * */ 40 | public class EmailService { 41 | 42 | private final EmailCredentials emailCredentials; 43 | 44 | public EmailService(@NotNull EmailCredentials emailCredentials) { 45 | this.emailCredentials = emailCredentials; 46 | } 47 | 48 | public static EmailService of(@NotNull EmailCredentials emailCredentials) { 49 | return new EmailService(emailCredentials); 50 | } 51 | 52 | /** 53 | * Send email to a receiver. 54 | * 55 | * @param emailContent 56 | * The content of the email. 57 | * 58 | * @param receiver 59 | * The receiver of the email. 60 | * 61 | * */ 62 | public void sendEmail(@NotNull EmailContent emailContent, @NotNull String receiver) { 63 | try { 64 | val mimeMessage = emailContent.build(emailCredentials.getSession()); 65 | mimeMessage.setFrom(new InternetAddress(emailCredentials.getEmail())); 66 | mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver)); 67 | Transport.send(mimeMessage); 68 | } catch (Exception exception) { 69 | exception.printStackTrace(); 70 | } 71 | } 72 | 73 | /** 74 | * Send email to a multiples receivers. 75 | * 76 | * 77 | * @param emailContent 78 | * The content of the email. 79 | * 80 | * @param receivers 81 | * The receivers of the email. 82 | * */ 83 | public void sendEmail(@NotNull EmailContent emailContent, @NotNull List receivers) { 84 | receivers.forEach(receiver -> this.sendEmail(emailContent, receiver)); 85 | } 86 | 87 | /** 88 | * Send email to a multiples receivers. 89 | * 90 | * 91 | * @param emailContent 92 | * The content of the email. 93 | * 94 | * @param receivers 95 | * The receivers of the email. 96 | * */ 97 | public void sendEmail(@NotNull EmailContent emailContent, String... receivers) { 98 | this.sendEmail(emailContent, Arrays.asList(receivers)); 99 | } 100 | 101 | } 102 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/file/FileUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.file; 26 | 27 | import org.jetbrains.annotations.NotNull; 28 | 29 | import java.io.File; 30 | import java.io.FileFilter; 31 | import java.util.ArrayList; 32 | import java.util.List; 33 | 34 | /** 35 | * A utility class for file operations. 36 | */ 37 | public class FileUtils { 38 | 39 | private static final FileFilter FILE_FILTER_EMPTY = file -> true; 40 | 41 | /** 42 | * Not instantiable. 43 | * */ 44 | private FileUtils() { 45 | throw new UnsupportedOperationException("This class is not instantiable"); 46 | } 47 | 48 | /** 49 | * It returns a list of all files in a folder, including all files in all subfolders 50 | * 51 | * @param path 52 | * The path of the folder you want to get all the files from. 53 | * 54 | * @return A list of files 55 | */ 56 | public static List getAllFilesOfAFileFolder(@NotNull File path) { 57 | return getAllFilesOfAFileFolder(path, FILE_FILTER_EMPTY); 58 | } 59 | 60 | /** 61 | * It returns a list of all files in a folder, including all files in subfolders, that match a given filter 62 | * 63 | * @param path 64 | * The path of the folder you want to get all the files from. 65 | * 66 | * @param filter 67 | * The filter to be used to filter the files. 68 | * 69 | * @return A list of all files in a folder and its subfolders. 70 | */ 71 | public static List getAllFilesOfAFileFolder(@NotNull File path, @NotNull FileFilter filter) { 72 | final List files = new ArrayList<>(); 73 | final File[] filesOfFolder = path.listFiles(filter); 74 | 75 | for (File file : filesOfFolder) { 76 | if (file.isDirectory()) 77 | files.addAll(getAllFilesOfAFileFolder(file, filter)); 78 | else 79 | files.add(file); 80 | } 81 | 82 | return files; 83 | } 84 | 85 | } 86 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/logger/LogLevel.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.logger; 26 | 27 | import com.github.mattnicee7.mattlib.console.ConsoleUtil; 28 | import lombok.Getter; 29 | import org.jetbrains.annotations.NotNull; 30 | import org.jetbrains.annotations.Nullable; 31 | 32 | import java.util.Arrays; 33 | 34 | @Getter 35 | public enum LogLevel { 36 | 37 | WARNING("[WARNING]" + ConsoleUtil.ANSI_RESET, ConsoleUtil.ANSI_RED_BACKGROUND), 38 | INFO("[INFO]" + ConsoleUtil.ANSI_RESET, ConsoleUtil.ANSI_CYAN_BACKGROUND), 39 | FINE("[FINE]" + ConsoleUtil.ANSI_RESET, ConsoleUtil.ANSI_GREEN_BACKGROUND); 40 | 41 | private final String name; 42 | private final String backgroundColor; 43 | 44 | LogLevel(@NotNull String name, @Nullable String backgroundColor) { 45 | this.name = name; 46 | this.backgroundColor = backgroundColor; 47 | } 48 | 49 | @Nullable 50 | public static LogLevel of(@NotNull String logLevelString) { 51 | return Arrays.stream(values()) 52 | .filter(logLevel -> logLevel.name.equalsIgnoreCase(logLevelString)) 53 | .findFirst() 54 | .orElse(null); 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/logger/Logger.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.logger; 26 | 27 | import com.github.mattnicee7.mattlib.date.DateUtil; 28 | import lombok.NoArgsConstructor; 29 | import org.jetbrains.annotations.NotNull; 30 | 31 | import java.io.PrintStream; 32 | import java.time.format.DateTimeFormatter; 33 | 34 | @NoArgsConstructor 35 | public class Logger { 36 | 37 | private static final PrintStream out = System.out; 38 | 39 | /** 40 | * Log a message with the {@link LogLevel} level. 41 | * 42 | * @param logLevel 43 | * The {@link LogLevel} level. 44 | * 45 | * @param message 46 | * The message to log. 47 | */ 48 | public void log(@NotNull LogLevel logLevel, @NotNull String message) { 49 | out.println(logLevel.getName() + ": " + message); 50 | } 51 | 52 | /** 53 | * Log a message with the {@link LogLevel} level and timestamp. 54 | * 55 | * @param logLevel 56 | * The {@link LogLevel} level. 57 | * 58 | * @param message 59 | * The message to log. 60 | * 61 | * @param timeStamp 62 | * If you want timestamp to be added to the log message. 63 | * */ 64 | public void log(@NotNull LogLevel logLevel, @NotNull String message, boolean timeStamp) { 65 | if (!timeStamp) { 66 | log(logLevel, message); 67 | return; 68 | } 69 | 70 | out.println(DateUtil.getNowTimeStamp() + " " + logLevel.getName() + ": " + message); 71 | } 72 | 73 | /** 74 | * Log a message with {@link LogLevel} level, timestamp and yours {@link DateTimeFormatter}. 75 | * 76 | * @param logLevel 77 | * The {@link LogLevel} level. 78 | * 79 | * @param message 80 | * The message to log. 81 | * 82 | * @param timeStamp 83 | * If you want timestamp to be added to the log message. 84 | * 85 | * @param dateTimeFormatter 86 | * The {@link DateTimeFormatter} to use. 87 | * */ 88 | public void log(@NotNull LogLevel logLevel, @NotNull String message, boolean timeStamp, @NotNull DateTimeFormatter dateTimeFormatter) { 89 | if (!timeStamp) { 90 | log(logLevel, message); 91 | return; 92 | } 93 | 94 | out.println(DateUtil.getNowTimeStamp(dateTimeFormatter) + " " + logLevel.getName() + ": " + message); 95 | } 96 | 97 | public void fine(@NotNull String message) { 98 | fine(message, false); 99 | } 100 | 101 | public void fine(@NotNull String message, boolean timeStamp) { 102 | log(LogLevel.FINE, message, timeStamp); 103 | } 104 | 105 | public void warn(@NotNull String message) { 106 | warn(message, false); 107 | } 108 | 109 | public void warn(@NotNull String message, boolean timeStamp) { 110 | log(LogLevel.WARNING, message, timeStamp); 111 | } 112 | 113 | public void info(@NotNull String message) { 114 | info(message, false); 115 | } 116 | 117 | public void info(@NotNull String message, boolean timeStamp) { 118 | log(LogLevel.INFO, message, timeStamp); 119 | } 120 | 121 | } 122 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/password/PasswordVerifier.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.password; 26 | 27 | import lombok.*; 28 | import org.jetbrains.annotations.NotNull; 29 | 30 | import java.util.ArrayList; 31 | import java.util.List; 32 | 33 | @NoArgsConstructor 34 | @AllArgsConstructor 35 | @Getter(AccessLevel.PACKAGE) 36 | @Setter(AccessLevel.PACKAGE) 37 | public class PasswordVerifier { 38 | 39 | private char[] symbolsPattern = "!@#$%¨&*()-=+".toCharArray(); 40 | private char[] lowerLettersPattern = "abcdefghijklmnopqrstuvwxyz".toCharArray(); 41 | private char[] upperLettersPattern = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray(); 42 | 43 | private int minLength; 44 | private int maxLength; 45 | private int minSymbols; 46 | private int minLowerLetter; 47 | private int minUpperLetter; 48 | 49 | private boolean repeatedCharacters; 50 | private boolean removeBlankSpaces = true; 51 | 52 | public boolean verify(@NotNull String password) { 53 | if (removeBlankSpaces) 54 | password = password.replace(" ", ""); 55 | 56 | if (!checkIfHasMinLength(password)) 57 | return false; 58 | 59 | if (checkIfHasMaxLength(password)) 60 | return false; 61 | 62 | if (getPatternCount(symbolsPattern, password) < minSymbols) 63 | return false; 64 | 65 | if (getPatternCount(lowerLettersPattern, password) < minLowerLetter) 66 | return false; 67 | 68 | if (getPatternCount(upperLettersPattern, password) < minUpperLetter) 69 | return false; 70 | 71 | if (repeatedCharacters && hasRepeatedCharacters(password)) 72 | return false; 73 | 74 | return true; 75 | } 76 | 77 | private boolean checkIfHasMinLength(@NotNull String password) { 78 | return password.length() >= minLength; 79 | } 80 | 81 | private boolean checkIfHasMaxLength(@NotNull String password) { 82 | return maxLength > 0 && password.length() >= maxLength; 83 | } 84 | 85 | private int getPatternCount(char[] pattern, @NotNull String password) { 86 | return (int) password.chars().mapToObj(it -> (char) it).filter(it -> equals(it, pattern)).count(); 87 | } 88 | 89 | private boolean hasRepeatedCharacters(@NotNull String password) { 90 | final List characters = new ArrayList<>(); 91 | char[] passwordArray = password.toCharArray(); 92 | 93 | for (char character : passwordArray) { 94 | if (characters.contains(character)) 95 | return true; 96 | 97 | characters.add(character); 98 | } 99 | 100 | return false; 101 | } 102 | 103 | private boolean equals(char character, char[] array) { 104 | for (char element : array) 105 | if (element == character) 106 | return true; 107 | 108 | return false; 109 | } 110 | 111 | } 112 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/password/PasswordVerifierBuilder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.password; 26 | 27 | import lombok.NoArgsConstructor; 28 | 29 | @NoArgsConstructor 30 | public class PasswordVerifierBuilder { 31 | 32 | private final PasswordVerifier passwordVerifier = new PasswordVerifier(); 33 | 34 | public PasswordVerifierBuilder symbolsPattern(char[] symbolsPattern) { 35 | passwordVerifier.setSymbolsPattern(symbolsPattern); 36 | return this; 37 | } 38 | 39 | public PasswordVerifierBuilder lowerLettersPattern(char[] lowerLettersPattern) { 40 | passwordVerifier.setLowerLettersPattern(lowerLettersPattern); 41 | return this; 42 | } 43 | 44 | public PasswordVerifierBuilder upperLettersPattern(char[] upperLettersPattern) { 45 | passwordVerifier.setUpperLettersPattern(upperLettersPattern); 46 | return this; 47 | } 48 | 49 | public PasswordVerifierBuilder minLength(int minLength) { 50 | passwordVerifier.setMinLength(minLength); 51 | return this; 52 | } 53 | 54 | public PasswordVerifierBuilder maxLength(int maxLength) { 55 | passwordVerifier.setMaxLength(maxLength); 56 | return this; 57 | } 58 | 59 | public PasswordVerifierBuilder minSymbols(int minSymbols) { 60 | passwordVerifier.setMinSymbols(minSymbols); 61 | return this; 62 | } 63 | 64 | public PasswordVerifierBuilder minLowerLetter(int minLowerLetter) { 65 | passwordVerifier.setMinLowerLetter(minLowerLetter); 66 | return this; 67 | } 68 | 69 | public PasswordVerifierBuilder minUpperLetter(int minUpperLetter) { 70 | passwordVerifier.setMinUpperLetter(minUpperLetter); 71 | return this; 72 | } 73 | 74 | public PasswordVerifierBuilder repeatedCharacters(boolean repeatedCharacters) { 75 | passwordVerifier.setRepeatedCharacters(repeatedCharacters); 76 | return this; 77 | } 78 | 79 | public PasswordVerifierBuilder removeBlankSpaces(boolean removeBlankSpaces) { 80 | passwordVerifier.setRemoveBlankSpaces(removeBlankSpaces); 81 | return this; 82 | } 83 | 84 | public PasswordVerifier build() { 85 | return passwordVerifier; 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/qrcode/QRCodeGenerator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.qrcode; 26 | 27 | import com.google.zxing.BarcodeFormat; 28 | import com.google.zxing.MultiFormatWriter; 29 | import com.google.zxing.client.j2se.MatrixToImageWriter; 30 | import com.google.zxing.common.BitMatrix; 31 | import org.jetbrains.annotations.NotNull; 32 | 33 | import java.io.File; 34 | 35 | /** 36 | * Utility class to generate qr codes. 37 | */ 38 | public class QRCodeGenerator { 39 | 40 | private QRCodeGenerator() { 41 | throw new UnsupportedOperationException("This class is not instantiable"); 42 | } 43 | 44 | /** 45 | * Generate a QRCode with the text you prefer. 46 | * Default charset: UTF-8 47 | * 48 | * @param text 49 | * The text of the QRCode content. 50 | * 51 | * @param path 52 | * File path to save the qr code image. 53 | * 54 | * @param height 55 | * Height of the QRCode image. 56 | * 57 | * @param width 58 | * Width of the QRCode image. 59 | */ 60 | public static void generateQRCode(@NotNull String text, @NotNull String path, int height, int width) { 61 | generateQRCode(text, path, "UTF-8", height, width); 62 | } 63 | 64 | /** 65 | * Generate a QRCode with the text you prefer, 66 | * and with the charset you prefer. 67 | * 68 | * @param text 69 | * The text of the QRCode content. 70 | * 71 | * @param path 72 | * File path to save the qr code image. 73 | * 74 | * @param charset 75 | * The charset of the qr code text. 76 | * 77 | * @param height 78 | * Height of the QRCode image. 79 | * 80 | * @param width 81 | * Width of the QRCode image. 82 | */ 83 | public static void generateQRCode(@NotNull String text, @NotNull String path, @NotNull String charset, int height, int width) { 84 | try { 85 | BitMatrix matrix = new MultiFormatWriter().encode( 86 | new String(text.getBytes(charset), 87 | charset), 88 | BarcodeFormat.QR_CODE, 89 | width, 90 | height); 91 | 92 | MatrixToImageWriter.writeToPath( 93 | matrix, 94 | path.substring(path.lastIndexOf('.') + 1), 95 | new File(path).getAbsoluteFile().toPath() 96 | ); 97 | 98 | } catch (Exception exception) { 99 | exception.printStackTrace(); 100 | } 101 | } 102 | 103 | } 104 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/qrcode/QRCodeReader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.qrcode; 26 | 27 | import com.google.zxing.BinaryBitmap; 28 | import com.google.zxing.MultiFormatReader; 29 | import com.google.zxing.client.j2se.BufferedImageLuminanceSource; 30 | import com.google.zxing.common.HybridBinarizer; 31 | import org.jetbrains.annotations.NotNull; 32 | import org.jetbrains.annotations.Nullable; 33 | 34 | import javax.imageio.ImageIO; 35 | import java.io.FileInputStream; 36 | 37 | /** 38 | * Utility class to read QRCodes. 39 | */ 40 | public class QRCodeReader { 41 | 42 | private QRCodeReader() { 43 | throw new UnsupportedOperationException("This class is not instantiable"); 44 | } 45 | 46 | /** 47 | * Read the QRCode image. 48 | * 49 | * @param path 50 | * Image file path of QRCode. 51 | * 52 | * @return The content of qr code. 53 | */ 54 | @Nullable 55 | public static String readQRCode(@NotNull String path) { 56 | try { 57 | BinaryBitmap binaryBitmap = new BinaryBitmap( 58 | new HybridBinarizer( 59 | new BufferedImageLuminanceSource( 60 | ImageIO.read( 61 | new FileInputStream(path))))); 62 | 63 | return new MultiFormatReader().decode(binaryBitmap).getText(); 64 | } catch (Exception exception) { 65 | exception.printStackTrace(); 66 | } 67 | 68 | return null; 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/random/RandomUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.random; 26 | 27 | import lombok.val; 28 | import org.jetbrains.annotations.NotNull; 29 | 30 | import java.util.List; 31 | import java.util.Random; 32 | 33 | /** 34 | * Utility class for random things. 35 | */ 36 | public class RandomUtils { 37 | 38 | /** 39 | * The random instance. 40 | */ 41 | private static final Random RANDOM = new Random(); 42 | 43 | /** 44 | * Alphabet & Numeric characters pattern. 45 | */ 46 | private static final char[] ALPHANUMERIC_CHARS = "01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray(); 47 | 48 | /** 49 | * Alphabet, Numeric & Special characters pattern. 50 | */ 51 | private static final char[] ALPHANUMERIC_SPECIAL_CHARS = "01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%&*()_+=-,.;/".toCharArray(); 52 | 53 | 54 | /** 55 | * Not instantiable 56 | */ 57 | private RandomUtils() { 58 | throw new UnsupportedOperationException("This class is not instantiable"); 59 | } 60 | 61 | /** 62 | * Get a random element from a generic type list 63 | * 64 | * @param elements 65 | * A generic list 66 | * 67 | * @throws IllegalArgumentException 68 | *
    69 | *
  • If the provided {@code elements} is empty
  • 70 | *
71 | * 72 | * @return A random element from the list 73 | */ 74 | public static T getRandomElement(@NotNull List elements) { 75 | if (elements.isEmpty()) 76 | throw new IllegalArgumentException("List can't be empty"); 77 | 78 | return elements.get(RANDOM.nextInt(elements.size())); 79 | } 80 | 81 | /** 82 | * Get a random element from a generic array. 83 | * 84 | * @param elements 85 | * A generic array. 86 | * 87 | * @throws IllegalArgumentException 88 | *
    89 | *
  • If the provided {@code elements} is null or empty.
  • 90 | *
91 | * 92 | * @return A random element from the array. 93 | */ 94 | public static T getRandomElement(@NotNull T[] elements) { 95 | if (elements.length < 1) 96 | throw new IllegalArgumentException("Array can't be empty"); 97 | 98 | return elements[RANDOM.nextInt(elements.length)]; 99 | } 100 | 101 | /** 102 | * Checks if the percentage you entered is between the randomly generated percentage. 103 | * 104 | * @param percentage 105 | * The percentage that you want to test. 106 | * 107 | * @throws IllegalArgumentException 108 | * If the percentage you entered is less than 0. 109 | * 110 | * @return If the random percentage is within the one you entered 111 | */ 112 | public static boolean checkPercentage(double percentage) { 113 | if (percentage < 0.0) 114 | throw new IllegalArgumentException("The percentage must be greater than 0"); 115 | 116 | return RANDOM.nextDouble() * 100 <= percentage; 117 | } 118 | 119 | /** 120 | * Get a random number between two numbers 121 | * 122 | * @param min 123 | * The minimum number 124 | * 125 | * @param max 126 | * The maximum number 127 | * 128 | * @return A random number among those informed. 129 | */ 130 | public static int getRandomNumberBetween(int min, int max) { 131 | int randomNumber = RANDOM.nextInt(max); 132 | 133 | while (randomNumber < min) 134 | randomNumber = RANDOM.nextInt(max); 135 | 136 | return randomNumber; 137 | } 138 | 139 | /** 140 | * Returns a random string. 141 | * 142 | * @param length 143 | * Size of random string. 144 | * 145 | * @throws IllegalArgumentException 146 | *
    147 | *
  • If the provided size is 0 or below.
  • 148 | *
149 | * 150 | * @return A random string with the size informed. 151 | */ 152 | public static String generateRandomString(int length) { 153 | if (length <= 0) 154 | throw new IllegalArgumentException("The size must be greater than 0"); 155 | 156 | val stringBuilder = new StringBuilder(); 157 | 158 | for (int i = 0; i < length; i++) 159 | stringBuilder.append(ALPHANUMERIC_CHARS[RANDOM.nextInt(ALPHANUMERIC_CHARS.length)]); 160 | 161 | return stringBuilder.toString(); 162 | } 163 | 164 | /** 165 | * Generate a random string with size informed, and if you prefer, you can use special characters. 166 | * 167 | * @param length 168 | * Size of random string. 169 | * 170 | * @param specialChars 171 | * If you want to use the special characters in the random string. 172 | * 173 | * @throws IllegalArgumentException 174 | *
    175 | *
  • If the provided size is 0 or below.
  • 176 | *
177 | * 178 | * @return The random string. 179 | */ 180 | public static String generateRandomString(int length, boolean specialChars) { 181 | if (length <= 0) 182 | throw new IllegalArgumentException("The size must be greater than 0"); 183 | 184 | if (!specialChars) 185 | return generateRandomString(length); 186 | 187 | val stringBuilder = new StringBuilder(); 188 | 189 | for (int i = 0; i < length; i++) 190 | stringBuilder.append(ALPHANUMERIC_SPECIAL_CHARS[RANDOM.nextInt(ALPHANUMERIC_CHARS.length)]); 191 | 192 | return stringBuilder.toString(); 193 | } 194 | 195 | } 196 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/singlemap/Pair.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.singlemap; 26 | 27 | import lombok.AllArgsConstructor; 28 | import lombok.Getter; 29 | import lombok.Setter; 30 | 31 | @AllArgsConstructor 32 | @Getter 33 | @Setter 34 | public class Pair { 35 | 36 | private F first; 37 | private S second; 38 | 39 | public static Pair of(F first, S second) { 40 | return new Pair<>(first, second); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/singlemap/Quadruple.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.singlemap; 26 | 27 | import lombok.AllArgsConstructor; 28 | import lombok.Getter; 29 | import lombok.Setter; 30 | 31 | @AllArgsConstructor 32 | @Getter 33 | @Setter 34 | public class Quadruple { 35 | 36 | private F first; 37 | private S second; 38 | private T third; 39 | private Q fourth; 40 | 41 | public static Quadruple of(F first, S second, T third, Q fourth) { 42 | return new Quadruple<>(first, second, third, fourth); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/singlemap/Quintuple.java: -------------------------------------------------------------------------------- 1 | package com.github.mattnicee7.mattlib.singlemap; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Getter; 5 | import lombok.Setter; 6 | 7 | @AllArgsConstructor 8 | @Getter 9 | @Setter 10 | public class Quintuple { 11 | 12 | private F first; 13 | private S second; 14 | private T third; 15 | private Q fourth; 16 | private E fifth; 17 | 18 | public static Quintuple of(F first, S second, T third, Q fourth, E fifth) { 19 | return new Quintuple<>(first, second, third, fourth, fifth); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/singlemap/Triple.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.singlemap; 26 | 27 | import lombok.AllArgsConstructor; 28 | import lombok.Getter; 29 | import lombok.Setter; 30 | 31 | @AllArgsConstructor 32 | @Getter 33 | @Setter 34 | public class Triple { 35 | 36 | private F first; 37 | private S second; 38 | private T third; 39 | 40 | public static Triple of(F first, S second, T third) { 41 | return new Triple<>(first, second, third); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/stopwatch/StopWatch.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.stopwatch; 26 | 27 | import lombok.AccessLevel; 28 | import lombok.Getter; 29 | import lombok.NoArgsConstructor; 30 | 31 | @NoArgsConstructor 32 | @Getter(AccessLevel.PACKAGE) 33 | public class StopWatch { 34 | 35 | private long startTime; 36 | private long endTime; 37 | 38 | /** 39 | * Start the stopwatch. 40 | * */ 41 | public void start() { 42 | this.startTime = System.currentTimeMillis(); 43 | } 44 | 45 | /** 46 | * Stop the stopwatch 47 | * */ 48 | public void stop() { 49 | this.endTime = System.currentTimeMillis(); 50 | } 51 | 52 | /** 53 | * Get the elapsed time in milliseconds. 54 | * */ 55 | public long getTotalTimeElapsedInMillis() { 56 | return endTime - startTime; 57 | } 58 | 59 | public String getResult() { 60 | return toString(); 61 | } 62 | 63 | @Override 64 | public String toString() { 65 | return getTotalTimeElapsedInMillis() + "ms"; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/string/Replacer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.string; 26 | 27 | import org.jetbrains.annotations.NotNull; 28 | 29 | import java.util.ArrayList; 30 | import java.util.HashMap; 31 | import java.util.List; 32 | import java.util.Map; 33 | import java.util.Map.Entry; 34 | 35 | public class Replacer { 36 | 37 | private final Map replacers = new HashMap<>(); 38 | 39 | public Replacer put(@NotNull String key, @NotNull Object value) { 40 | replacers.put(key, value); 41 | return this; 42 | } 43 | 44 | public String replace(@NotNull String message) { 45 | for (Entry entry : replacers.entrySet()) { 46 | message = message.replace(entry.getKey(), entry.getValue().toString()); 47 | } 48 | 49 | return message; 50 | } 51 | 52 | public List replace(@NotNull List messages) { 53 | final List messagesReplaced = new ArrayList<>(); 54 | 55 | for (String message : messages) 56 | messagesReplaced.add(replace(message)); 57 | 58 | return messagesReplaced; 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/string/StringUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.string; 26 | 27 | import org.jetbrains.annotations.NotNull; 28 | 29 | import java.util.function.Function; 30 | 31 | public class StringUtil { 32 | 33 | /** 34 | * Not instantiable. 35 | * */ 36 | private StringUtil() { 37 | throw new UnsupportedOperationException("This class is not instantiable"); 38 | } 39 | 40 | /** 41 | * 42 | * */ 43 | public static String format(@NotNull String message, @NotNull Function format) { 44 | return format.apply(message); 45 | } 46 | 47 | /** 48 | * If the message is empty, return the default message, otherwise return the message 49 | * 50 | * @param message 51 | * The message to check if it's empty. 52 | * 53 | * @param defaultMessage 54 | * The message to return if the message is empty. 55 | * 56 | * @return The message if it is not empty, otherwise the defaultMessage. 57 | */ 58 | public static String ifEmpty(@NotNull String message, @NotNull String defaultMessage) { 59 | return message.isEmpty() ? defaultMessage : message; 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/time/TimeFormat.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.time; 26 | 27 | import com.github.mattnicee7.mattlib.singlemap.Pair; 28 | import lombok.AllArgsConstructor; 29 | import lombok.Getter; 30 | import lombok.NoArgsConstructor; 31 | import lombok.Setter; 32 | import org.jetbrains.annotations.NotNull; 33 | 34 | /** 35 | * 36 | */ 37 | @NoArgsConstructor 38 | @AllArgsConstructor 39 | @Getter 40 | @Setter 41 | public class TimeFormat { 42 | 43 | private long timeInSecond; 44 | private String singular; 45 | private String plural; 46 | 47 | public TimeFormat(@NotNull String singular, @NotNull String plural) { 48 | this.singular = singular; 49 | this.plural = plural; 50 | } 51 | 52 | public static TimeFormat of(long time, @NotNull String singular, @NotNull String plural) { 53 | return new TimeFormat(time, singular, plural); 54 | } 55 | 56 | public static TimeFormat of(@NotNull String singular, @NotNull String plural) { 57 | return new TimeFormat(singular, plural); 58 | } 59 | 60 | /** 61 | * 62 | */ 63 | public void setSingularAndPlural(Pair singularAndPlural) { 64 | this.singular = singularAndPlural.getFirst(); 65 | this.plural = singularAndPlural.getSecond(); 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/time/TimeFormatter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.time; 26 | 27 | import lombok.AccessLevel; 28 | import lombok.Getter; 29 | import org.jetbrains.annotations.NotNull; 30 | 31 | import java.util.*; 32 | import java.util.concurrent.TimeUnit; 33 | import java.util.Map.Entry; 34 | 35 | /** 36 | * It converts a number of milliseconds into a human readable format. 37 | */ 38 | @Getter(AccessLevel.PACKAGE) 39 | public class TimeFormatter { 40 | 41 | private TimeFormat year = new TimeFormat(); 42 | private TimeFormat month = new TimeFormat(); 43 | private TimeFormat week = new TimeFormat(); 44 | private TimeFormat day = new TimeFormat(); 45 | private TimeFormat hour = new TimeFormat(); 46 | private TimeFormat minute = new TimeFormat(); 47 | private TimeFormat second = new TimeFormat(); 48 | 49 | public TimeFormatter() { 50 | applyTimeInTimeFormats(); 51 | } 52 | 53 | public TimeFormatter( 54 | @NotNull TimeFormat year, @NotNull TimeFormat month, 55 | @NotNull TimeFormat week, @NotNull TimeFormat day, 56 | @NotNull TimeFormat hour, @NotNull TimeFormat minute, 57 | @NotNull TimeFormat second) { 58 | this.year = year; 59 | this.month = month; 60 | this.week = week; 61 | this.day = day; 62 | this.hour = hour; 63 | this.minute = minute; 64 | this.second = second; 65 | applyTimeInTimeFormats(); 66 | } 67 | 68 | /** 69 | * Format the time in milliseconds to a string. 70 | * 71 | * Credits: ViiictorXD, (Thanks so much, Viiictor). 72 | * 73 | * @param timeInMillis 74 | * The time in milliseconds. 75 | * 76 | * @return The formatted time. 77 | */ 78 | public String format(long timeInMillis) { 79 | final List values = Arrays.asList( 80 | year, month, week, day, hour, minute, second 81 | ); 82 | final Map timeFormatMap = new LinkedHashMap<>(); 83 | 84 | long leftTime = TimeUnit.MILLISECONDS.toSeconds(timeInMillis); 85 | for (TimeFormat value : values) { 86 | if (leftTime >= value.getTimeInSecond()) { 87 | int durationInCurrentTime = (int) (leftTime / value.getTimeInSecond()); 88 | leftTime %= value.getTimeInSecond(); 89 | 90 | timeFormatMap.put(value, durationInCurrentTime); 91 | } 92 | } 93 | 94 | final StringBuilder stringBuilder = new StringBuilder(); 95 | final Set> entries = timeFormatMap.entrySet(); 96 | int size = entries.size(); 97 | 98 | int index = 1; 99 | 100 | for (Entry entry : entries) { 101 | final TimeFormat key = entry.getKey(); 102 | final Integer value = entry.getValue(); 103 | 104 | stringBuilder.append(value) 105 | .append(value == 1 ? key.getSingular() : key.getPlural()); 106 | 107 | if (index == size - 1) 108 | stringBuilder.append(" & "); 109 | else if (index != size) 110 | stringBuilder.append(", "); 111 | 112 | index++; 113 | } 114 | 115 | return stringBuilder.toString(); 116 | } 117 | 118 | /** 119 | * > It sets the time in seconds for each of the time formats 120 | */ 121 | private void applyTimeInTimeFormats() { 122 | this.year.setTimeInSecond(31104000L); 123 | this.month.setTimeInSecond(2592000L); 124 | this.week.setTimeInSecond(604800L); 125 | this.day.setTimeInSecond(86400L); 126 | this.hour.setTimeInSecond(3600L); 127 | this.minute.setTimeInSecond(60L); 128 | this.second.setTimeInSecond(1L); 129 | } 130 | 131 | } 132 | -------------------------------------------------------------------------------- /misc/src/main/java/com/github/mattnicee7/mattlib/time/TimeFormatterBuilder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.time; 26 | 27 | import com.github.mattnicee7.mattlib.singlemap.Pair; 28 | import lombok.NoArgsConstructor; 29 | import org.jetbrains.annotations.NotNull; 30 | 31 | /** 32 | * A class that builds a {@link TimeFormatter}. 33 | * */ 34 | @NoArgsConstructor 35 | public class TimeFormatterBuilder { 36 | 37 | private static final TimeFormatter DEFAULT_TIME_FORMATTER = new TimeFormatter( 38 | TimeFormat.of(" year", " years"), 39 | TimeFormat.of(" month", " months"), 40 | TimeFormat.of(" week", " weeks"), 41 | TimeFormat.of(" day", " days"), 42 | TimeFormat.of(" hour", " hours"), 43 | TimeFormat.of(" minute", " minutes"), 44 | TimeFormat.of(" second", " seconds") 45 | ); 46 | 47 | private final TimeFormatter timeFormatter = new TimeFormatter(); 48 | 49 | public static TimeFormatter getDefaultTimeFormatter() { 50 | return DEFAULT_TIME_FORMATTER; 51 | } 52 | 53 | public TimeFormatterBuilder setYearFormatter(@NotNull Pair singularAndPlural) { 54 | timeFormatter.getYear().setSingularAndPlural(singularAndPlural); 55 | return this; 56 | } 57 | 58 | public TimeFormatterBuilder setYearFormatter(@NotNull String singular, @NotNull String plural) { 59 | return setYearFormatter(Pair.of(singular, plural)); 60 | } 61 | 62 | public TimeFormatterBuilder setMonthFormatter(@NotNull Pair singularAndPlural) { 63 | timeFormatter.getMonth().setSingularAndPlural(singularAndPlural); 64 | return this; 65 | } 66 | 67 | public TimeFormatterBuilder setMonthFormatter(@NotNull String singular, @NotNull String plural) { 68 | return setMonthFormatter(Pair.of(singular, plural)); 69 | } 70 | 71 | public TimeFormatterBuilder setWeekFormatter(@NotNull Pair singularAndPlural) { 72 | timeFormatter.getWeek().setSingularAndPlural(singularAndPlural); 73 | return this; 74 | } 75 | 76 | public TimeFormatterBuilder setWeekFormatter(@NotNull String singular, @NotNull String plural) { 77 | return setWeekFormatter(Pair.of(singular, plural)); 78 | } 79 | 80 | public TimeFormatterBuilder setDayFormatter(@NotNull Pair singularAndPlural) { 81 | timeFormatter.getDay().setSingularAndPlural(singularAndPlural); 82 | return this; 83 | } 84 | 85 | public TimeFormatterBuilder setDayFormatter(@NotNull String singular, @NotNull String plural) { 86 | return setDayFormatter(Pair.of(singular, plural)); 87 | } 88 | 89 | public TimeFormatterBuilder setHourFormatter(@NotNull Pair singularAndPlural) { 90 | timeFormatter.getHour().setSingularAndPlural(singularAndPlural); 91 | return this; 92 | } 93 | 94 | public TimeFormatterBuilder setHourFormatter(@NotNull String singular, @NotNull String plural) { 95 | return setHourFormatter(Pair.of(singular, plural)); 96 | } 97 | 98 | public TimeFormatterBuilder setMinuteFormatter(@NotNull Pair singularAndPlural) { 99 | timeFormatter.getMinute().setSingularAndPlural(singularAndPlural); 100 | return this; 101 | } 102 | 103 | public TimeFormatterBuilder setMinuteFormatter(@NotNull String singular, @NotNull String plural) { 104 | return setMinuteFormatter(Pair.of(singular, plural)); 105 | } 106 | 107 | public TimeFormatterBuilder setSecondFormatter(@NotNull Pair singularAndPlural) { 108 | timeFormatter.getSecond().setSingularAndPlural(singularAndPlural); 109 | return this; 110 | } 111 | 112 | public TimeFormatterBuilder setSecondFormatter(@NotNull String singular, @NotNull String plural) { 113 | return setSecondFormatter(Pair.of(singular, plural)); 114 | } 115 | 116 | public TimeFormatter build() { 117 | return timeFormatter; 118 | } 119 | 120 | } 121 | -------------------------------------------------------------------------------- /misc/src/test/java/com/github/mattnicee7/mattlib/cooldown/CooldownMapTest.java: -------------------------------------------------------------------------------- 1 | package com.github.mattnicee7.mattlib.cooldown; 2 | 3 | import static org.junit.jupiter.api.Assertions.*; 4 | 5 | import org.junit.jupiter.api.BeforeEach; 6 | import org.junit.jupiter.api.Test; 7 | 8 | import java.util.concurrent.TimeUnit; 9 | 10 | public class CooldownMapTest { 11 | 12 | /** 13 | * Instance of the CooldownMap for String objects used in all test cases. 14 | */ 15 | private CooldownMap cooldownMap; 16 | 17 | /** 18 | * Set up method to initialize the CooldownMap instance before each test. 19 | */ 20 | @BeforeEach 21 | public void setUp() { 22 | this.cooldownMap = CooldownMap.of(String.class); 23 | } 24 | 25 | /** 26 | * Tests the cooldown expiry mechanism. 27 | * Verifies that an object remains in cooldown for the specified duration and then is no longer in cooldown. 28 | * 29 | * @throws InterruptedException if the thread sleep is interrupted 30 | */ 31 | @Test 32 | public void testCooldownExpiry() throws InterruptedException { 33 | final String key = "TestKey"; 34 | final long cooldownTime = 2000L; // 2 seconds 35 | 36 | this.cooldownMap.put(key, cooldownTime); 37 | Thread.sleep(1000); // Wait for 1 second 38 | assertTrue(cooldownMap.isInCooldown(key), "Object should still be in cooldown"); 39 | Thread.sleep(1500); // Wait additional 1.5 seconds 40 | assertFalse(cooldownMap.isInCooldown(key), "Object should no longer be in cooldown"); 41 | } 42 | 43 | /** 44 | * Tests the accuracy of the getRemainingTime method. 45 | * Ensures that the method returns a time that is within a second of the expected remaining cooldown time. 46 | */ 47 | @Test 48 | public void testGetRemainingTimeAccuracy() { 49 | final String key = "TestKey"; 50 | final long cooldownTime = 5000L; // 5 seconds 51 | 52 | this.cooldownMap.put(key, cooldownTime); 53 | final long remainingTime = cooldownMap.getRemainingTime(key); 54 | assertTrue(remainingTime <= cooldownTime && remainingTime > cooldownTime - 1000, 55 | "Remaining time should be accurate within a second"); 56 | } 57 | 58 | /** 59 | * Tests the functionality of updating the cooldown time of an object already in cooldown. 60 | * Verifies that the most recent cooldown time is applied and the old one is overridden. 61 | */ 62 | @Test 63 | public void testPutObjectTwiceWithDifferentCooldowns() { 64 | final String key = "TestKey"; 65 | this.cooldownMap.put(key, 3000L); // Put with 3 seconds cooldown 66 | this.cooldownMap.put(key, 5000L); // Update with 5 seconds cooldown 67 | 68 | assertTrue(cooldownMap.getRemainingTime(key) > 3000L, 69 | "Cooldown time should be updated to the new value"); 70 | } 71 | 72 | /** 73 | * Tests the removal of an object from cooldown. 74 | * Verifies that an object is no longer considered to be in cooldown after it has been removed. 75 | */ 76 | @Test 77 | public void testRemoveFromCooldown() { 78 | final String key = "TestKey"; 79 | this.cooldownMap.put(key, 10000L); // 10 seconds 80 | this.cooldownMap.remove(key); // Remove from cooldown immediately 81 | 82 | assertFalse(cooldownMap.isInCooldown(key), 83 | "Object should not be in cooldown after being removed"); 84 | } 85 | 86 | /** 87 | * Tests the cooldown time expiry after an object has been removed. 88 | * Verifies that an object is not in cooldown after the cooldown period has expired, 89 | * even if it was not explicitly removed from the cooldown map. 90 | * 91 | * @throws InterruptedException if the thread sleep is interrupted 92 | */ 93 | @Test 94 | public void testCooldownTimeExpiryAfterRemoval() { 95 | final String key = "TestKey"; 96 | this.cooldownMap.put(key, 1000L); // 1 second cooldown 97 | assertTrue(cooldownMap.isInCooldown(key), "Object should initially be in cooldown"); 98 | 99 | try { 100 | TimeUnit.SECONDS.sleep(2); // Wait for cooldown to expire 101 | } catch (InterruptedException e) { 102 | Thread.currentThread().interrupt(); 103 | } 104 | 105 | assertFalse(cooldownMap.isInCooldown(key), 106 | "Object should not be in cooldown after time expires"); 107 | } 108 | 109 | } 110 | 111 | 112 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include 'misc' 2 | include 'sql' 3 | include 'spigot' -------------------------------------------------------------------------------- /spigot/build.gradle: -------------------------------------------------------------------------------- 1 | repositories { 2 | maven { 3 | name = 'spigotmc-repo' 4 | url = 'https://hub.spigotmc.org/nexus/content/repositories/snapshots/' 5 | } 6 | } 7 | 8 | dependencies { 9 | compileOnly 'org.spigotmc:spigot-api:1.16.5-R0.1-SNAPSHOT' 10 | } -------------------------------------------------------------------------------- /spigot/src/main/java/com/github/mattnicee7/util/chat/ChatUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.util.chat; 26 | 27 | import lombok.val; 28 | import lombok.var; 29 | import org.bukkit.ChatColor; 30 | 31 | import java.util.regex.Pattern; 32 | 33 | public class ChatUtils { 34 | 35 | private static boolean HEX_COLOR_SUPPORT; 36 | 37 | public static final Pattern HEX_COLOR_PATTERN = Pattern.compile("&#([0-9A-Fa-f]{6})"); 38 | 39 | private ChatUtils() { 40 | throw new UnsupportedOperationException("This class is not instantiable"); 41 | } 42 | 43 | static { 44 | try { 45 | net.md_5.bungee.api.ChatColor.class.getDeclaredMethod("of", String.class); 46 | HEX_COLOR_SUPPORT = true; 47 | } catch (NoSuchMethodException e) { 48 | HEX_COLOR_SUPPORT = false; 49 | } 50 | } 51 | 52 | /** 53 | * It takes a string, and replaces all hex color codes with their corresponding ChatColor 54 | * 55 | * @param text 56 | * The text to colorize 57 | * 58 | * @return The colored text. 59 | */ 60 | public static String colorize(String text) { 61 | var coloredText = text; 62 | if (HEX_COLOR_SUPPORT) { 63 | val matcher = HEX_COLOR_PATTERN.matcher(coloredText); 64 | val buffer = new StringBuffer(); 65 | 66 | while (matcher.find()) 67 | matcher.appendReplacement(buffer, net.md_5.bungee.api.ChatColor.of("#" + matcher.group(1)).toString()); 68 | 69 | coloredText = matcher.appendTail(buffer).toString(); 70 | } 71 | return ChatColor.translateAlternateColorCodes('&', coloredText); 72 | } 73 | 74 | public static boolean supportHexColor() { 75 | return HEX_COLOR_SUPPORT; 76 | } 77 | 78 | } -------------------------------------------------------------------------------- /spigot/src/main/java/com/github/mattnicee7/util/player/PlayerUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.util.player; 26 | 27 | import lombok.experimental.UtilityClass; 28 | 29 | public class PlayerUtils { 30 | 31 | } 32 | -------------------------------------------------------------------------------- /spigot/src/main/java/com/github/mattnicee7/util/serializer/location/LocationSerializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.util.serializer.location; 26 | 27 | import org.bukkit.Bukkit; 28 | import org.bukkit.Location; 29 | import org.jetbrains.annotations.NotNull; 30 | 31 | /** 32 | * This class is a util class to serialize Bukkit Locations. 33 | */ 34 | public class LocationSerializer { 35 | 36 | private static final String DEFAULT_SEPARATOR = ";"; 37 | 38 | /** 39 | * Not instantiable. 40 | * */ 41 | private LocationSerializer() { 42 | throw new UnsupportedOperationException("This class is not instantiable"); 43 | } 44 | 45 | public static String serialize(@NotNull Location location) { 46 | return serialize(location, DEFAULT_SEPARATOR); 47 | } 48 | 49 | public static String serialize(@NotNull Location location, @NotNull String separator) { 50 | return location.getWorld().getName() + separator + 51 | location.getX() + separator + 52 | location.getY() + separator + 53 | location.getZ() + separator + 54 | location.getYaw() + separator + 55 | location.getPitch(); 56 | } 57 | 58 | public static Location deserialize(@NotNull String serialized) { 59 | return deserialize(serialized, DEFAULT_SEPARATOR); 60 | } 61 | 62 | public static Location deserialize(@NotNull String serialized, @NotNull String separator) { 63 | String[] split = serialized.split(separator); 64 | 65 | if (split.length != 6) 66 | throw new IllegalArgumentException( 67 | String.format("Serialized location must be in the format of world%sx%sy%sz%syaw%spitch", separator, separator, separator, separator, separator) 68 | ); 69 | 70 | return new Location( 71 | Bukkit.getWorld(split[0]), 72 | Double.parseDouble(split[1]), 73 | Double.parseDouble(split[2]), 74 | Double.parseDouble(split[3]), 75 | Float.parseFloat(split[4]), 76 | Float.parseFloat(split[5]) 77 | ); 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /sql/build.gradle: -------------------------------------------------------------------------------- 1 | repositories { 2 | mavenCentral() 3 | } 4 | 5 | dependencies { 6 | // SQLite Driver 7 | implementation('org.xerial:sqlite-jdbc:3.41.2.2') 8 | 9 | // MySQL Driver 10 | implementation("mysql:mysql-connector-java:8.0.28") 11 | 12 | // PostgreSQL Driver 13 | implementation('org.postgresql:postgresql:42.5.1') 14 | 15 | // MariaDB Driver 16 | implementation("org.mariadb.jdbc:mariadb-java-client:3.0.3") 17 | } -------------------------------------------------------------------------------- /sql/src/main/java/com/github/mattnicee7/mattlib/credentials/DatabaseCredentials.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.credentials; 26 | 27 | /** 28 | * 29 | */ 30 | public interface DatabaseCredentials { 31 | 32 | /** 33 | * Generate the correct connection link to connect to the database. 34 | * 35 | * @return The correct connection link. 36 | */ 37 | String getUrl(); 38 | 39 | } 40 | -------------------------------------------------------------------------------- /sql/src/main/java/com/github/mattnicee7/mattlib/credentials/impl/MariaDBCredentials.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.credentials.impl; 26 | 27 | import com.github.mattnicee7.mattlib.credentials.DatabaseCredentials; 28 | import lombok.Getter; 29 | import org.jetbrains.annotations.NotNull; 30 | 31 | public class MariaDBCredentials implements DatabaseCredentials { 32 | 33 | private final String address; 34 | private final int port; 35 | private final String database; 36 | 37 | @Getter 38 | private final String username; 39 | 40 | @Getter 41 | private final String password; 42 | 43 | public MariaDBCredentials(@NotNull String address, int port, @NotNull String database, @NotNull String username, @NotNull String password) { 44 | this.address = address; 45 | this.port = port; 46 | this.database = database; 47 | this.username = username; 48 | this.password = password; 49 | } 50 | 51 | public static MariaDBCredentials of(@NotNull String address, int port, @NotNull String database, @NotNull String username, @NotNull String password) { 52 | return new MariaDBCredentials(address, port, database, username, password); 53 | } 54 | 55 | @Override 56 | public String getUrl() { 57 | return "jdbc:mariadb://" + address + ":" + port + "/" + database; 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /sql/src/main/java/com/github/mattnicee7/mattlib/credentials/impl/MySQLCredentials.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.credentials.impl; 26 | 27 | import com.github.mattnicee7.mattlib.credentials.DatabaseCredentials; 28 | import lombok.Getter; 29 | import org.jetbrains.annotations.NotNull; 30 | 31 | /** 32 | * Class responsible for storing credentials of a MySQL database. 33 | */ 34 | public class MySQLCredentials implements DatabaseCredentials { 35 | 36 | private final String address; 37 | private final int port; 38 | private final String database; 39 | 40 | @Getter 41 | private final String username; 42 | 43 | @Getter 44 | private final String password; 45 | 46 | public MySQLCredentials(@NotNull String address, int port, @NotNull String database, @NotNull String username, @NotNull String password) { 47 | this.address = address; 48 | this.port = port; 49 | this.database = database; 50 | this.username = username; 51 | this.password = password; 52 | } 53 | 54 | public static MySQLCredentials of(@NotNull String address, int port, @NotNull String database, @NotNull String username, @NotNull String password) { 55 | return new MySQLCredentials(address, port, database, username, password); 56 | } 57 | 58 | @Override 59 | public String getUrl() { 60 | return "jdbc:mysql://" + address + ":" + port + "/" + database + "?autoReconnect=true"; 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /sql/src/main/java/com/github/mattnicee7/mattlib/credentials/impl/PostgreSQLCredentials.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.credentials.impl; 26 | 27 | import com.github.mattnicee7.mattlib.credentials.DatabaseCredentials; 28 | import lombok.Getter; 29 | import org.jetbrains.annotations.NotNull; 30 | 31 | public class PostgreSQLCredentials implements DatabaseCredentials { 32 | 33 | private final String address; 34 | private final int port; 35 | private final String database; 36 | 37 | @Getter 38 | private final String username; 39 | 40 | @Getter 41 | private final String password; 42 | 43 | public PostgreSQLCredentials(@NotNull String address, int port, @NotNull String database, @NotNull String username, @NotNull String password) { 44 | this.address = address; 45 | this.port = port; 46 | this.database = database; 47 | this.username = username; 48 | this.password = password; 49 | } 50 | 51 | public static PostgreSQLCredentials of(@NotNull String address, int port, @NotNull String database, @NotNull String username, @NotNull String password) { 52 | return new PostgreSQLCredentials(address, port, database, username, password); 53 | } 54 | 55 | @Override 56 | public String getUrl() { 57 | return "jdbc:postgresql://" + address + ":" + port + "/" + database; 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /sql/src/main/java/com/github/mattnicee7/mattlib/credentials/impl/SQLiteCredentials.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.credentials.impl; 26 | 27 | import com.github.mattnicee7.mattlib.credentials.DatabaseCredentials; 28 | import org.jetbrains.annotations.NotNull; 29 | 30 | import java.io.File; 31 | 32 | /** 33 | * Class responsible for storing credentials of a SQLite database. 34 | */ 35 | public class SQLiteCredentials implements DatabaseCredentials { 36 | 37 | private final File file; 38 | 39 | public SQLiteCredentials(@NotNull File file) { 40 | this.file = file; 41 | } 42 | 43 | public static SQLiteCredentials of(@NotNull File file) { 44 | return new SQLiteCredentials(file); 45 | } 46 | 47 | @Override 48 | public String getUrl() { 49 | return "jdbc:sqlite:" + file; 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /sql/src/main/java/com/github/mattnicee7/mattlib/datasource/DataSource.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.datasource; 26 | 27 | import java.sql.Connection; 28 | import java.sql.SQLException; 29 | 30 | /** 31 | * Class responsible for providing a connection to the database, 32 | * and methods to get the connection to use, and close the connection 33 | * when you no longer use it. 34 | */ 35 | public interface DataSource { 36 | 37 | /** 38 | * Get the DataSource connection. 39 | * 40 | * @throws SQLException 41 | *
    42 | *
  • If something went wrong in the syntax.
  • 43 | *
44 | * 45 | * @return DataSource connection. 46 | */ 47 | Connection getConnection() throws SQLException; 48 | 49 | /** 50 | * Close the DataSource connection. 51 | * */ 52 | void closeConnection(); 53 | 54 | } 55 | -------------------------------------------------------------------------------- /sql/src/main/java/com/github/mattnicee7/mattlib/datasource/factory/DataSourceFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.datasource.factory; 26 | 27 | import com.github.mattnicee7.mattlib.credentials.impl.MariaDBCredentials; 28 | import com.github.mattnicee7.mattlib.credentials.impl.MySQLCredentials; 29 | import com.github.mattnicee7.mattlib.credentials.impl.PostgreSQLCredentials; 30 | import com.github.mattnicee7.mattlib.credentials.impl.SQLiteCredentials; 31 | import com.github.mattnicee7.mattlib.datasource.impl.MariaDB; 32 | import com.github.mattnicee7.mattlib.datasource.impl.MySQL; 33 | import com.github.mattnicee7.mattlib.datasource.impl.PostgreSQL; 34 | import com.github.mattnicee7.mattlib.datasource.impl.SQLite; 35 | import com.github.mattnicee7.mattlib.datasource.DataSource; 36 | import com.github.mattnicee7.mattlib.exception.DatabaseConnectionException; 37 | import com.github.mattnicee7.mattlib.exception.DatabaseDriverNotFoundException; 38 | import org.jetbrains.annotations.NotNull; 39 | 40 | /** 41 | * Useful class to create database connections. You can create a connection with MySQL and SQLite. 42 | */ 43 | public class DataSourceFactory { 44 | 45 | /** 46 | * Not instantiable. 47 | * */ 48 | private DataSourceFactory() { 49 | throw new UnsupportedOperationException("This class is not instantiable"); 50 | } 51 | 52 | /** 53 | * Create a DataSource with SQLite file. 54 | * 55 | *

Example Usage 56 | *
 57 |      *     {@code
 58 |      * public class Application {
 59 |      *     public static void main(String[] args) {
 60 |      *         try {
 61 |      *             DataSource dataSource = DataSourceFactory.createSQLiteDataSource(
 62 |      *                      SQLiteCredentials.of(new File(path))
 63 |      *              );
 64 |      *
 65 |      *             // Do something with dataSource (...)
 66 |      *         } catch (DriverNotFoundException exception) {
 67 |      *             exception.printStackTrace();
 68 |      *         }
 69 |      *     }
 70 |      * }}
71 | * 72 | * 73 | * @param sqLiteCredentials 74 | * Credentials of the SQLite Database 75 | * 76 | * @throws DatabaseDriverNotFoundException 77 | *
    78 | *
  • If the SQLite driver was not found.
  • 79 | *
80 | * 81 | * @return A datasource with the SQLite connection. 82 | */ 83 | public static DataSource createSQLiteDataSource(@NotNull SQLiteCredentials sqLiteCredentials) throws DatabaseDriverNotFoundException { 84 | return new SQLite(sqLiteCredentials); 85 | } 86 | 87 | /** 88 | * Create a DataSource with MySQL Url. 89 | * 90 | *

Example Usage 91 | *
 92 |      *     {@code
 93 |      * public class Application {
 94 |      *     public static void main(String[] args) {
 95 |      *         try {
 96 |      *             DataSource dataSource = DataSourceFactory.createMySQLDataSource(
 97 |      *                      MySQLCredentials.of(address, port, database, username, password)
 98 |      *             );
 99 |      *
100 |      *             // Do something with the dataSource (...)
101 |      *         } catch (DatabaseConnectionException exception) {
102 |      *             System.out.println("DatabaseConnection Error: " + exception.getMessage();
103 |      *         } catch (DriverNotFoundException exception) {
104 |      *             System.out.println("DriverNotFound Error: " + exception.getMessage();
105 |      *         }
106 |      *     }
107 |      * }}
108 | * 109 | * @param mySQLCredentials 110 | * Credentials of the MySQL Database. 111 | * 112 | * @throws DatabaseConnectionException 113 | *
    114 | *
  • If the credentials is wrong.
  • 115 | *
116 | * 117 | * @throws DatabaseDriverNotFoundException 118 | *
    119 | *
  • If the MySQL driver was not found.
  • 120 | *
121 | * 122 | * @return A datasource with MySQL connection. 123 | * 124 | * */ 125 | public static DataSource createMySQLDataSource(@NotNull MySQLCredentials mySQLCredentials) throws DatabaseConnectionException, DatabaseDriverNotFoundException { 126 | return new MySQL(mySQLCredentials); 127 | } 128 | 129 | /** 130 | * Create a DataSource with PostgreSQL Url. 131 | * 132 | *

Example Usage 133 | *
134 |      *     {@code
135 |      * public class Application {
136 |      *     public static void main(String[] args) {
137 |      *         try {
138 |      *             DataSource dataSource = DataSourceFactory.createPostgreSQLDataSource(
139 |      *                      PostgreSQLCredentials.of(address, port, database, username, password)
140 |      *             );
141 |      *
142 |      *             // Do something with the dataSource (...)
143 |      *         } catch (DatabaseConnectionException exception) {
144 |      *             System.out.println("DatabaseConnection Error: " + exception.getMessage();
145 |      *         } catch (DriverNotFoundException exception) {
146 |      *             System.out.println("DriverNotFound Error: " + exception.getMessage();
147 |      *         }
148 |      *     }
149 |      * }}
150 | * 151 | * @param postgreSQLCredentials 152 | * Credentials of the PostgreSQL Database. 153 | * 154 | * @throws DatabaseConnectionException 155 | *
    156 | *
  • If the credentials is wrong.
  • 157 | *
158 | * 159 | * @throws DatabaseDriverNotFoundException 160 | *
    161 | *
  • If the PostgreSQL driver was not found.
  • 162 | *
163 | * 164 | * @return A datasource with PostgreSQL connection. 165 | * 166 | * */ 167 | public static DataSource createPostgreSQLDataSource(@NotNull PostgreSQLCredentials postgreSQLCredentials) throws DatabaseDriverNotFoundException, DatabaseConnectionException { 168 | return new PostgreSQL(postgreSQLCredentials); 169 | } 170 | 171 | /** 172 | * Create a DataSource with MariaDB Url. 173 | * 174 | *

Example Usage 175 | *
176 |      *     {@code
177 |      * public class Application {
178 |      *     public static void main(String[] args) {
179 |      *         try {
180 |      *             DataSource dataSource = DataSourceFactory.createMariaDBDataSource(
181 |      *                      MariaDBCredentials.of(address, port, database, username, password)
182 |      *             );
183 |      *
184 |      *             // Do something with the dataSource (...)
185 |      *         } catch (DatabaseConnectionException exception) {
186 |      *             System.out.println("DatabaseConnection Error: " + exception.getMessage();
187 |      *         } catch (DriverNotFoundException exception) {
188 |      *             System.out.println("DriverNotFound Error: " + exception.getMessage();
189 |      *         }
190 |      *     }
191 |      * }}
192 | * 193 | * @param mariaDBCredentials 194 | * Credentials of the MariaDB Database. 195 | * 196 | * @throws DatabaseConnectionException 197 | *
    198 | *
  • If the credentials is wrong.
  • 199 | *
200 | * 201 | * @throws DatabaseDriverNotFoundException 202 | *
    203 | *
  • If the MariaDB driver was not found.
  • 204 | *
205 | * 206 | * @return A datasource with MariaDB connection. 207 | * 208 | * */ 209 | public static DataSource createMariaDBDataSource(@NotNull MariaDBCredentials mariaDBCredentials) throws DatabaseDriverNotFoundException, DatabaseConnectionException { 210 | return new MariaDB(mariaDBCredentials); 211 | } 212 | 213 | } 214 | -------------------------------------------------------------------------------- /sql/src/main/java/com/github/mattnicee7/mattlib/datasource/impl/MariaDB.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.datasource.impl; 26 | 27 | import com.github.mattnicee7.mattlib.credentials.impl.MariaDBCredentials; 28 | import com.github.mattnicee7.mattlib.datasource.DataSource; 29 | import com.github.mattnicee7.mattlib.exception.DatabaseConnectionException; 30 | import com.github.mattnicee7.mattlib.exception.DatabaseDriverNotFoundException; 31 | import org.jetbrains.annotations.NotNull; 32 | 33 | import java.sql.Connection; 34 | import java.sql.DriverManager; 35 | import java.sql.SQLException; 36 | 37 | public class MariaDB implements DataSource { 38 | 39 | private final Connection connection; 40 | 41 | public MariaDB(@NotNull MariaDBCredentials mariaDBCredentials) throws DatabaseDriverNotFoundException, DatabaseConnectionException { 42 | try { 43 | Class.forName("org.mariadb.jdbc.Driver"); 44 | 45 | this.connection = DriverManager.getConnection( 46 | mariaDBCredentials.getUrl(), 47 | mariaDBCredentials.getUsername(), 48 | mariaDBCredentials.getPassword()); 49 | } catch (ClassNotFoundException exception) { 50 | throw new DatabaseDriverNotFoundException("MariaDB Driver not found."); 51 | } catch (SQLException exception) { 52 | throw new DatabaseConnectionException("Failed to connect with MariaDB."); 53 | } 54 | } 55 | 56 | @Override 57 | public Connection getConnection() throws SQLException { 58 | return connection; 59 | } 60 | 61 | @Override 62 | public void closeConnection() { 63 | try { 64 | if (!connection.isClosed()) 65 | connection.close(); 66 | } catch (SQLException exception) { 67 | exception.printStackTrace(); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /sql/src/main/java/com/github/mattnicee7/mattlib/datasource/impl/MySQL.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.datasource.impl; 26 | 27 | import com.github.mattnicee7.mattlib.credentials.impl.MySQLCredentials; 28 | import com.github.mattnicee7.mattlib.datasource.DataSource; 29 | import com.github.mattnicee7.mattlib.exception.DatabaseConnectionException; 30 | import com.github.mattnicee7.mattlib.exception.DatabaseDriverNotFoundException; 31 | import org.jetbrains.annotations.NotNull; 32 | 33 | import java.sql.Connection; 34 | import java.sql.DriverManager; 35 | import java.sql.SQLException; 36 | 37 | /** 38 | * Class responsible for storing the connection with MySQL. You can close the connection whenever you want. 39 | */ 40 | public class MySQL implements DataSource { 41 | 42 | private final Connection connection; 43 | 44 | public MySQL(@NotNull MySQLCredentials mySQLCredentials) throws DatabaseConnectionException, DatabaseDriverNotFoundException { 45 | try { 46 | Class.forName("com.mysql.jdbc.Driver"); 47 | 48 | this.connection = DriverManager.getConnection( 49 | mySQLCredentials.getUrl(), 50 | mySQLCredentials.getUsername(), 51 | mySQLCredentials.getPassword() 52 | ); 53 | 54 | } catch (ClassNotFoundException exception) { 55 | throw new DatabaseDriverNotFoundException("MySQL Driver not found."); 56 | } catch (SQLException exception) { 57 | throw new DatabaseConnectionException("Failed to connect with MySQL."); 58 | } 59 | } 60 | 61 | @Override 62 | public Connection getConnection() { 63 | return connection; 64 | } 65 | 66 | @Override 67 | public void closeConnection() { 68 | try { 69 | if (!connection.isClosed()) 70 | connection.close(); 71 | } catch (SQLException exception) { 72 | exception.printStackTrace(); 73 | } 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /sql/src/main/java/com/github/mattnicee7/mattlib/datasource/impl/PostgreSQL.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.datasource.impl; 26 | 27 | import com.github.mattnicee7.mattlib.credentials.impl.PostgreSQLCredentials; 28 | import com.github.mattnicee7.mattlib.datasource.DataSource; 29 | import com.github.mattnicee7.mattlib.exception.DatabaseConnectionException; 30 | import com.github.mattnicee7.mattlib.exception.DatabaseDriverNotFoundException; 31 | import org.jetbrains.annotations.NotNull; 32 | 33 | import java.sql.Connection; 34 | import java.sql.DriverManager; 35 | import java.sql.SQLException; 36 | 37 | public class PostgreSQL implements DataSource { 38 | 39 | private final Connection connection; 40 | 41 | public PostgreSQL(@NotNull PostgreSQLCredentials postgreSQLCredentials) throws DatabaseDriverNotFoundException, DatabaseConnectionException { 42 | try { 43 | Class.forName("org.postgresql.Driver"); 44 | 45 | this.connection = DriverManager.getConnection( 46 | postgreSQLCredentials.getUrl(), 47 | postgreSQLCredentials.getUsername(), 48 | postgreSQLCredentials.getPassword() 49 | ); 50 | 51 | } catch (ClassNotFoundException exception) { 52 | throw new DatabaseDriverNotFoundException("PostgreSQL Driver not found."); 53 | } catch (SQLException exception) { 54 | throw new DatabaseConnectionException("Failed to connect with PostgreSQL."); 55 | } 56 | } 57 | 58 | @Override 59 | public Connection getConnection() { 60 | return connection; 61 | } 62 | 63 | @Override 64 | public void closeConnection() { 65 | try { 66 | if (!connection.isClosed()) 67 | connection.close(); 68 | } catch (SQLException exception) { 69 | exception.printStackTrace(); 70 | } 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /sql/src/main/java/com/github/mattnicee7/mattlib/datasource/impl/SQLite.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.datasource.impl; 26 | 27 | import com.github.mattnicee7.mattlib.credentials.impl.SQLiteCredentials; 28 | import com.github.mattnicee7.mattlib.datasource.DataSource; 29 | import com.github.mattnicee7.mattlib.exception.DatabaseDriverNotFoundException; 30 | import org.jetbrains.annotations.NotNull; 31 | 32 | import java.sql.Connection; 33 | import java.sql.DriverManager; 34 | import java.sql.SQLException; 35 | 36 | /** 37 | * Class responsible for storing the connection with SQLite. 38 | */ 39 | public class SQLite implements DataSource { 40 | 41 | private final String url; 42 | 43 | public SQLite(@NotNull SQLiteCredentials sqLiteCredentials) throws DatabaseDriverNotFoundException { 44 | try { 45 | this.url = sqLiteCredentials.getUrl(); 46 | 47 | Class.forName("org.sqlite.JDBC"); 48 | } catch (ClassNotFoundException exception) { 49 | throw new DatabaseDriverNotFoundException("SQLite driver not found."); 50 | } 51 | 52 | } 53 | 54 | @Override 55 | public Connection getConnection() throws SQLException { 56 | return DriverManager.getConnection(url); 57 | } 58 | 59 | @Override 60 | public void closeConnection() { 61 | // Do nothing because SQLite doesn't need to be closed. 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /sql/src/main/java/com/github/mattnicee7/mattlib/exception/DatabaseConnectionException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.exception; 26 | 27 | import java.sql.SQLException; 28 | 29 | /** 30 | * Custom exception used when something in the attempt to connect to the database goes wrong, such as wrong credentials, etc. 31 | */ 32 | public class DatabaseConnectionException extends SQLException { 33 | 34 | public DatabaseConnectionException(String message) { 35 | super(message); 36 | } 37 | 38 | public DatabaseConnectionException(String message, Throwable cause) { 39 | super(message, cause); 40 | } 41 | 42 | public DatabaseConnectionException(Throwable cause) { 43 | super(cause); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /sql/src/main/java/com/github/mattnicee7/mattlib/exception/DatabaseDriverNotFoundException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.exception; 26 | 27 | import java.sql.SQLException; 28 | 29 | /** 30 | * Custom exception used when some database driver is not found. Probably an error in your project 31 | */ 32 | public class DatabaseDriverNotFoundException extends SQLException { 33 | 34 | public DatabaseDriverNotFoundException(String message) { 35 | super(message); 36 | } 37 | 38 | public DatabaseDriverNotFoundException(String message, Throwable cause) { 39 | super(message, cause); 40 | } 41 | 42 | public DatabaseDriverNotFoundException(Throwable cause) { 43 | super(cause); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /sql/src/main/java/com/github/mattnicee7/mattlib/util/PreparedStatementBuilder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of MattLib, licensed under the MIT License. 3 | * 4 | * Copyright (c) mattnicee7 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | package com.github.mattnicee7.mattlib.util; 26 | 27 | import lombok.val; 28 | import org.jetbrains.annotations.NotNull; 29 | 30 | import java.sql.Connection; 31 | import java.sql.PreparedStatement; 32 | import java.sql.SQLException; 33 | import java.util.HashMap; 34 | import java.util.Map; 35 | 36 | /** 37 | * The PreparedStatementBuilder class is a utility class that allows you to build a prepared statement in steps 38 | * Credits: chicoferreira, thanks so much chico. 39 | */ 40 | public class PreparedStatementBuilder { 41 | 42 | private final String query; 43 | private final Map parameters; 44 | 45 | public PreparedStatementBuilder(@NotNull String query) { 46 | this.query = query; 47 | this.parameters = new HashMap<>(); 48 | } 49 | 50 | public static PreparedStatementBuilder of(@NotNull String query) { 51 | return new PreparedStatementBuilder(query); 52 | } 53 | 54 | /** 55 | * This function adds a parameter to the prepared statement 56 | * 57 | * @param index The index of the parameter in the SQL statement. 58 | * @param value The value to bind to the parameter. 59 | * @return Nothing. 60 | */ 61 | public PreparedStatementBuilder parameter(int index, @NotNull Object value) { 62 | this.parameters.put(index, value); 63 | return this; 64 | } 65 | 66 | /** 67 | * Build a prepared statement from the query and parameters 68 | * 69 | * @param connection The connection to the database. 70 | * @return PreparedStatement 71 | */ 72 | public PreparedStatement build(@NotNull Connection connection) throws SQLException { 73 | val preparedStatement = connection.prepareStatement(this.query); 74 | 75 | for (Map.Entry entry : parameters.entrySet()) 76 | preparedStatement.setObject(entry.getKey(), entry.getValue()); 77 | 78 | return preparedStatement; 79 | } 80 | 81 | } 82 | --------------------------------------------------------------------------------