Go to file
Artem Tsebrov 5e0fce2a60 Update testcontainers versions for better docker compatibility (#2)
https://github.com/testcontainers/testcontainers-java/releases/tag/1.18.3
Co-authored-by: Artyom Tsebrov <artem.tsebrov@touchin.ru>
Reviewed-on: #2
2023-08-04 17:38:17 +03:00
captcha Miscellaneous changes (#50) 2021-08-19 20:07:41 +03:00
codestyle-archunit Codestyle archunit (#1) 2023-04-18 17:17:14 +03:00
common Feature/telegram bot (#106) 2022-12-12 14:14:13 +03:00
common-device Add user agent parsing module (#82) 2022-09-26 23:34:20 +03:00
common-geo rename GeoHelper -> GeoCalculator 2021-06-08 20:24:32 +03:00
common-geo-spatial4j-spring review fixes 2021-06-08 20:29:33 +03:00
common-measure fix linter 2021-06-15 19:06:50 +03:00
common-measure-spring add common-measure 2021-06-08 19:48:08 +03:00
common-messaging Add common-messaging (#51) 2021-08-26 15:25:00 +03:00
common-spring detekt support (#90) 2022-11-12 18:59:35 +03:00
common-spring-jpa Mark createdAt as not updatable (#108) 2023-01-13 17:30:42 +03:00
common-spring-security fix linter 2021-06-15 19:06:50 +03:00
common-spring-security-jpa fix migrations, refresh token 2021-06-27 10:23:26 +03:00
common-spring-test add common-spring-test 2021-06-06 22:55:02 +03:00
common-spring-test-jpa add test-slow profile to RepositoryTestConfiguration 2021-06-10 18:41:01 +03:00
common-spring-web add missing value resolver (#55) 2021-11-03 15:57:30 +03:00
common-territories Add geoip-core (#74) 2022-05-25 17:56:18 +03:00
exception-handler-logger-spring-web detekt support (#90) 2022-11-12 18:59:35 +03:00
exception-handler-spring-security-web Miscellaneous changes (#50) 2021-08-19 20:07:41 +03:00
exception-handler-spring-web detekt support (#90) 2022-11-12 18:59:35 +03:00
geoip-core Remove geoip schema creation script (#75) 2022-05-26 13:41:20 +03:00
gradle/wrapper detekt support (#90) 2022-11-12 18:59:35 +03:00
logger Implement "debug" level for logging (#107) 2023-01-10 14:02:39 +03:00
logger-spring detekt support (#90) 2022-11-12 18:59:35 +03:00
logger-spring-web Miscellaneous changes (#50) 2021-08-19 20:07:41 +03:00
push-message-provider Push message provider for Huawei Push Kit (#102) 2022-11-08 15:42:25 +03:00
push-message-provider-fcm detekt support (#90) 2022-11-12 18:59:35 +03:00
push-message-provider-hpk detekt support (#90) 2022-11-12 18:59:35 +03:00
push-message-provider-mock Implement push message provider mock check method (#103) 2022-11-09 18:23:48 +03:00
response-wrapper-spring-web rename wrap annotations 2021-06-08 18:21:02 +03:00
s3-storage Added property endpoint (#76) 2022-07-14 16:02:02 +03:00
security-authorization-server-core detekt support (#90) 2022-11-12 18:59:35 +03:00
security-authorization-server-jwt-core More auth refactoring (#47) 2021-08-18 13:22:19 +03:00
security-authorization-server-oauth2-metadata detekt support (#90) 2022-11-12 18:59:35 +03:00
security-jwt-common Refactor auth modules (#46) 2021-08-17 10:47:00 +03:00
security-resource-server-custom-jwt-configuration More auth refactoring (#47) 2021-08-18 13:22:19 +03:00
security-resource-server-default-jwt-configuration More auth refactoring (#47) 2021-08-18 13:22:19 +03:00
security-resource-server-test-jwt-configuration More auth refactoring (#47) 2021-08-18 13:22:19 +03:00
server-info-spring-web detekt support (#90) 2022-11-12 18:59:35 +03:00
settings-spring-jpa fix linter 2021-06-15 19:06:50 +03:00
smart-migration Feature/smart migration (#86) 2022-11-12 16:11:58 +03:00
telegram-bot-spring Feature/telegram bot (#106) 2022-12-12 14:14:13 +03:00
user-agent Add user agent parsing module (#82) 2022-09-26 23:34:20 +03:00
validation-spring detekt support (#90) 2022-11-12 18:59:35 +03:00
version-spring-web rename version annotations 2021-06-08 15:23:16 +03:00
.editorconfig add common module 2021-06-06 19:19:46 +03:00
.gitignore add common module 2021-06-06 19:19:46 +03:00
LICENSE add Apache 2.0 License 2021-06-06 21:39:21 +03:00
README.md Codestyle archunit (#1) 2023-04-18 17:17:14 +03:00
build.gradle.kts Update testcontainers versions for better docker compatibility (#2) 2023-08-04 17:38:17 +03:00
detekt-config.yml Codestyle archunit (#1) 2023-04-18 17:17:14 +03:00
diktat-analysis.yml Kotlin Styleguide plugins 2023-04-06 16:54:03 +00:00
gradle.properties Kotlin Styleguide plugins 2023-04-06 16:54:03 +00:00
gradlew add common module 2021-06-06 19:19:46 +03:00
gradlew.bat add common module 2021-06-06 19:19:46 +03:00
settings.gradle.kts Codestyle archunit (#1) 2023-04-18 17:17:14 +03:00

README.md

Modules

Installation via Gradle Composite Build

  1. Add this repository as a git submodule to your project

  2. Add these lines to your settings.gradle.kts:

    includeBuild("Backend-common")
    
  3. Use TLK modules as dependencies of your project

    dependencies {
        implementation("ru.touchin:common")
    }
    

Project Gradle tasks

Detekt:

  • gradle $project:detekt - detect not formatted, complex code.

Reports are stored in "pwd/build/reports/kotlin-detekt-{project.name}.html".

DiKTat:

  • gradle :diktatCheck - detect not formatted code of "kt", "kts" files;
  • gradle :diktatFix - if possible, fix not formatted code. Known issues: full fix may require 1+ launch in order to apply all rules; some rules potentially may break code syntax.

By setting environment variable TASKS_FILE_REPORT_ENABLED(true, false) you may configure raw console output or html file as report. Reports are stored in "$pwd/build/reports/diktat-report.html".

common

Набор утилит, структур данных, исключений без привязки к spring

  • ExecutionContext - класс для хранения/получения данных из текущего потока
  • SecureRandomStringGenerator - генератор случайной строки по словарю
  • errors.* - базовые исключения
  • <type>.*Utils - утилиты для различных типов данных

common-spring

Набор утилит, структур данных для spring, без привязки к доп. модулям, таким как jpa и web

common-spring-jpa

  • models.* - базовые Entity
  • repositories - утилиты и доп. интерфейсы для репозиториев
  • liquibase.LiquibaseStart - для подключения этого компонента необходимо объявить liquibase.LiquibaseParams. Указать путь к файлу с миграцией и схему, для которой эта миграция будет применяться. С помощью LiquibaseStart можно применить кастомную миграцию не конфликтуя с основной.
  • EnableJpaAuditingExtra - подключение JpaAuditing с поддержкой типа ZoneDateTime

common-spring-web

  • request.Utils - различные extensions для работы с HttpServletRequest
  • errors.* - исключения и типы данных для web
  • webclient.* - классы для расширения webclient, включая логирование

common-spring-security

  • configurations.DefaultSecurityConfiguration - дефолтная реализация WebSecurity, определяет для каких request path надо ограничить доступ. Использует url.interceptors.UrlExpressionRegistryInterceptor для принятия решения.
  • auditor.AuditorResolver - служит для преобразования principal в строку, используется с JpaAuditing

common-spring-security-jpa

  • auditor.SecurityAuditorAware - резолвит имя пользователя для полей @CreatedBy, @LastModifiedBy. Требуется явно создать бин AuditorAware<String> в проекте.

common-spring-test

Утилиты для тестирования в среде spring-test

common-spring-test-jpa

Утилиты для тестирования репозиториев

codestyle-archunit

Набор правил для поддержки оформления архитектуры.

Список доступных правил

  • ru.touchin.codestyle.archunit.rules.ClassNamingArchRules
  • ru.touchin.codestyle.archunit.rules.ClassPackagingArchRules

Gradle plugin

Настройка и применение совместно с ArchUnit Gradle Plugin.

Действие checkRules для проверки соответствие правилам запускается при операциях сборки, по умолчанию. Вручную можно вызвать командой gradle :checkRules для нужного модуля. Добавить его можно следующим образом на примере установки в рутовый gradle.build проекта:

Groovy DSL:

buildscript {
    dependencies {
        classpath "com.societegenerale.commons:arch-unit-gradle-plugin:3.0.0"
    }
}
subprojects {
    dependencyManagement {
        dependencies {
            dependency "com.tngtech.archunit:archunit:1.0.1"
        }
    }

    apply plugin: "java"
    apply plugin: "com.societegenerale.commons.arch-unit-gradle-plugin"

    archUnit {
        mainScopePath = "/classes/kotlin/main" // or "/classes/java/main"
        testScopePath = "/classes/kotlin/test" // or "/classes/java/test"

        var applyType = applyOn("ru.touchin", "main")
        configurableRules = [
            configurableRule(
                "ru.touchin.codestyle.archunit.rules.ClassNamingArchRules",
                applyType,
            ),
            configurableRule(
                "ru.touchin.codestyle.archunit.rules.ClassPackagingArchRules",
                applyType,
            ),
        ]
    }

    dependencies {
        archUnitExtraLib "ru.touchin:codestyle-archunit" // or archUnitExtraLib project(":codestyle-archunit")
    }
}

Kotlin DSL:

plugins {
    id("com.societegenerale.commons.arch-unit-gradle-plugin") version "3.0.0"
}
subprojects {
    configure<DependencyManagementExtension> {
        dependencies {
            dependency("com.tngtech.archunit:archunit:1.0.1")
        }
    }
    
    apply(plugin = "java")
    apply(plugin = "com.societegenerale.commons.arch-unit-gradle-plugin")

    archUnit {
        mainScopePath = "/classes/kotlin/main" // or "/classes/java/main"
        testScopePath = "/classes/kotlin/test" // or "/classes/java/test"

        configurableRules = listOf(
            "ru.touchin.codestyle.archunit.rules.ClassNamingArchRules",
            "ru.touchin.codestyle.archunit.rules.ClassPackagingArchRules"
        ).map { package ->
            configurableRule(
                package,
                applyOn("ru.touchin", "main")
            )
        }
    }

    dependencies {
        archUnitExtraLib("ru.touchin:codestyle-archunit") // or archUnitExtraLib(project(":codestyle-archunit"))
    }
}

Отключить проверки на таске помимо конфигурирования configurableRule можно также таким образом:

// clear action launch for root project to avoid exception
tasks.checkRules.configure {
    actions.clear()
}

logger

Основные компоненты логирования:

  • layout
  • context
  • format

logger-spring

Встраивание системы логирования в spring

  • autologging
  • serializer

logger-spring-web

Interceptor для логирования запросов/ответов.

exception-handler-spring-web

Перехватывает ошибки сервера, определяет код ошибки и возвращает их в правильный response. Подключается с помощью аннотации @EnableSpringExceptionHandler

exception-handler-logger-spring-web

Добавляет логирование в обработку ошибок. Подключается с помощью аннотации @EnableSpringExceptionHandlerLogger до подключения основного модуля.

validation-spring

Добавляет аннотации для валидации запросов.

version-spring-web

Добавляет возможность задавать версию апи через properties без необходимости явно указывать в каждом маппинге

response-wrapper-spring-web

Добавляет обертку для успешного ответа

common-measure

Утилиты для работы с measure

common-measure-spring

Возможность задавать measure через properties

common-geo

Интерфейс для работы с гео-данными

common-geo-spatial4j-spring

Реализация интерфейса GeoCalculator с помощью библиотеки spatial4j

settings-spring-jpa

Модуль для хранения настроек

security-authorization-server-core

Модуль авторизации

security-authorization-server-jwt-core

Добавляет поддержку jwt-токенов (создание/хранение). Для работы этого модуля требуется прописать в пропертях:

token.access:
  issuer: ${app.issuer}
  timeToLive: PT15M # 15 minutes
  signatureAlgorithm: RS256
  keyPair:
    public: |
      -----BEGIN PUBLIC KEY-----
      -----END PUBLIC KEY-----      
    private: |
      -----BEGIN PRIVATE KEY-----
      -----END PRIVATE KEY-----      
token.refresh:
  length: 20
  prefix: RT-
  timeToLive: PT2H # 2 hours

Генерация ключей:

openssl genrsa -out private.pem 4096
openssl rsa -in private.pem -pubout -out public.pem
openssl pkcs8 -topk8 -inform PEM -in private.pem -out private_key.pem -nocrypt

cat private_key.pem
cat public.pem

security-authorization-server-oauth2-metadata

OAuth2 metadata support.

security-jwt-common

JWT related utilities.

security-resource-server-default-configuration

Default configuration for the Spring OAuth2 resource server with JWT auth.

security-resource-server-custom-configuration

Custom configuration for the Spring OAuth2 resource server with JWT auth. Requires the following properties:

token.access:
  issuer: ${app.issuer}
  signatureAlgorithm: RS256
  keyPair:
    public: |
      -----BEGIN PUBLIC KEY-----
      -----END PUBLIC KEY-----      

security-resource-server-test-configuration

Disables Spring OAuth2 resource server for testing.

s3-storage

Amazon S3 support.

server-info-spring-web

Allow include headers with information about the server in responses

To get started you need:

  1. Add annotation to configuration
  2. Add property to yml/properties file:
server.info:
    buildVersion: ${buildVersion}
  1. Implement ServerInfoService (optional. If you want to add other headers)
  2. Add dir with impl ServerInfoService in ComponentScan annotation

push-message-provider

Интерфейсы и компоненты для модулей по обеспечению интеграции с сервисами отправки пуш-уведомлений. Является необходимой зависимостью для использования провайдеров.

Далее рассматривается пример использования подключаемых модулей-провайдеров.

@Service
class PushSendingService(
    private val pushMessageProviderServiceFactory: PushMessageProviderServiceFactory
) {

    fun sendPushMessage() {
        val yourPushToken = "pushTokenForChecking"
        val platform = PlatformType.ANDROID_GOOGLE

        val pushMessageProvider: PushMessageProviderService = pushMessageProviderServiceFactory.get(platform)

        val result = pushMessageProvider.check( // Проверка валидности токена для обозначения целесообразности отправки
            PushTokenCheck(
                pushToken = yourPushToken
            )
        )

        if (result.status == PushTokenStatus.VALID) { // Токен валиден, PushMessageProviderService интегрирован в систему
            // Отправка пуш-уведомления
            pushMessageProvider.send(
                PushTokenMessage(
                    token = yourPushToken,
                    pushMessageNotification = PushMessageNotification(
                        title = "Your PushMessage",
                        description = "Provided by PushMessageProviderService",
                        imageUrl = null
                    ),
                    data = mapOf(
                        "customKey" to "customData"
                    )
                )
            )
        }
    }

}

push-message-provider-fcm

Модуль по обеспечению интеграции с Firebase Cloud Messaging.

  1. Подключение компонентов Spring осуществляется при помощи аннотации @EnablePushMessageProviderFcm.
  2. Необходимо добавление конфигурации для модуля с выбранным способом хранения данных для авторизации. Пример файла конфигурации в формате yaml:
push-message-provider:
  platformProviders:
    ANDROID_GOOGLE:
      - FCM
    IOS:
      - FCM
  fcm:
    appName: yourAppName
    auth:
      # Выбранный тип авторизации
    client:
      readTimeout: 10s
      connectionTimeout: 1s
  1. Настраивается способ предоставления авторизации для Firebase Cloud Messaging.

А) Токен доступа из консоли Google, добавляемый в конфигурацию настроек:

    auth:
      token:
        value: testValue
        expiresAt: 2023-01-01 23:59:59 +00:00

B) Данные в файле из консоли Firebase, добавляемые в resources с обозначением пути в конфигурации настроек:

    auth:
      credentialsFile:
        path: credentials/firebase-admin.json

C) Данные из файла консоли Firebase, добавляемые в конфигурацию настроек:

    auth:
      credentialsData:
        type: service_account
        projectId: yourProjectId
        privateKeyId: yourPrivateKeyId
        privateKey: |
          -----BEGIN PRIVATE KEY-----
          -----END PRIVATE KEY-----          
        clientEmail: yourClientEmail
        clientId: yourClientId
        authUri: yourAuthUri
        tokenUri: yourTokenUri
        authProviderX509CertUrl: yourAuthProviderX509CertUrl
        clientX509CertUrl: yourClientX509CertUrl

push-message-provider-hpk

Модуль по обеспечению интеграции с Huawei Push Kit.

  1. Подключение нового провайдера осуществляется при помощи аннотации @EnablePushMessageProviderHpk.
  2. Для логирования запросов к сервису HPK нужно встроить в контейнер Spring собственный WebClientLogger из модуля logger-spring-web или же использовать стандартный посредством импорта конфигурации:
@Import(
    SpringLoggerConfiguration::class,
    SpringLoggerWebConfiguration::class
)
class YourConfiguration
  1. Нужно добавить конфигурацию для считывания модулем. Пример файла в формате yaml:
push-message-provider:
  platformProviders:
    ANDROID_HUAWEI:
      - HPK
  hpk:
    web-services:
      client-id: yourClientId
      oauth:
        client-secret: yourClientSecret
        url: https://oauth-login.cloud.huawei.com/oauth2/v3/
        http:
          connection-timeout: 1s
          read-timeout: 10s
          write-timeout: 10s
        ssl: # Опциональная структура
          handshake-timeout: 1s
          notify-read-timeout: 1s
          notify-flush-timeout: 1s
      hpk:
        url: https://push-api.cloud.huawei.com/v1/
        http:
          connection-timeout: 1s
          read-timeout: 10s
          write-timeout: 10s
        ssl: # Опциональная структура
          handshake-timeout: 1s
          notify-read-timeout: 1s
          notify-flush-timeout: 1s