add common module

This commit is contained in:
Alexander Buntakov 2021-06-06 19:19:46 +03:00
parent 3ddf8a9c5e
commit 0d038f50ec
36 changed files with 623 additions and 748 deletions

83
.editorconfig Normal file
View File

@ -0,0 +1,83 @@
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
max_line_length = 120
tab_width = 4
ij_continuation_indent_size = 4
ij_smart_tabs = false
[{*.yml, *.yaml}]
indent_size = 2
tab_width = 2
ij_continuation_indent_size = 2
[{*.kts, *.kt}]
ij_kotlin_code_style_defaults = KOTLIN_OFFICIAL
ij_java_use_single_class_imports = true
ij_kotlin_align_in_columns_case_branch = false
ij_kotlin_align_multiline_binary_operation = false
ij_kotlin_align_multiline_extends_list = false
ij_kotlin_align_multiline_method_parentheses = false
ij_kotlin_align_multiline_parameters = true
ij_kotlin_align_multiline_parameters_in_calls = false
ij_kotlin_assignment_wrap = off
ij_kotlin_blank_lines_after_class_header = 1
ij_kotlin_blank_lines_around_block_when_branches = 1
ij_kotlin_call_parameters_wrap = off
ij_kotlin_catch_on_new_line = false
ij_kotlin_class_annotation_wrap = split_into_lines
ij_kotlin_else_on_new_line = false
ij_kotlin_enum_constants_wrap = off
ij_kotlin_extends_list_wrap = off
ij_kotlin_field_annotation_wrap = split_into_lines
ij_kotlin_finally_on_new_line = false
ij_kotlin_if_rparen_on_new_line = false
ij_kotlin_import_nested_classes = false
ij_kotlin_insert_whitespaces_in_simple_one_line_method = true
ij_kotlin_keep_blank_lines_before_right_brace = 2
ij_kotlin_keep_blank_lines_in_code = 2
ij_kotlin_keep_blank_lines_in_declarations = 1
ij_kotlin_keep_first_column_comment = true
ij_kotlin_keep_indents_on_empty_lines = false
ij_kotlin_keep_line_breaks = true
ij_kotlin_lbrace_on_next_line = false
ij_kotlin_line_comment_add_space = false
ij_kotlin_line_comment_at_first_column = true
ij_kotlin_method_annotation_wrap = split_into_lines
ij_kotlin_method_call_chain_wrap = off
ij_kotlin_method_parameters_new_line_after_left_paren = false
ij_kotlin_method_parameters_right_paren_on_new_line = false
ij_kotlin_method_parameters_wrap = off
ij_kotlin_name_count_to_use_star_import = 2147483647
ij_kotlin_name_count_to_use_star_import_for_members = 2147483647
ij_kotlin_parameter_annotation_wrap = off
ij_kotlin_space_after_comma = true
ij_kotlin_space_after_extend_colon = true
ij_kotlin_space_after_type_colon = true
ij_kotlin_space_before_catch_parentheses = true
ij_kotlin_space_before_comma = false
ij_kotlin_space_before_extend_colon = true
ij_kotlin_space_before_for_parentheses = true
ij_kotlin_space_before_if_parentheses = true
ij_kotlin_space_before_lambda_arrow = true
ij_kotlin_space_before_type_colon = false
ij_kotlin_space_before_when_parentheses = true
ij_kotlin_space_before_while_parentheses = true
ij_kotlin_spaces_around_additive_operators = true
ij_kotlin_spaces_around_assignment_operators = true
ij_kotlin_spaces_around_equality_operators = true
ij_kotlin_spaces_around_function_type_arrow = true
ij_kotlin_spaces_around_logical_operators = true
ij_kotlin_spaces_around_multiplicative_operators = true
ij_kotlin_spaces_around_range = false
ij_kotlin_spaces_around_relational_operators = true
ij_kotlin_spaces_around_unary_operator = false
ij_kotlin_spaces_around_when_arrow = true
ij_kotlin_variable_annotation_wrap = off
ij_kotlin_while_on_new_line = false
ij_kotlin_wrap_elvis_expressions = 1
ij_kotlin_wrap_expression_body_functions = 0
ij_kotlin_wrap_first_method_in_call_chain = false

71
.gitignore vendored
View File

@ -1,44 +1,37 @@
# Generated files
bin/
gen/
out/
# Gradle files
.gradle/
gradle/
HELP.md
.gradle
build/
build/*
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
# Intellij
*.iml
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
# Compiled class file
*.class
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
# 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
### VS Code ###
.vscode/

View File

@ -1 +1,30 @@
# Backend-common
# Modules
## Installation via Gradle Composite Build
1. Add this repository as
[git submodule](https://git-scm.com/book/en/v2/Git-Tools-Submodules)
of your project
1. Add to your `settings.gradle.kts` these lines:
```kotlin
includeBuild("Backend-common")
```
1. Use TLK modules as dependencies of your project
```kotlin
dependencies {
implementation("ru.touchin:common")
}
```
## common
Набор утилит, структур данных, исключений без привязки к `spring`
* `ExecutionContext` - класс для хранения/получения данных из текущего потока
* `SecureRandomStringGenerator` - генератор случайной строки по словарю
* `errors.*` - базовые исключения
* `<type>.*Utils` - утилиты для различных типов данных

View File

@ -1,63 +0,0 @@
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}")
}
}
}
}

73
build.gradle.kts Normal file
View File

@ -0,0 +1,73 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import io.spring.gradle.dependencymanagement.dsl.DependencyManagementExtension
plugins {
kotlin("jvm")
id ("org.springframework.boot") apply false
// IntelliJ
idea
// Classes annotated with @Configuration, @Controller, @RestController, @Service or @Repository are automatically opened
// https://kotlinlang.org/docs/reference/compiler-plugins.html#spring-support
kotlin("plugin.spring") apply false
// A Gradle plugin that provides Maven-like dependency management and exclusions
// https://docs.spring.io/dependency-management-plugin/docs/current/reference/html/
id("io.spring.dependency-management")
}
allprojects {
group = "ru.touchin"
version = "2021.1"
repositories {
mavenLocal()
mavenCentral()
}
println("Enabling IDEA plugin in project ${project.name}...")
apply(plugin = "idea")
}
subprojects {
println("Enabling Kotlin JVM plugin in project ${project.name}...")
apply(plugin = "org.jetbrains.kotlin.jvm")
println("Enabling Kotlin Spring plugin in project ${project.name}...")
apply(plugin = "org.jetbrains.kotlin.plugin.spring")
println("Enabling Spring Boot Dependency Management in project ${project.name}...")
apply(plugin = "io.spring.dependency-management")
configure<DependencyManagementExtension> {
imports {
mavenBom(org.springframework.boot.gradle.plugin.SpringBootPlugin.BOM_COORDINATES)
}
dependencies {
dependency("ch.qos.logback:logback-classic:1.2.3")
dependency("ch.qos.logback.contrib:logback-json-classic:0.1.5")
dependency("ch.qos.logback.contrib:logback-jackson:0.1.5")
}
}
dependencies {
// use for @ConstructorBinding
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation ("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
annotationProcessor("org.springframework.boot:spring-boot-configuration-processor")
}
tasks.withType<KotlinCompile> {
java.sourceCompatibility = JavaVersion.VERSION_11
kotlinOptions.jvmTarget = JavaVersion.VERSION_11.toString()
}
tasks.test {
useJUnitPlatform()
}
}

3
common/build.gradle.kts Normal file
View File

@ -0,0 +1,3 @@
plugins {
id("maven-publish")
}

View File

@ -0,0 +1,26 @@
@file:Suppress("unused")
package ru.touchin.common.context
class ExecutionContext<T>(val init: () -> T) {
private val contextDataThreadLocal = ThreadLocal<T>()
private fun set(executionContextData: T) {
contextDataThreadLocal.set(executionContextData)
}
fun reset(): T {
return init().also(::set)
}
fun get(): T? {
return contextDataThreadLocal.get()
}
fun updateContext(updater: (T) -> T): T? {
return (get() ?: init())
.let(updater)
.also(::set)
}
}

View File

@ -0,0 +1,49 @@
@file:Suppress("unused", "MemberVisibilityCanBePrivate")
package ru.touchin.common.date
import java.time.Duration
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.ZonedDateTime
import java.util.*
object DateUtils {
val MOSCOW_ZONE_ID: ZoneId = TimeZone.getTimeZone("Europe/Moscow").toZoneId()
fun ZonedDateTime.isExpired(
currentDate: ZonedDateTime = ZonedDateTime.now()
) = isBefore(currentDate)
fun ZonedDateTime.isNotExpired(
currentDate: ZonedDateTime = ZonedDateTime.now()
) = !isExpired(currentDate)
fun ZonedDateTime.isExpired(duration: Duration) = isExpired(ZonedDateTime.now().minus(duration))
fun ZonedDateTime.isNotExpired(duration: Duration) = !isExpired(duration)
fun ZonedDateTime.equals(arg: ZonedDateTime, maxDiff: Duration) =
Duration.between(this, arg) <= maxDiff
fun LocalDateTime.isExpired(currentDate: LocalDateTime = LocalDateTime.now()) = isBefore(currentDate)
fun LocalDateTime.isExpired(duration: Duration) = isBefore(LocalDateTime.now().minus(duration))
fun dateMin(date1: LocalDate, date2: LocalDate?): LocalDate =
if (date2 == null || date2.isAfter(date1)) date1 else date2
fun LocalDate.toMoscowDateTime(): ZonedDateTime = atStartOfDay(MOSCOW_ZONE_ID)
fun createLocalDate(): LocalDate = LocalDate.now()
fun createLocalDateAtStartOfYear(): LocalDate = createLocalDate().withDayOfYear(1)
fun LocalDate.startOfWeek(): LocalDate = minusDays(this.dayOfWeek.ordinal.toLong())
fun LocalDate.endOfWeek(): LocalDate =
plusWeeks(1L).minusDays(this.dayOfWeek.ordinal.toLong() + 1L)
}

View File

@ -0,0 +1,3 @@
package ru.touchin.common.exceptions
open class CommonException(description: String?) : RuntimeException(description.orEmpty())

View File

@ -0,0 +1,4 @@
@file:Suppress("unused")
package ru.touchin.common.exceptions
open class CommonNotFoundException(description: String?) : CommonException(description)

View File

@ -0,0 +1,13 @@
@file:Suppress("unused")
package ru.touchin.common.number
import java.math.BigDecimal
object BigDecimalUtils {
fun BigDecimal.equalTo(number: BigDecimal): Boolean = compareTo(number) == 0
fun <T> Iterable<T>.sumBy(selector: (T) -> BigDecimal): BigDecimal =
fold(BigDecimal.ZERO) { accumulator, element -> accumulator + selector(element) }
}

View File

@ -0,0 +1,27 @@
@file:Suppress("unused")
package ru.touchin.common.random
import ru.touchin.common.string.StringUtils.emptyString
import java.security.SecureRandom
object SecureRandomStringGenerator {
private val secureRandom = SecureRandom()
private val DEFAULT_ALLOWED_CHARS = listOf<Iterable<*>>(0..9, 'a'..'z', 'A'..'Z').joinToString(emptyString()) {
it.joinToString(emptyString())
}
fun generate(length: Int, allowedChars: String = DEFAULT_ALLOWED_CHARS): String {
return buildString(length) {
repeat(length) {
val char = secureRandom
.nextInt(allowedChars.length)
.let(allowedChars::get)
append(char)
}
}
}
}

View File

@ -0,0 +1,130 @@
@file:Suppress("unused", "MemberVisibilityCanBePrivate")
package ru.touchin.common.string
import org.jetbrains.annotations.Contract
object StringUtils {
fun emptyString() = ""
@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
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"
)
}

View File

@ -1 +1,4 @@
kotlin.code.style=official
kotlin.code.style=official
springBootVersion=2.4.1
springDependencyManagementVersion=1.0.11.RELEASE
kotlinVersion=1.4.32

Binary file not shown.

View File

@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.2.1-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

53
gradlew vendored
View File

@ -1,5 +1,21 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
@ -28,7 +44,7 @@ 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"'
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
@ -66,6 +82,7 @@ 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
@ -109,10 +126,11 @@ 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
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
@ -138,19 +156,19 @@ if $cygwin ; then
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
i=`expr $i + 1`
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
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
@ -159,14 +177,9 @@ save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
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" "$@"

173
gradlew.bat vendored
View File

@ -1,84 +1,89 @@
@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
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
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 execute
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
: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 %*
: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

View File

@ -1,5 +0,0 @@
rootProject.name = System.getProperty("rootProjectName")
?: 'Backend-common'
include 'utils'
include 'test-utils'

23
settings.gradle.kts Normal file
View File

@ -0,0 +1,23 @@
pluginManagement {
resolutionStrategy {
val kotlinVersion: String by settings
val springBootVersion: String by settings
val springDependencyManagementVersion: String by settings
val versions = listOf(
"org.jetbrains.kotlin" to kotlinVersion,
"org.springframework.boot" to springBootVersion,
"io.spring.dependency-management" to springDependencyManagementVersion
)
eachPlugin {
versions.find { requested.id.id.startsWith(it.first) }
?.let {
useVersion(it.second)
}
}
}
}
include("common")

View File

@ -1,19 +0,0 @@
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"
}

View File

@ -1,19 +0,0 @@
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")
}
}
}

View File

@ -1,30 +0,0 @@
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)
}

View File

@ -1,9 +0,0 @@
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()
}

View File

@ -1,144 +0,0 @@
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
}
}

View File

@ -1,17 +0,0 @@
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"
}

View File

@ -1,6 +0,0 @@
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) }

View File

@ -1,15 +0,0 @@
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

View File

@ -1,7 +0,0 @@
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"

View File

@ -1,38 +0,0 @@
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)

View File

@ -1,3 +0,0 @@
package ru.touchinstinct.utils
class Empty

View File

@ -1,17 +0,0 @@
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())
}

View File

@ -1,19 +0,0 @@
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))
}

View File

@ -1,12 +0,0 @@
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
}

View File

@ -1,128 +0,0 @@
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

View File

@ -1,51 +0,0 @@
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")
}