Merge pull request #1 from TouchInstinct/feature/init
Initialize project
This commit is contained in:
commit
3ddf8a9c5e
|
|
@ -0,0 +1,44 @@
|
|||
# Generated files
|
||||
bin/
|
||||
gen/
|
||||
out/
|
||||
|
||||
# Gradle files
|
||||
.gradle/
|
||||
gradle/
|
||||
build/
|
||||
build/*
|
||||
|
||||
# Intellij
|
||||
*.iml
|
||||
.idea
|
||||
|
||||
# Compiled class file
|
||||
*.class
|
||||
|
||||
# Log file
|
||||
*.log
|
||||
|
||||
# BlueJ files
|
||||
*.ctxt
|
||||
|
||||
# Mobile Tools for Java (J2ME)
|
||||
.mtj.tmp/
|
||||
|
||||
# Package Files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
*.zip
|
||||
*.tar.gz
|
||||
*.rar
|
||||
|
||||
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
|
||||
hs_err_pid*
|
||||
|
||||
elk/server/elasticsearch/data
|
||||
|
||||
server/deploy/deploy_playbook\.retry
|
||||
jobs/deploy/deploy_playbook\.retry
|
||||
|
||||
application-local.properties
|
||||
|
|
@ -0,0 +1,63 @@
|
|||
buildscript {
|
||||
|
||||
ext {
|
||||
kotlinVersion = '1.3.71'
|
||||
springBootVersion = '2.2.5.RELEASE'
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven { url "https://plugins.gradle.org/m2/" }
|
||||
}
|
||||
|
||||
dependencies {
|
||||
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
|
||||
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlinVersion}")
|
||||
classpath("org.jetbrains.kotlin:kotlin-allopen:${kotlinVersion}")
|
||||
classpath("org.jetbrains.kotlin:kotlin-noarg:${kotlinVersion}")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
plugins {
|
||||
id 'org.springframework.boot' version '2.2.5.RELEASE' apply false
|
||||
}
|
||||
|
||||
allprojects {
|
||||
group 'ru.touchin'
|
||||
}
|
||||
|
||||
subprojects {
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven { url "https://plugins.gradle.org/m2/" }
|
||||
}
|
||||
|
||||
apply plugin: 'kotlin'
|
||||
|
||||
sourceCompatibility = 1.8
|
||||
|
||||
compileKotlin {
|
||||
kotlinOptions {
|
||||
freeCompilerArgs = ["-Xjsr305=strict"]
|
||||
jvmTarget = "1.8"
|
||||
}
|
||||
}
|
||||
|
||||
compileTestKotlin {
|
||||
kotlinOptions {
|
||||
freeCompilerArgs = ["-Xjsr305=strict"]
|
||||
jvmTarget = "1.8"
|
||||
}
|
||||
}
|
||||
|
||||
apply plugin: 'io.spring.dependency-management'
|
||||
|
||||
dependencyManagement {
|
||||
imports {
|
||||
mavenBom("org.springframework.boot:spring-boot-dependencies:${springBootVersion}") {
|
||||
bomProperty("kotlin.version", "${kotlinVersion}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
kotlin.code.style=official
|
||||
Binary file not shown.
|
|
@ -0,0 +1,5 @@
|
|||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-5.2.1-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
|
|
@ -0,0 +1,172 @@
|
|||
#!/usr/bin/env sh
|
||||
|
||||
##############################################################################
|
||||
##
|
||||
## Gradle start up script for UN*X
|
||||
##
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
# Resolve links: $0 may be a link
|
||||
PRG="$0"
|
||||
# Need this for relative symlinks.
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG=`dirname "$PRG"`"/$link"
|
||||
fi
|
||||
done
|
||||
SAVED="`pwd`"
|
||||
cd "`dirname \"$PRG\"`/" >/dev/null
|
||||
APP_HOME="`pwd -P`"
|
||||
cd "$SAVED" >/dev/null
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=`basename "$0"`
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD="maximum"
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
}
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
}
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "`uname`" in
|
||||
CYGWIN* )
|
||||
cygwin=true
|
||||
;;
|
||||
Darwin* )
|
||||
darwin=true
|
||||
;;
|
||||
MINGW* )
|
||||
msys=true
|
||||
;;
|
||||
NONSTOP* )
|
||||
nonstop=true
|
||||
;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD="java"
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
|
||||
MAX_FD_LIMIT=`ulimit -H -n`
|
||||
if [ $? -eq 0 ] ; then
|
||||
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
|
||||
MAX_FD="$MAX_FD_LIMIT"
|
||||
fi
|
||||
ulimit -n $MAX_FD
|
||||
if [ $? -ne 0 ] ; then
|
||||
warn "Could not set maximum file descriptor limit: $MAX_FD"
|
||||
fi
|
||||
else
|
||||
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
|
||||
fi
|
||||
fi
|
||||
|
||||
# For Darwin, add options to specify how the application appears in the dock
|
||||
if $darwin; then
|
||||
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
|
||||
fi
|
||||
|
||||
# For Cygwin, switch paths to Windows format before running java
|
||||
if $cygwin ; then
|
||||
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
|
||||
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
|
||||
JAVACMD=`cygpath --unix "$JAVACMD"`
|
||||
|
||||
# We build the pattern for arguments to be converted via cygpath
|
||||
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
|
||||
SEP=""
|
||||
for dir in $ROOTDIRSRAW ; do
|
||||
ROOTDIRS="$ROOTDIRS$SEP$dir"
|
||||
SEP="|"
|
||||
done
|
||||
OURCYGPATTERN="(^($ROOTDIRS))"
|
||||
# Add a user-defined pattern to the cygpath arguments
|
||||
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
|
||||
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
|
||||
fi
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
i=0
|
||||
for arg in "$@" ; do
|
||||
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
|
||||
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
|
||||
|
||||
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
|
||||
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
|
||||
else
|
||||
eval `echo args$i`="\"$arg\""
|
||||
fi
|
||||
i=$((i+1))
|
||||
done
|
||||
case $i in
|
||||
(0) set -- ;;
|
||||
(1) set -- "$args0" ;;
|
||||
(2) set -- "$args0" "$args1" ;;
|
||||
(3) set -- "$args0" "$args1" "$args2" ;;
|
||||
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
|
||||
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
|
||||
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
|
||||
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
|
||||
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
|
||||
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
|
||||
esac
|
||||
fi
|
||||
|
||||
# Escape application args
|
||||
save () {
|
||||
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
|
||||
echo " "
|
||||
}
|
||||
APP_ARGS=$(save "$@")
|
||||
|
||||
# Collect all arguments for the java command, following the shell quoting and substitution rules
|
||||
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
|
||||
|
||||
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
|
||||
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
|
||||
cd "$(dirname "$0")"
|
||||
fi
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
|
|
@ -0,0 +1,84 @@
|
|||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto init
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto init
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:init
|
||||
@rem Get command-line arguments, handling Windows variants
|
||||
|
||||
if not "%OS%" == "Windows_NT" goto win9xME_args
|
||||
|
||||
:win9xME_args
|
||||
@rem Slurp the command line arguments.
|
||||
set CMD_LINE_ARGS=
|
||||
set _SKIP=2
|
||||
|
||||
:win9xME_args_slurp
|
||||
if "x%~1" == "x" goto execute
|
||||
|
||||
set CMD_LINE_ARGS=%*
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
rootProject.name = System.getProperty("rootProjectName")
|
||||
?: 'Backend-common'
|
||||
|
||||
include 'utils'
|
||||
include 'test-utils'
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
plugins {
|
||||
id 'kotlin'
|
||||
id 'kotlin-spring'
|
||||
id 'kotlin-jpa'
|
||||
id 'eclipse'
|
||||
id 'org.springframework.boot' apply false
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven { url "https://plugins.gradle.org/m2/" }
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation "org.jetbrains.kotlin:kotlin-stdlib"
|
||||
compileOnly "org.springframework.data:spring-data-commons"
|
||||
compileOnly "org.junit.jupiter:junit-jupiter"
|
||||
compileOnly "org.mockito:mockito-core"
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
package ru.touchinstinct.utils.test.mockito
|
||||
|
||||
import org.junit.jupiter.api.fail
|
||||
|
||||
object AssertUtils {
|
||||
|
||||
fun <T> assertContains(container: Iterable<T>, element: T) {
|
||||
if (element !in container) {
|
||||
fail("Not contains: \nElement: $element \nContainer: $container")
|
||||
}
|
||||
}
|
||||
|
||||
fun <T> assertContains(container: Iterable<T>, predicate: (T) -> Boolean) {
|
||||
if (container.none(predicate)) {
|
||||
fail("Not contains: \nContainer: $container")
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
package ru.touchinstinct.utils.test.mockito
|
||||
|
||||
import org.mockito.ArgumentMatchers
|
||||
import org.mockito.ArgumentMatchers.booleanThat
|
||||
import org.mockito.ArgumentMatchers.longThat
|
||||
import org.mockito.Mockito
|
||||
|
||||
object MockitoUtils {
|
||||
|
||||
fun <T> anyx(matcher: ((T) -> Boolean)? = null): T {
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
return if (matcher == null) {
|
||||
ArgumentMatchers.any() ?: (null as T)
|
||||
} else {
|
||||
Mockito.argThat(matcher) ?: (null as T)
|
||||
}
|
||||
}
|
||||
|
||||
fun <T> anyx(sample: T): T = anyx { it == sample }
|
||||
|
||||
fun trueBoolean(): Boolean = booleanThat { it }
|
||||
|
||||
fun anyLong(matcher: ((Long) -> Boolean)? = { true }): Long = longThat(matcher)
|
||||
|
||||
fun <T> anyType(type: Class<T>): T = Mockito.any<T>(type)
|
||||
|
||||
inline fun <reified T> mock(clazz: Class<T> = T::class.java): T = Mockito.mock(clazz)
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
package ru.touchinstinct.utils.test.mockito
|
||||
|
||||
import java.io.StringWriter
|
||||
import javax.xml.bind.JAXBContext
|
||||
|
||||
fun <T : Any> transformToXmlString(obj: T): String = StringWriter().let { stringWriter ->
|
||||
JAXBContext.newInstance(obj::class.java).createMarshaller().marshal(obj, stringWriter)
|
||||
stringWriter.toString()
|
||||
}
|
||||
|
|
@ -0,0 +1,144 @@
|
|||
package ru.touchinstinct.utils.test.spring.data
|
||||
|
||||
import org.springframework.data.repository.CrudRepository
|
||||
import ru.touchinstinct.utils.test.mockito.MockitoUtils.anyx
|
||||
import ru.touchinstinct.utils.test.mockito.MockitoUtils.mock
|
||||
import java.lang.reflect.Field
|
||||
import java.util.Optional
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.ThreadLocalRandom
|
||||
import kotlin.math.absoluteValue
|
||||
import org.mockito.Mockito.`when` as on
|
||||
|
||||
/**
|
||||
* This class is used to set up mock of repository
|
||||
**/
|
||||
class MockRepository<R : CrudRepository<T, ID>, T : Any, ID>(
|
||||
val mock: R, // repository mock
|
||||
private val entities: MutableList<T> = ArrayList(),
|
||||
private val idExtractor: ((T) -> ID?)? = null
|
||||
) {
|
||||
|
||||
companion object {
|
||||
@Deprecated("idExtractor is no more required", ReplaceWith("MockRepository.create()"))
|
||||
inline fun <reified R : CrudRepository<T, ID>, reified T : Any, reified ID> mockRepository(
|
||||
noinline idExtractor: (T) -> ID?
|
||||
): R = MockRepository.create()
|
||||
|
||||
@Deprecated("idExtractor is no more required", ReplaceWith("MockRepository.create(settings)"))
|
||||
inline fun <reified R : CrudRepository<T, ID>, reified T : Any, reified ID> mockRepository(
|
||||
noinline idExtractor: (T) -> ID?,
|
||||
noinline settings: (R, MutableList<T>) -> Unit
|
||||
): R = MockRepository.create(settings)
|
||||
|
||||
inline fun <reified R : CrudRepository<T, ID>, reified T : Any, reified ID> create(
|
||||
noinline settings: (R, MutableList<T>) -> Unit
|
||||
): R {
|
||||
val entities = ArrayList<T>()
|
||||
|
||||
return MockRepository(mock<R>(), entities).mock
|
||||
.also { settings(it, entities) }
|
||||
}
|
||||
|
||||
inline fun <reified R : CrudRepository<T, ID>, reified T : Any, reified ID> create(): R {
|
||||
val entities = ArrayList<T>()
|
||||
|
||||
return MockRepository(mock<R>(), entities).mock
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
init {
|
||||
init()
|
||||
}
|
||||
|
||||
private fun init() {
|
||||
on(mock.findAll()).thenAnswer {
|
||||
entities
|
||||
}
|
||||
|
||||
on(mock.save(anyx<T>())).thenAnswer { it ->
|
||||
save(it.getArgument(0))
|
||||
}
|
||||
|
||||
on(mock.saveAll(anyx<List<T>>())).thenAnswer { it ->
|
||||
saveAll(it.getArgument(0))
|
||||
}
|
||||
|
||||
// 'findById' method does not check if id is unique.
|
||||
on(mock.findById(anyx())).thenAnswer { it ->
|
||||
findById(it.getArgument(0))
|
||||
}
|
||||
|
||||
// 'findById' method does not check if id is unique.
|
||||
on(mock.deleteAll()).thenAnswer { reset() }
|
||||
|
||||
on(mock.delete(anyx())).thenAnswer { delete(it.getArgument(0)) }
|
||||
|
||||
}
|
||||
|
||||
private fun findById(id: ID): Optional<T> {
|
||||
|
||||
return Optional.ofNullable(entities.find { id(it) == id })
|
||||
}
|
||||
|
||||
private fun save(argument: T): T {
|
||||
val id = id(argument) ?: trySetId(argument)
|
||||
|
||||
entities.replaceAll { entity -> if (id(entity) == id) argument else entity }
|
||||
|
||||
if (entities.find { entity -> id(entity) == id } == null) {
|
||||
entities.add(argument)
|
||||
}
|
||||
|
||||
return argument
|
||||
}
|
||||
|
||||
private fun saveAll(objects: List<T>): List<T> {
|
||||
|
||||
return objects.map { save(it) }
|
||||
}
|
||||
|
||||
private fun delete(any: T) = entities.remove(any)
|
||||
|
||||
fun reset() {
|
||||
entities.clear()
|
||||
}
|
||||
|
||||
private fun idField(entity: T): Field {
|
||||
val javaClass = (entity as Any).javaClass
|
||||
|
||||
val fields = javaClass.declaredFields.toSet() + javaClass.superclass.declaredFields.toSet()
|
||||
|
||||
val idFieldOrNull = fields
|
||||
.firstOrNull {
|
||||
it.annotations.any { annotation -> annotation.annotationClass.simpleName == "Id" }
|
||||
}
|
||||
?.also { it.isAccessible = true }
|
||||
|
||||
return idFieldOrNull
|
||||
?: throw IllegalStateException("Type ${javaClass.canonicalName} has no field with @Id annotation.\n" +
|
||||
"Fields: ${fields.map { it.name }}")
|
||||
}
|
||||
|
||||
private fun id(entity: T): ID {
|
||||
val idField = idField(entity)
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
return idField.get(entity) as ID
|
||||
}
|
||||
|
||||
private fun trySetId(entity: T): ID = idField(entity).let { idField ->
|
||||
val id = when (idField.type) {
|
||||
java.lang.String::class.java, String::class.java -> UUID.randomUUID().toString()
|
||||
java.lang.Long::class.java, Long::class.java -> ThreadLocalRandom.current().nextLong().absoluteValue
|
||||
else -> throw IllegalAccessException("Could not generate id of type ${idField.type.canonicalName}")
|
||||
}
|
||||
|
||||
idField.set(entity, id)
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
id as ID
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
plugins {
|
||||
id 'kotlin'
|
||||
id 'eclipse'
|
||||
id 'io.spring.dependency-management'
|
||||
id 'org.springframework.boot' apply false
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven { url "https://plugins.gradle.org/m2/" }
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation "org.jetbrains.kotlin:kotlin-stdlib"
|
||||
compileOnly "org.springframework.data:spring-data-commons"
|
||||
compileOnly "io.projectreactor.kotlin:reactor-kotlin-extensions"
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
package ru.touchinstinct.utils
|
||||
|
||||
import java.math.BigDecimal
|
||||
|
||||
inline fun <T> Iterable<T>.sumBy(selector: (T) -> BigDecimal) =
|
||||
fold(BigDecimal.ZERO) { accumulator, element -> accumulator + selector(element) }
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
package ru.touchinstinct.utils
|
||||
|
||||
import org.springframework.core.io.ClassPathResource
|
||||
import java.io.InputStream
|
||||
import java.math.BigDecimal
|
||||
import java.util.Optional
|
||||
|
||||
fun getInputStreamOfResourceFile(fileName: String): InputStream = ClassPathResource(fileName).inputStream
|
||||
|
||||
fun getResourceAsString(filename: String): String = getInputStreamOfResourceFile(filename)
|
||||
.use { String(it.readBytes()) }
|
||||
|
||||
fun <T> Optional<T>.getOrNull(): T? = takeIf { it.isPresent }?.get()
|
||||
|
||||
fun BigDecimal.equalTo(number: BigDecimal): Boolean = compareTo(number) == 0
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
package ru.touchinstinct.utils
|
||||
|
||||
const val SKIP_LOCKED_PARAMETER = "javax.persistence.lock.timeout"
|
||||
/**
|
||||
* Const value which is used for 'SKIP LOCKED' in 'SELECT ... FOR UPDATE' query
|
||||
*/
|
||||
const val SKIP_LOCKED_VALUE = "-2"
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
package ru.touchinstinct.utils
|
||||
|
||||
import java.time.Duration
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalDateTime
|
||||
import java.time.ZoneId
|
||||
import java.time.ZonedDateTime
|
||||
import java.util.TimeZone
|
||||
|
||||
val MOSCOW_ZONE_ID: ZoneId = TimeZone.getTimeZone("Europe/Moscow").toZoneId()
|
||||
|
||||
fun ZonedDateTime.isExpired(duration: Duration) = this.isExpired(ZonedDateTime.now().minus(duration))
|
||||
|
||||
fun ZonedDateTime.isExpired(currentDate: ZonedDateTime = ZonedDateTime.now()) = this.isBefore(currentDate)
|
||||
|
||||
fun ZonedDateTime.isNotExpired(duration: Duration) = !this.isExpired(duration)
|
||||
|
||||
fun ZonedDateTime.isNotExpired(currentDate: ZonedDateTime = ZonedDateTime.now()) = !this.isExpired(currentDate)
|
||||
|
||||
fun ZonedDateTime.equals(arg: ZonedDateTime, maxDiff: Duration) =
|
||||
Duration.between(this, arg) <= maxDiff
|
||||
|
||||
fun LocalDateTime.isExpired(currentDate: LocalDateTime = LocalDateTime.now()) = this.isBefore(currentDate)
|
||||
|
||||
fun LocalDateTime.isExpired(duration: Duration) = this.isBefore(LocalDateTime.now().minus(duration))
|
||||
|
||||
fun dateMin(date1: LocalDate, date2: LocalDate?): LocalDate =
|
||||
if (date2 == null || date2.isAfter(date1)) date1 else date2
|
||||
|
||||
fun LocalDate.toZonedDateTime(): ZonedDateTime = atStartOfDay(MOSCOW_ZONE_ID)
|
||||
|
||||
fun createLocalDate(): LocalDate = LocalDate.now()
|
||||
|
||||
fun createLocalDateAtStartOfYear(): LocalDate = createLocalDate().withDayOfYear(1)
|
||||
|
||||
fun LocalDate.startOfWeek(): LocalDate = this.minusDays(this.dayOfWeek.ordinal.toLong())
|
||||
|
||||
fun LocalDate.endOfWeek(): LocalDate = this.plusWeeks(1L).minusDays(this.dayOfWeek.ordinal.toLong() + 1L)
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
package ru.touchinstinct.utils
|
||||
|
||||
class Empty
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
package ru.touchinstinct.utils
|
||||
|
||||
import reactor.core.publisher.Mono
|
||||
import reactor.core.scheduler.Schedulers
|
||||
|
||||
object ReactorUtils {
|
||||
|
||||
fun <T : Any?> blocking(block: () -> T): Mono<T> =
|
||||
Mono.fromCallable(block).subscribeOn(Schedulers.elastic())
|
||||
|
||||
}
|
||||
|
||||
fun <T : Any?, Y : Any?> Mono<T>.mapElastic(block: (T) -> Y): Mono<Y> =
|
||||
flatMap { argument ->
|
||||
Mono.fromCallable { block(argument) }
|
||||
.subscribeOn(Schedulers.elastic())
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
package ru.touchinstinct.utils
|
||||
|
||||
import org.springframework.data.repository.CrudRepository
|
||||
|
||||
fun <T : Any, ID> CrudRepository<T, ID>.update(entity: T, updater: T.() -> Unit): T {
|
||||
|
||||
return save(entity.apply(updater))
|
||||
}
|
||||
|
||||
fun <T : Any, ID> CrudRepository<T, ID>.upsert(entity: T, updater: (T) -> Unit): T {
|
||||
|
||||
return save(entity.apply(updater))
|
||||
}
|
||||
|
||||
fun <T : Any, ID> T.upsertInto(repository: CrudRepository<T, ID>, updater: (T) -> Unit): T {
|
||||
|
||||
return repository.save(also(updater))
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
package ru.touchinstinct.utils
|
||||
|
||||
import org.w3c.dom.Node
|
||||
import javax.xml.bind.JAXBContext
|
||||
|
||||
inline fun <reified T> unmarshalRequestFrom(xml: Node): T = unmarshalRequestFrom(xml, T::class.java)
|
||||
|
||||
fun <T> unmarshalRequestFrom(xml: Node, clazz: Class<T>): T {
|
||||
val jaxbUnmarshaller = JAXBContext.newInstance(clazz).createUnmarshaller()
|
||||
|
||||
return jaxbUnmarshaller.unmarshal(xml, clazz).value
|
||||
}
|
||||
|
|
@ -0,0 +1,128 @@
|
|||
package ru.touchinstinct.utils
|
||||
|
||||
import org.jetbrains.annotations.Contract
|
||||
|
||||
private val TRANSLITERATION_TABLE: Map<Char, String> = mapOf(
|
||||
' ' to " ",
|
||||
'а' to "a",
|
||||
'б' to "b",
|
||||
'в' to "v",
|
||||
'г' to "g",
|
||||
'д' to "d",
|
||||
'е' to "e",
|
||||
'ё' to "e",
|
||||
'ж' to "zh",
|
||||
'з' to "z",
|
||||
'и' to "i",
|
||||
'й' to "y",
|
||||
'к' to "k",
|
||||
'л' to "l",
|
||||
'м' to "m",
|
||||
'н' to "n",
|
||||
'о' to "o",
|
||||
'п' to "p",
|
||||
'р' to "r",
|
||||
'с' to "s",
|
||||
'т' to "t",
|
||||
'у' to "u",
|
||||
'ф' to "f",
|
||||
'х' to "h",
|
||||
'ц' to "ts",
|
||||
'ч' to "ch",
|
||||
'ш' to "sh",
|
||||
'щ' to "sch",
|
||||
'ъ' to "'",
|
||||
'ы' to "i",
|
||||
'ь' to "'",
|
||||
'э' to "e",
|
||||
'ю' to "ju",
|
||||
'я' to "ja",
|
||||
'А' to "A",
|
||||
'Б' to "B",
|
||||
'В' to "V",
|
||||
'Г' to "G",
|
||||
'Д' to "D",
|
||||
'Е' to "E",
|
||||
'Ё' to "E",
|
||||
'Ж' to "Zh",
|
||||
'З' to "Z",
|
||||
'И' to "I",
|
||||
'Й' to "Y",
|
||||
'К' to "K",
|
||||
'Л' to "L",
|
||||
'М' to "M",
|
||||
'Н' to "N",
|
||||
'О' to "O",
|
||||
'П' to "P",
|
||||
'Р' to "R",
|
||||
'С' to "S",
|
||||
'Т' to "T",
|
||||
'У' to "U",
|
||||
'Ф' to "F",
|
||||
'Х' to "H",
|
||||
'Ц' to "Ts",
|
||||
'Ч' to "Ch",
|
||||
'Ш' to "Sh",
|
||||
'Щ' to "Sch",
|
||||
'Ъ' to "'",
|
||||
'Ы' to "I",
|
||||
'Ь' to "'",
|
||||
'Э' to "E",
|
||||
'Ю' to "Ju",
|
||||
'Я' to "Ja"
|
||||
)
|
||||
|
||||
object StringUtils {
|
||||
|
||||
@Contract("hello_world -> helloWorld; HeLlO_WORld -> helloWorld; HELLO_WORLD -> helloWorld", pure = true)
|
||||
fun snakeCaseToCamelCase(string: String): String {
|
||||
var nextUpperCase = false
|
||||
|
||||
return buildString {
|
||||
for (char in string) {
|
||||
when {
|
||||
char == '_' -> {
|
||||
nextUpperCase = true
|
||||
}
|
||||
|
||||
nextUpperCase -> {
|
||||
this.append(char.toUpperCase())
|
||||
nextUpperCase = false
|
||||
}
|
||||
|
||||
!nextUpperCase -> {
|
||||
this.append(char.toLowerCase())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
fun String.removeNonPrintableCharacters(): String {
|
||||
|
||||
return this
|
||||
.transliterateCyrillic()
|
||||
.replace("[\\p{Cntrl}&&[^\r\n\t]]".toRegex(), "")// erases all the ASCII control characters
|
||||
.replace("\\p{C}".toRegex(), "")// removes non-printable characters from Unicode
|
||||
.trim()
|
||||
}
|
||||
|
||||
fun String.transliterateCyrillic(): String {
|
||||
val builder = StringBuilder()
|
||||
|
||||
for (char in this) {
|
||||
if (TRANSLITERATION_TABLE.containsKey(char)) {
|
||||
builder.append(TRANSLITERATION_TABLE[char])
|
||||
} else {
|
||||
builder.append(char)
|
||||
}
|
||||
}
|
||||
|
||||
return builder.toString()
|
||||
}
|
||||
|
||||
fun String?.orNullIfBlank(): String? = this?.takeIf { it.isNotBlank() }
|
||||
|
||||
fun String?.orIfNullOrBlank(altValue: String): String = if (this.isNullOrBlank()) altValue else this
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
package ru.touchinstinct.utils
|
||||
|
||||
import org.w3c.dom.Document
|
||||
import org.w3c.dom.Node
|
||||
import org.w3c.dom.NodeList
|
||||
import java.io.ByteArrayOutputStream
|
||||
import javax.xml.parsers.DocumentBuilderFactory
|
||||
import javax.xml.transform.OutputKeys
|
||||
import javax.xml.transform.Source
|
||||
import javax.xml.transform.Transformer
|
||||
import javax.xml.transform.TransformerFactory
|
||||
import javax.xml.transform.dom.DOMSource
|
||||
import javax.xml.transform.stream.StreamResult
|
||||
|
||||
private val XML_DOCUMENT_BUILDER_FACTORY: DocumentBuilderFactory =
|
||||
DocumentBuilderFactory.newInstance().apply { isNamespaceAware = true }
|
||||
|
||||
private val transformerFactory = TransformerFactory.newInstance()
|
||||
|
||||
fun getXmlMinified(filename: String) = getResourceAsString(filename)
|
||||
.replace(">(\\s+)<".toRegex(), "><")
|
||||
|
||||
fun String.parseXmlDocument(): Document =
|
||||
XML_DOCUMENT_BUILDER_FACTORY.newDocumentBuilder().parse(byteInputStream())
|
||||
|
||||
fun Node.stringify(): String = DOMSource(this).stringify()
|
||||
|
||||
fun Source.stringify(): String {
|
||||
val streamOut = ByteArrayOutputStream()
|
||||
|
||||
getDefaultTransformer().transform(this, StreamResult(streamOut))
|
||||
|
||||
return streamOut.toString(Charsets.UTF_8.name())
|
||||
}
|
||||
|
||||
fun NodeList.get(localName: String): Node? {
|
||||
for (i in 0 until length) {
|
||||
if (item(i).localName == localName) {
|
||||
|
||||
return item(i)
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
private fun getDefaultTransformer(): Transformer =
|
||||
transformerFactory.newTransformer().apply {
|
||||
setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes")
|
||||
setOutputProperty(OutputKeys.INDENT, "yes")
|
||||
}
|
||||
Loading…
Reference in New Issue