From 9de4d99ab61c6fd5d5156eafa43fa6115069ede2 Mon Sep 17 00:00:00 2001 From: Struchkov Mark Date: Fri, 29 Apr 2022 01:04:33 +0300 Subject: [PATCH] release-2.0.0 --- pom.xml | 288 +++++++++++------- .../autoresponder/AutoResponder.java | 118 ++++--- .../compare/UnitPriorityComparator.java | 4 +- .../struchkov/autoresponder/entity/Unit.java | 131 ++++++++ .../autoresponder/entity/UnitPointer.java | 56 ++++ .../repository/UnitPointerRepository.java | 26 ++ .../repository/UnitPointerRepositoryMap.java | 41 +++ .../service/UnitPointerService.java | 22 ++ .../service/UnitPointerServiceImpl.java | 43 +++ .../autoresponder/util/Message.java | 2 +- .../struchkov/autoresponder/util/Parser.java | 40 +++ .../struchkov/autoresponder/util/Units.java | 39 +++ src/main/java/module-info.java | 6 + .../sadtech/autoresponder/entity/Unit.java | 55 ---- .../autoresponder/entity/UnitPointer.java | 26 -- .../repository/UnitPointerRepository.java | 26 -- .../repository/UnitPointerRepositoryMap.java | 36 --- .../service/UnitPointerService.java | 22 -- .../service/UnitPointerServiceImpl.java | 34 --- .../autoresponder/util/Description.java | 19 -- .../sadtech/autoresponder/util/Parser.java | 42 --- .../autoresponder/AutoResponderTest.java | 143 +++++++++ .../autoresponder/test/TestUnit.java | 108 +++++++ .../autoresponder/AutoResponderTest.java | 141 --------- .../sadtech/autoresponder/test/TestUnit.java | 32 -- 25 files changed, 901 insertions(+), 599 deletions(-) rename src/main/java/{org/sadtech => dev/struchkov}/autoresponder/AutoResponder.java (56%) rename src/main/java/{org/sadtech => dev/struchkov}/autoresponder/compare/UnitPriorityComparator.java (80%) create mode 100644 src/main/java/dev/struchkov/autoresponder/entity/Unit.java create mode 100644 src/main/java/dev/struchkov/autoresponder/entity/UnitPointer.java create mode 100644 src/main/java/dev/struchkov/autoresponder/repository/UnitPointerRepository.java create mode 100644 src/main/java/dev/struchkov/autoresponder/repository/UnitPointerRepositoryMap.java create mode 100644 src/main/java/dev/struchkov/autoresponder/service/UnitPointerService.java create mode 100644 src/main/java/dev/struchkov/autoresponder/service/UnitPointerServiceImpl.java rename src/main/java/{org/sadtech => dev/struchkov}/autoresponder/util/Message.java (94%) create mode 100644 src/main/java/dev/struchkov/autoresponder/util/Parser.java create mode 100644 src/main/java/dev/struchkov/autoresponder/util/Units.java create mode 100644 src/main/java/module-info.java delete mode 100644 src/main/java/org/sadtech/autoresponder/entity/Unit.java delete mode 100644 src/main/java/org/sadtech/autoresponder/entity/UnitPointer.java delete mode 100644 src/main/java/org/sadtech/autoresponder/repository/UnitPointerRepository.java delete mode 100644 src/main/java/org/sadtech/autoresponder/repository/UnitPointerRepositoryMap.java delete mode 100644 src/main/java/org/sadtech/autoresponder/service/UnitPointerService.java delete mode 100644 src/main/java/org/sadtech/autoresponder/service/UnitPointerServiceImpl.java delete mode 100644 src/main/java/org/sadtech/autoresponder/util/Description.java delete mode 100644 src/main/java/org/sadtech/autoresponder/util/Parser.java create mode 100644 src/test/java/dev/struchkov/autoresponder/AutoResponderTest.java create mode 100644 src/test/java/dev/struchkov/autoresponder/test/TestUnit.java delete mode 100644 src/test/java/org/sadtech/autoresponder/AutoResponderTest.java delete mode 100644 src/test/java/org/sadtech/autoresponder/test/TestUnit.java diff --git a/pom.xml b/pom.xml index 66bc948..d24c218 100644 --- a/pom.xml +++ b/pom.xml @@ -4,9 +4,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - org.sadtech.autoresponder + dev.struchkov autoresponder - 1.10-SNAPSHOT + 2.0.0 jar Abstract Autoresponder @@ -20,6 +20,174 @@ + + 17 + ${java.version} + ${java.version} + UTF-8 + UTF-8 + + 1.0.2 + + 5.8.2 + 1.7.36 + 23.0.0 + + 3.9.0 + 1.6.8 + 3.2.1 + 3.3.1 + 3.0.0-M6 + 3.0.1 + + + + + org.slf4j + slf4j-api + ${slf4j.ver} + + + + dev.struchkov.haiti + haiti-utils + ${haiti.utils.ver} + + + + org.jetbrains + annotations + ${jetbrains.annotation.ver} + + + + org.junit.jupiter + junit-jupiter-engine + ${junit.ver} + test + + + + + + + + org.sonatype.plugins + nexus-staging-maven-plugin + ${plugin.nexus.staging.ver} + true + + ossrh + https://s01.oss.sonatype.org/ + true + + + + org.apache.maven.plugins + maven-source-plugin + ${plugin.maven.source.ver} + + + attach-sources + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + ${plugin.maven.javadoc.ver} + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-gpg-plugin + ${plugin.maven.gpg.ver} + + + sign-artifacts + verify + + sign + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${plugin.maven.compiler.ver} + + ${java.version} + ${java.version} + + + + org.apache.maven.plugins + maven-surefire-plugin + ${plugin.maven.surefire.ver} + + + org.junit.jupiter + junit-jupiter-engine + ${junit.ver} + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + org.apache.maven.plugins + maven-source-plugin + + + org.apache.maven.plugins + maven-javadoc-plugin + + + + + + + release + + + + org.sonatype.plugins + nexus-staging-maven-plugin + + + org.apache.maven.plugins + maven-source-plugin + + + org.apache.maven.plugins + maven-gpg-plugin + + + org.apache.maven.plugins + maven-javadoc-plugin + + + + + + scm:git:https://github.com/uPagge/autoresponder.git https://github.com/uPagge/autoresponder @@ -33,124 +201,12 @@ - - 4.12 - 1.18.12 - 1.7.30 - - - - - junit - junit - ${junit.ver} - - - - org.projectlombok - lombok - ${lombok.ver} - - - - org.slf4j - slf4j-api - ${slf4j.ver} - - - - - - release - - - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.7 - true - - ossrh - https://oss.sonatype.org/ - true - - - - org.apache.maven.plugins - maven-source-plugin - 2.2.1 - - - attach-sources - - jar-no-fork - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9.1 - - - attach-javadocs - - jar - - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.5 - - - sign-artifacts - verify - - sign - - - - - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.7 - true - - ossrh - https://oss.sonatype.org/ - true - - - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.0 - - 8 - 8 - - - - - uPagge Struchkov Mark - upagge@mail.ru - SADTECH + mark@struchkov.dev + https://mark.struchkov.dev diff --git a/src/main/java/org/sadtech/autoresponder/AutoResponder.java b/src/main/java/dev/struchkov/autoresponder/AutoResponder.java similarity index 56% rename from src/main/java/org/sadtech/autoresponder/AutoResponder.java rename to src/main/java/dev/struchkov/autoresponder/AutoResponder.java index 8fd61b2..614251b 100644 --- a/src/main/java/org/sadtech/autoresponder/AutoResponder.java +++ b/src/main/java/dev/struchkov/autoresponder/AutoResponder.java @@ -1,43 +1,49 @@ -package org.sadtech.autoresponder; +package dev.struchkov.autoresponder; -import lombok.Getter; -import lombok.NonNull; -import lombok.Setter; -import lombok.extern.slf4j.Slf4j; -import org.sadtech.autoresponder.compare.UnitPriorityComparator; -import org.sadtech.autoresponder.entity.Unit; -import org.sadtech.autoresponder.entity.UnitPointer; -import org.sadtech.autoresponder.service.UnitPointerService; -import org.sadtech.autoresponder.util.Description; -import org.sadtech.autoresponder.util.Message; -import org.sadtech.autoresponder.util.Parser; +import dev.struchkov.autoresponder.compare.UnitPriorityComparator; +import dev.struchkov.autoresponder.entity.Unit; +import dev.struchkov.autoresponder.entity.UnitPointer; +import dev.struchkov.autoresponder.service.UnitPointerService; +import dev.struchkov.autoresponder.util.Message; +import dev.struchkov.autoresponder.util.Parser; +import dev.struchkov.haiti.utils.Inspector; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.HashSet; import java.util.Optional; import java.util.Set; +import static dev.struchkov.haiti.utils.Inspector.isEmpty; +import static dev.struchkov.haiti.utils.Inspector.isNotEmpty; +import static dev.struchkov.haiti.utils.Inspector.isNotNull; + /** * Реализуют основную логику автоответчика. * * @author upagge [07/07/2019] */ -@Slf4j -public class AutoResponder { +public class AutoResponder> { - @Description("Компоратор для сортировки Unit-ов") + private static final Logger log = LoggerFactory.getLogger(AutoResponder.class); + + /** + * Компоратор для сортировки Unit-ов + */ private static final UnitPriorityComparator UNIT_PRIORITY_COMPARATOR = new UnitPriorityComparator(); - @Description("Начальные юниты, первый запрос приходит на них") + /** + * Начальные юниты, первый запрос приходит на них + */ private final Set startUnits; - @Getter - @Setter - @Description("Дефолтный юнит, отправляется если ни один Unit не подошел") - private U defaultUnit; - - @Getter private final UnitPointerService unitPointerService; + /** + * Дефолтный юнит, отправляется если ни один Unit не подошел + */ + private U defaultUnit; + public AutoResponder(UnitPointerService unitPointerService, Set startUnits) { this.startUnits = startUnits; this.unitPointerService = unitPointerService; @@ -50,7 +56,8 @@ public class AutoResponder { * @param message Запрос пользователя - текстовое сообщение * @return {@link Unit}, который отвечает за данные для обработки данного запроса */ - public Optional answer(@NonNull Long entityId, @NonNull String message) { + public Optional answer(Long entityId, String message) { + isNotNull(entityId, message); Optional> unitPointer = unitPointerService.getByEntityId(entityId); final Optional answer = nextUnit( unitPointer.isPresent() @@ -62,7 +69,8 @@ public class AutoResponder { ); if (answer.isPresent()) { final U unitAnswer = answer.get(); - if (unitAnswer.getNextUnits().isEmpty()) { + final Set nextUnits = unitAnswer.getNextUnits(); + if (isEmpty(nextUnits)) { unitPointerService.removeByEntityId(entityId); } else { unitPointerService.save(new UnitPointer<>(entityId, unitAnswer)); @@ -80,30 +88,29 @@ public class AutoResponder { * @param message Запрос пользователя - текстовое сообщение * @return Юнит, который нуждается в обработке в соответствии с запросом пользователя */ - private Optional nextUnit(@NonNull Set nextUnits, @NonNull String message) { - Set searchUnit = new HashSet<>(); + private Optional nextUnit(Set nextUnits, String message) { + isNotNull(nextUnits, message); + final Set searchUnit = new HashSet<>(); - for (U unit : nextUnits) { - if (unit.getPhrase() != null - && !unit.getPhrase().isEmpty() - && unit.getPhrase().equalsIgnoreCase(message)) { - searchUnit.add(unit); + if (isNotEmpty(nextUnits)) { + for (U unit : nextUnits) { + if (unit.getPhrase() != null + && !unit.getPhrase().isEmpty() + && unit.getPhrase().equalsIgnoreCase(message)) { + searchUnit.add(unit); + } + + if (unit.getPattern() != null && patternReg(unit, message)) { + searchUnit.add(unit); + } + + if (percentageMatch(unit, Parser.parse(message)) >= unit.getMatchThreshold()) { + searchUnit.add(unit); + } } } - for (U unit : nextUnits) { - if (unit.getPattern() != null && patternReg(unit, message)) { - searchUnit.add(unit); - } - } - - for (U unit : nextUnits) { - if (percentageMatch(unit, Parser.parse(message)) >= unit.getMatchThreshold()) { - searchUnit.add(unit); - } - } - - if (searchUnit.isEmpty()) { + if (isEmpty(searchUnit)) { for (U nextUnit : nextUnits) { if ((nextUnit.getPattern() == null && (nextUnit.getKeyWords() == null || nextUnit.getKeyWords().isEmpty()))) { searchUnit.add(nextUnit); @@ -113,14 +120,15 @@ public class AutoResponder { return searchUnit.stream().max(UNIT_PRIORITY_COMPARATOR); } - private boolean patternReg(@NonNull U unit, String message) { + private boolean patternReg(U unit, String message) { + isNotNull(unit); return message.matches(unit.getPattern().pattern()); } private Double percentageMatch(U unit, Set words) { - Set keyWords = unit.getKeyWords(); + final Set keyWords = unit.getKeyWords(); if (keyWords != null && !keyWords.isEmpty()) { - Set temp = new HashSet<>(keyWords); + final Set temp = new HashSet<>(keyWords); temp.retainAll(words); log.trace(Message.UNIT_KEYWORDS, keyWords, keyWords.size()); log.trace(Message.USER_MESSAGE_KEYWORDS, words); @@ -132,4 +140,20 @@ public class AutoResponder { } } + public UnitPointerService getUnitPointerService() { + return unitPointerService; + } + + public Set getStartUnits() { + return startUnits; + } + + public U getDefaultUnit() { + return defaultUnit; + } + + public void setDefaultUnit(U defaultUnit) { + this.defaultUnit = defaultUnit; + } + } diff --git a/src/main/java/org/sadtech/autoresponder/compare/UnitPriorityComparator.java b/src/main/java/dev/struchkov/autoresponder/compare/UnitPriorityComparator.java similarity index 80% rename from src/main/java/org/sadtech/autoresponder/compare/UnitPriorityComparator.java rename to src/main/java/dev/struchkov/autoresponder/compare/UnitPriorityComparator.java index dc8785e..3e22cdf 100644 --- a/src/main/java/org/sadtech/autoresponder/compare/UnitPriorityComparator.java +++ b/src/main/java/dev/struchkov/autoresponder/compare/UnitPriorityComparator.java @@ -1,6 +1,6 @@ -package org.sadtech.autoresponder.compare; +package dev.struchkov.autoresponder.compare; -import org.sadtech.autoresponder.entity.Unit; +import dev.struchkov.autoresponder.entity.Unit; import java.util.Comparator; diff --git a/src/main/java/dev/struchkov/autoresponder/entity/Unit.java b/src/main/java/dev/struchkov/autoresponder/entity/Unit.java new file mode 100644 index 0000000..44f7dd5 --- /dev/null +++ b/src/main/java/dev/struchkov/autoresponder/entity/Unit.java @@ -0,0 +1,131 @@ +package dev.struchkov.autoresponder.entity; + +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Pattern; + +/** + * Абстрактная сущность, отвечающая за хранение данных, необходимая для обработки запроса. + * + * @author upagge [07/07/2019] + */ +public abstract class Unit> { + + /** + * Ключевые слова. + */ + protected Set keyWords = new HashSet<>(); + + /** + * Точная фраза. + */ + protected String phrase; + + /** + * Регулярное выражение. + */ + protected Pattern pattern; + + /** + * Значение минимального отношения количества найденых ключевых слов, к количеству ключевых слов Unit-а. + */ + protected Integer matchThreshold; + + /** + * Значение приоритета. + */ + protected Integer priority; + + /** + * Множество следующих Unit в сценарии. + */ + protected Set nextUnits = new HashSet<>(); + + protected Unit(Set keyWords, + String phrase, + Pattern pattern, + Integer matchThreshold, + Integer priority, + Set nextUnits) { + this.keyWords = keyWords; + this.phrase = phrase; + this.pattern = pattern; + this.matchThreshold = matchThreshold == null ? 10 : matchThreshold; + this.priority = priority == null ? 10 : priority; + this.nextUnits = nextUnits; + } + + public Set getKeyWords() { + return keyWords; + } + + public void setKeyWords(Set keyWords) { + this.keyWords = keyWords; + } + + public String getPhrase() { + return phrase; + } + + public void setPhrase(String phrase) { + this.phrase = phrase; + } + + public Pattern getPattern() { + return pattern; + } + + public void setPattern(Pattern pattern) { + this.pattern = pattern; + } + + public Integer getMatchThreshold() { + return matchThreshold; + } + + public void setMatchThreshold(Integer matchThreshold) { + this.matchThreshold = matchThreshold; + } + + public Integer getPriority() { + return priority; + } + + public void setPriority(Integer priority) { + this.priority = priority; + } + + public Set getNextUnits() { + return nextUnits; + } + + public void setNextUnits(Set nextUnits) { + this.nextUnits = nextUnits; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Unit unit = (Unit) o; + return Objects.equals(keyWords, unit.keyWords) && Objects.equals(phrase, unit.phrase) && Objects.equals(pattern, unit.pattern) && Objects.equals(matchThreshold, unit.matchThreshold) && Objects.equals(priority, unit.priority); + } + + @Override + public int hashCode() { + return Objects.hash(keyWords, phrase, pattern, matchThreshold, priority); + } + + @Override + public String toString() { + return "Unit{" + + "keyWords=" + keyWords + + ", phrase='" + phrase + '\'' + + ", pattern=" + pattern + + ", matchThreshold=" + matchThreshold + + ", priority=" + priority + + '}'; + } + +} diff --git a/src/main/java/dev/struchkov/autoresponder/entity/UnitPointer.java b/src/main/java/dev/struchkov/autoresponder/entity/UnitPointer.java new file mode 100644 index 0000000..84667ac --- /dev/null +++ b/src/main/java/dev/struchkov/autoresponder/entity/UnitPointer.java @@ -0,0 +1,56 @@ +package dev.struchkov.autoresponder.entity; + +import java.util.Objects; + +/** + * Сущность для сохранения позиции пользователя в сценарии, состоящем из связного списка элементов {@link Unit}. + * + * @author upagge [07/07/2019] + */ +public class UnitPointer> { + + /** + * Идентификатор пользователя. + */ + private Long entityId; + + /** + * Юнит, который был обработан. + */ + private U unit; + + public UnitPointer(Long entityId, U unit) { + this.entityId = entityId; + this.unit = unit; + } + + public Long getEntityId() { + return entityId; + } + + public void setEntityId(Long entityId) { + this.entityId = entityId; + } + + public U getUnit() { + return unit; + } + + public void setUnit(U unit) { + this.unit = unit; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + UnitPointer that = (UnitPointer) o; + return Objects.equals(entityId, that.entityId); + } + + @Override + public int hashCode() { + return Objects.hash(entityId); + } + +} diff --git a/src/main/java/dev/struchkov/autoresponder/repository/UnitPointerRepository.java b/src/main/java/dev/struchkov/autoresponder/repository/UnitPointerRepository.java new file mode 100644 index 0000000..580f8f6 --- /dev/null +++ b/src/main/java/dev/struchkov/autoresponder/repository/UnitPointerRepository.java @@ -0,0 +1,26 @@ +package dev.struchkov.autoresponder.repository; + +import dev.struchkov.autoresponder.entity.Unit; +import dev.struchkov.autoresponder.entity.UnitPointer; +import org.jetbrains.annotations.NotNull; + +import java.util.Optional; + +/** + * Интегрфейс для работы с хранилищем сущности {@link UnitPointer}. + * + * @author upagge [07/07/2019] + */ +public interface UnitPointerRepository> { + + UnitPointer save(@NotNull UnitPointer unitPointer); + + /** + * @param entityId Идентификатор пользователя + * @return Объект с последним обработанным {@link Unit} для пользователя + */ + Optional> findByEntityId(Long entityId); + + void removeByEntityId(Long entityId); + +} diff --git a/src/main/java/dev/struchkov/autoresponder/repository/UnitPointerRepositoryMap.java b/src/main/java/dev/struchkov/autoresponder/repository/UnitPointerRepositoryMap.java new file mode 100644 index 0000000..5855739 --- /dev/null +++ b/src/main/java/dev/struchkov/autoresponder/repository/UnitPointerRepositoryMap.java @@ -0,0 +1,41 @@ +package dev.struchkov.autoresponder.repository; + +import dev.struchkov.autoresponder.entity.Unit; +import dev.struchkov.autoresponder.entity.UnitPointer; +import org.jetbrains.annotations.NotNull; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +import static dev.struchkov.haiti.utils.Inspector.isNotNull; + +/** + * Реализация хранилища для {@link UnitPointer} на основе Map. + * + * @author upagge [07/07/2019] + */ +public class UnitPointerRepositoryMap> implements UnitPointerRepository { + + private final Map> unitPointerMap = new HashMap<>(); + + @Override + public UnitPointer save(@NotNull UnitPointer unitPointer) { +// isNotNull(unitPointer); + unitPointerMap.put(unitPointer.getEntityId(), unitPointer); + return unitPointer; + } + + @Override + public Optional> findByEntityId(Long entityId) { + isNotNull(entityId); + return Optional.ofNullable(unitPointerMap.get(entityId)); + } + + @Override + public void removeByEntityId(Long entityId) { + isNotNull(entityId); + unitPointerMap.remove(entityId); + } + +} diff --git a/src/main/java/dev/struchkov/autoresponder/service/UnitPointerService.java b/src/main/java/dev/struchkov/autoresponder/service/UnitPointerService.java new file mode 100644 index 0000000..84b5e35 --- /dev/null +++ b/src/main/java/dev/struchkov/autoresponder/service/UnitPointerService.java @@ -0,0 +1,22 @@ +package dev.struchkov.autoresponder.service; + +import dev.struchkov.autoresponder.entity.Unit; +import dev.struchkov.autoresponder.entity.UnitPointer; +import org.jetbrains.annotations.NotNull; + +import java.util.Optional; + +/** + * Сервис для взаимодействия с сущностью {@link UnitPointer}. + * + * @author upagge [07/07/2019] + */ +public interface UnitPointerService> { + + void save(@NotNull UnitPointer unitPointer); + + Optional> getByEntityId(@NotNull Long entityId); + + void removeByEntityId(@NotNull Long entityId); + +} diff --git a/src/main/java/dev/struchkov/autoresponder/service/UnitPointerServiceImpl.java b/src/main/java/dev/struchkov/autoresponder/service/UnitPointerServiceImpl.java new file mode 100644 index 0000000..9bc2e87 --- /dev/null +++ b/src/main/java/dev/struchkov/autoresponder/service/UnitPointerServiceImpl.java @@ -0,0 +1,43 @@ +package dev.struchkov.autoresponder.service; + +import dev.struchkov.autoresponder.entity.Unit; +import dev.struchkov.autoresponder.entity.UnitPointer; +import dev.struchkov.autoresponder.repository.UnitPointerRepository; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Optional; + +import static dev.struchkov.haiti.utils.Inspector.isNotNull; + +public class UnitPointerServiceImpl> implements UnitPointerService { + + private static final Logger log = LoggerFactory.getLogger(UnitPointerServiceImpl.class); + + private final UnitPointerRepository unitPointerRepository; + + public UnitPointerServiceImpl(UnitPointerRepository unitPointerRepository) { + this.unitPointerRepository = unitPointerRepository; + } + + @Override + public Optional> getByEntityId(@NotNull Long entityId) { + isNotNull(entityId); + return unitPointerRepository.findByEntityId(entityId); + } + + @Override + public void removeByEntityId(@NotNull Long entityId) { + isNotNull(entityId); + unitPointerRepository.removeByEntityId(entityId); + } + + @Override + public void save(@NotNull UnitPointer unitPointer) { + isNotNull(unitPointer); + unitPointerRepository.save(unitPointer); + log.trace("Пользователь отправлен в репозиторий"); + } + +} diff --git a/src/main/java/org/sadtech/autoresponder/util/Message.java b/src/main/java/dev/struchkov/autoresponder/util/Message.java similarity index 94% rename from src/main/java/org/sadtech/autoresponder/util/Message.java rename to src/main/java/dev/struchkov/autoresponder/util/Message.java index a36fa8d..35392a5 100644 --- a/src/main/java/org/sadtech/autoresponder/util/Message.java +++ b/src/main/java/dev/struchkov/autoresponder/util/Message.java @@ -1,4 +1,4 @@ -package org.sadtech.autoresponder.util; +package dev.struchkov.autoresponder.util; /** * Класс содержащий сообщения для ошибок и логера. diff --git a/src/main/java/dev/struchkov/autoresponder/util/Parser.java b/src/main/java/dev/struchkov/autoresponder/util/Parser.java new file mode 100644 index 0000000..af3e3e5 --- /dev/null +++ b/src/main/java/dev/struchkov/autoresponder/util/Parser.java @@ -0,0 +1,40 @@ +package dev.struchkov.autoresponder.util; + +import java.util.Arrays; +import java.util.Set; +import java.util.stream.Collectors; + +import static dev.struchkov.autoresponder.util.Message.UTILITY_CLASS; + +/** + * Разбивает строку на множество слов, удаляя предлоги. + * + * @author upagge [07/07/2019] + */ +public class Parser { + + /** + * Множество предлогов. + */ + private static final Set pretexts = Set.of( + "в", "без", "до", "из", "к", "на", "по", "о", "от", "перед", "при", "с", "у", "за", "над", "об", + "под", "про", "для"); + + private Parser() { + throw new IllegalStateException(UTILITY_CLASS); + } + + /** + * Метод по разбиению строки на множество слов. + * + * @param text Строка + * @return Множество слов + */ + public static Set parse(String text) { + final String[] split = text.split("\\P{L}+"); + final Set words = Arrays.stream(split).map(String::toLowerCase).collect(Collectors.toSet()); + words.removeAll(pretexts); + return words; + } + +} diff --git a/src/main/java/dev/struchkov/autoresponder/util/Units.java b/src/main/java/dev/struchkov/autoresponder/util/Units.java new file mode 100644 index 0000000..550f3ae --- /dev/null +++ b/src/main/java/dev/struchkov/autoresponder/util/Units.java @@ -0,0 +1,39 @@ +package dev.struchkov.autoresponder.util; + +import dev.struchkov.autoresponder.entity.Unit; + +import java.util.Set; + +import static dev.struchkov.haiti.utils.Exceptions.utilityClass; +import static dev.struchkov.haiti.utils.Inspector.isNotEmpty; +import static dev.struchkov.haiti.utils.Inspector.isNotNull; + +/** + * Утилитарный класс с полезными методами для работы с юнитами. + */ +public class Units { + + private Units() { + utilityClass(); + } + + /** + * Позволяет связать два разных юнита. Используется, чтобы побороть циклические зависимости в различных фреймворках. + * + * @param first К этому юниту будет присоединен юнит second. + * @param second Этот юнит присоединяется после first. + */ + public static void link(Unit first, Unit second) { + isNotNull(first, second); + final Set nextUnits = first.getNextUnits(); + if (isNotEmpty(nextUnits)) { + nextUnits.add(second); + } + } + + public static void link(Unit first, Unit... other) { + isNotNull(first); + isNotEmpty(other); + } + +} diff --git a/src/main/java/module-info.java b/src/main/java/module-info.java new file mode 100644 index 0000000..a88900b --- /dev/null +++ b/src/main/java/module-info.java @@ -0,0 +1,6 @@ +module autoresponder.copy { + requires haiti.utils; + + requires org.slf4j; + requires org.jetbrains.annotations; +} \ No newline at end of file diff --git a/src/main/java/org/sadtech/autoresponder/entity/Unit.java b/src/main/java/org/sadtech/autoresponder/entity/Unit.java deleted file mode 100644 index 3d9f84a..0000000 --- a/src/main/java/org/sadtech/autoresponder/entity/Unit.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.sadtech.autoresponder.entity; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; -import org.sadtech.autoresponder.util.Description; - -import java.util.Set; -import java.util.regex.Pattern; - -/** - * Абстрактная сущность, отвечающая за хранение данных, необходимая для обработки запроса. - * - * @author upagge [07/07/2019] - */ -@Getter -@EqualsAndHashCode -@ToString -@Setter -public abstract class Unit { - - @Description("Ключевые слова") - protected Set keyWords; - - @Description("Точная фраза") - protected String phrase; - - @Description("Регулярное выражение") - protected Pattern pattern; - - @Description("Значение минимального отношения количества найденых ключевых слов, к количеству ключевых слов Unit-а") - protected Integer matchThreshold; - - @Description("Значение приоритета") - protected Integer priority; - - @Description("Множество следующих Unit в сценарии") - protected Set nextUnits; - - protected Unit(Set keyWords, - String phrase, - Pattern pattern, - Integer matchThreshold, - Integer priority, - Set nextUnits) { - this.keyWords = keyWords; - this.phrase = phrase; - this.pattern = pattern; - this.matchThreshold = matchThreshold == null ? 10 : matchThreshold; - this.priority = priority == null ? 10 : priority; - this.nextUnits = nextUnits; - } - -} diff --git a/src/main/java/org/sadtech/autoresponder/entity/UnitPointer.java b/src/main/java/org/sadtech/autoresponder/entity/UnitPointer.java deleted file mode 100644 index 7916ec9..0000000 --- a/src/main/java/org/sadtech/autoresponder/entity/UnitPointer.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.sadtech.autoresponder.entity; - -import lombok.AllArgsConstructor; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.sadtech.autoresponder.util.Description; - -/** - * Сущность для сохранения позиции пользователя в сценарии, состоящем из связного списка элементов {@link Unit}. - * - * @author upagge [07/07/2019] - */ -@Getter -@Setter -@AllArgsConstructor -@EqualsAndHashCode(of = "entityId") -public class UnitPointer { - - @Description("Идентификатор пользователя") - private Long entityId; - - @Description("Юнит, который был обработан") - private U unit; - -} diff --git a/src/main/java/org/sadtech/autoresponder/repository/UnitPointerRepository.java b/src/main/java/org/sadtech/autoresponder/repository/UnitPointerRepository.java deleted file mode 100644 index bf4141f..0000000 --- a/src/main/java/org/sadtech/autoresponder/repository/UnitPointerRepository.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.sadtech.autoresponder.repository; - -import lombok.NonNull; -import org.sadtech.autoresponder.entity.Unit; -import org.sadtech.autoresponder.entity.UnitPointer; - -import java.util.Optional; - -/** - * Интегрфейс для работы с хранилищем сущности {@link UnitPointer}. - * - * @author upagge [07/07/2019] - */ -public interface UnitPointerRepository { - - UnitPointer save(@NonNull UnitPointer unitPointer); - - /** - * @param entityId Идентификатор пользователя - * @return Объект с последним обработанным {@link Unit} для пользователя - */ - Optional> findByEntityId(@NonNull Long entityId); - - void removeByEntityId(@NonNull Long entityId); - -} diff --git a/src/main/java/org/sadtech/autoresponder/repository/UnitPointerRepositoryMap.java b/src/main/java/org/sadtech/autoresponder/repository/UnitPointerRepositoryMap.java deleted file mode 100644 index 021cdfd..0000000 --- a/src/main/java/org/sadtech/autoresponder/repository/UnitPointerRepositoryMap.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.sadtech.autoresponder.repository; - -import lombok.NonNull; -import org.sadtech.autoresponder.entity.Unit; -import org.sadtech.autoresponder.entity.UnitPointer; - -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - -/** - * Реализация хранилища для {@link UnitPointer} на основе Map. - * - * @author upagge [07/07/2019] - */ -public class UnitPointerRepositoryMap implements UnitPointerRepository { - - private Map> unitPointerMap = new HashMap<>(); - - @Override - public UnitPointer save(@NonNull UnitPointer unitPointer) { - unitPointerMap.put(unitPointer.getEntityId(), unitPointer); - return unitPointer; - } - - @Override - public Optional> findByEntityId(@NonNull Long entityId) { - return Optional.ofNullable(unitPointerMap.get(entityId)); - } - - @Override - public void removeByEntityId(@NonNull Long entityId) { - unitPointerMap.remove(entityId); - } - -} diff --git a/src/main/java/org/sadtech/autoresponder/service/UnitPointerService.java b/src/main/java/org/sadtech/autoresponder/service/UnitPointerService.java deleted file mode 100644 index 3089bd4..0000000 --- a/src/main/java/org/sadtech/autoresponder/service/UnitPointerService.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.sadtech.autoresponder.service; - -import lombok.NonNull; -import org.sadtech.autoresponder.entity.Unit; -import org.sadtech.autoresponder.entity.UnitPointer; - -import java.util.Optional; - -/** - * Сервис для взаимодействия с сущностью {@link UnitPointer}. - * - * @author upagge [07/07/2019] - */ -public interface UnitPointerService { - - void save(@NonNull UnitPointer unitPointer); - - Optional> getByEntityId(@NonNull Long entityId); - - void removeByEntityId(@NonNull Long entityId); - -} diff --git a/src/main/java/org/sadtech/autoresponder/service/UnitPointerServiceImpl.java b/src/main/java/org/sadtech/autoresponder/service/UnitPointerServiceImpl.java deleted file mode 100644 index 3248556..0000000 --- a/src/main/java/org/sadtech/autoresponder/service/UnitPointerServiceImpl.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.sadtech.autoresponder.service; - -import lombok.NonNull; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.sadtech.autoresponder.entity.Unit; -import org.sadtech.autoresponder.entity.UnitPointer; -import org.sadtech.autoresponder.repository.UnitPointerRepository; - -import java.util.Optional; - -@Slf4j -@RequiredArgsConstructor -public class UnitPointerServiceImpl implements UnitPointerService { - - private final UnitPointerRepository unitPointerRepository; - - @Override - public Optional> getByEntityId(@NonNull Long entityId) { - return unitPointerRepository.findByEntityId(entityId); - } - - @Override - public void removeByEntityId(@NonNull Long entityId) { - unitPointerRepository.removeByEntityId(entityId); - } - - @Override - public void save(@NonNull UnitPointer unitPointer) { - unitPointerRepository.save(unitPointer); - log.trace("Пользователь отправлен в репозиторий"); - } - -} diff --git a/src/main/java/org/sadtech/autoresponder/util/Description.java b/src/main/java/org/sadtech/autoresponder/util/Description.java deleted file mode 100644 index d374876..0000000 --- a/src/main/java/org/sadtech/autoresponder/util/Description.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.sadtech.autoresponder.util; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Служит для описания роли полей в классах. - * - * @author upagge [07/07/2019] - */ -@Target(ElementType.FIELD) -@Retention(RetentionPolicy.SOURCE) -public @interface Description { - - String value() default ""; - -} diff --git a/src/main/java/org/sadtech/autoresponder/util/Parser.java b/src/main/java/org/sadtech/autoresponder/util/Parser.java deleted file mode 100644 index 260da36..0000000 --- a/src/main/java/org/sadtech/autoresponder/util/Parser.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.sadtech.autoresponder.util; - -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; -import java.util.stream.Collectors; - -import static org.sadtech.autoresponder.util.Message.UTILITY_CLASS; - -/** - * Разбивает строку на множество слов, удаляя предлоги. - * - * @author upagge [07/07/2019] - */ -public class Parser { - - @Description("Множество предлогов") - private static final Set pretexts = Collections.unmodifiableSet( - new HashSet<>(Arrays.asList( - "в", "без", "до", "из", "к", "на", "по", "о", "от", "перед", "при", "с", "у", "за", "над", "об", - "под", "про", "для" - ))); - - private Parser() { - throw new IllegalStateException(UTILITY_CLASS); - } - - /** - * Метод по разбиению строки на множество слов. - * - * @param text Строка - * @return Множество слов - */ - public static Set parse(String text) { - String[] split = text.split("\\P{L}+"); - Set words = Arrays.stream(split).map(String::toLowerCase).collect(Collectors.toSet()); - words.removeAll(pretexts); - return words; - } - -} diff --git a/src/test/java/dev/struchkov/autoresponder/AutoResponderTest.java b/src/test/java/dev/struchkov/autoresponder/AutoResponderTest.java new file mode 100644 index 0000000..7231497 --- /dev/null +++ b/src/test/java/dev/struchkov/autoresponder/AutoResponderTest.java @@ -0,0 +1,143 @@ +package dev.struchkov.autoresponder; + +import dev.struchkov.autoresponder.repository.UnitPointerRepositoryMap; +import dev.struchkov.autoresponder.service.UnitPointerServiceImpl; +import dev.struchkov.autoresponder.test.TestUnit; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class AutoResponderTest { + + private AutoResponder autoresponder; + + @BeforeEach + public void setUp() { + final TestUnit dela = TestUnit.builder() + .keyWord("дела") + .keyWord("делишки") + .message("хорошо") + .build(); + + final TestUnit delaTop = TestUnit.builder() + .priority(100) + .keyWord("делишки") + .message("отлично") + .build(); + + final TestUnit hello = TestUnit.builder() + .keyWord("привет") + .message("тест") + .nextUnit(dela) + .nextUnit(delaTop) + .build(); + + + final TestUnit number = TestUnit.builder() + .keyWord("89101234567") + .message("ответ") + .build(); + + final TestUnit regExp = TestUnit.builder() + .pattern(Pattern.compile("^((8|\\+7)[\\- ]?)?(\\(?\\d{3}\\)?[\\- ]?)?[\\d\\- ]{7,10}$")) + .message("регулярка") + .build(); + dela.setNextUnits(Stream.of(regExp, number).collect(Collectors.toSet())); + + final Set strings = Stream.of("витамин", "мультифрукт", "арбуз", "параметр").collect(Collectors.toSet()); + + final TestUnit unreal = TestUnit.builder() + .keyWords(strings) + .message("победа") + .matchThreshold(100) + .build(); + + final Set testUnits = new HashSet<>(); + testUnits.add(hello); + testUnits.add(regExp); + testUnits.add(unreal); + + final UnitPointerRepositoryMap unitPointerRepository = new UnitPointerRepositoryMap<>(); + final UnitPointerServiceImpl unitPointerService = new UnitPointerServiceImpl<>(unitPointerRepository); + autoresponder = new AutoResponder<>(unitPointerService, testUnits); + } + + @Test + void simpleAnswer() { + final String message = autoresponder.answer(1L, "привет это тестирвоание функциональности").orElseThrow(NullPointerException::new).getMessage(); + assertEquals("тест", message); + final String message1 = autoresponder.answer(2L, "привет, еще одно тестирование").orElseThrow(NullPointerException::new).getMessage(); + assertEquals("тест", message1); + } + + @Test + void defaultAnswer() { + final TestUnit defaultUnit = TestUnit.builder().message("не знаю").build(); + autoresponder.setDefaultUnit(defaultUnit); + + assertEquals("не знаю", autoresponder.answer(2L, "пока").orElseThrow(NullPointerException::new).getMessage()); + } + + @Test + void notDefaultAnswer() { + assertEquals(Optional.empty(), autoresponder.answer(2L, "пока")); + } + + @Test + void regExpAnswer() { + final String message = autoresponder.answer(1L, "79101234567").orElseThrow(NullPointerException::new).getMessage(); + assertEquals("регулярка", message); + } + + @Test + void priorityAnswer() { + autoresponder.answer(1L, "привет"); + autoresponder.answer(2L, "привет"); + final String message = autoresponder.answer(1L, "как твои делишки").orElseThrow(NullPointerException::new).getMessage(); + assertEquals("отлично", message); + final String message1 = autoresponder.answer(2L, "твои дела все еще хорошо?").orElseThrow(NullPointerException::new).getMessage(); + assertEquals("хорошо", message1); + } + + @Test + void showRegExpVsKeyWords() { + autoresponder.answer(1L, "привет"); + autoresponder.answer(1L, "дела"); + assertEquals("регулярка", autoresponder.answer(1L, "89101234567").orElseThrow(NullPointerException::new).getMessage()); + } + + @Test + void matchThreshold() { + autoresponder.answer(1L, "витамин я сьем, и арбуз получу"); + final String message = "параметр себе задам: покушать витамин и арбуз, а вместе все это мультифрукт"; + final String answer = autoresponder.answer(1L, message).orElseThrow(NullPointerException::new).getMessage(); + assertEquals("победа", answer); + } + + @Test + void generalAnswer() { + TestUnit defaultUnit = TestUnit.builder().message("не знаю").build(); + autoresponder.setDefaultUnit(defaultUnit); + final String answer = autoresponder.answer(1L, "привет это тестирование функциональности").orElseThrow(NullPointerException::new).getMessage(); + assertEquals("тест", answer); + assertEquals("хорошо", autoresponder.answer(1L, "как твои дела").orElseThrow(NullPointerException::new).getMessage()); + final String answer2 = autoresponder.answer(2L, "привет это тестирование функциональности").orElseThrow(NullPointerException::new).getMessage(); + assertEquals("тест", answer2); + assertEquals("не знаю", autoresponder.answer(1L, "нет").orElseThrow(NullPointerException::new).getMessage()); + final String message = "параметр себе задам: покушать витамин и арбуз, а вместе все это мультифрукт"; + assertEquals("победа", autoresponder.answer(3L, message).orElseThrow(NullPointerException::new).getMessage()); + assertEquals("регулярка", autoresponder.answer(1L, "8912345678").orElseThrow(NullPointerException::new).getMessage()); + final String answer3 = autoresponder.answer(1L, "привет это тестирование функциональности").orElseThrow(NullPointerException::new).getMessage(); + assertEquals("тест", answer3); + } + + +} \ No newline at end of file diff --git a/src/test/java/dev/struchkov/autoresponder/test/TestUnit.java b/src/test/java/dev/struchkov/autoresponder/test/TestUnit.java new file mode 100644 index 0000000..b190b59 --- /dev/null +++ b/src/test/java/dev/struchkov/autoresponder/test/TestUnit.java @@ -0,0 +1,108 @@ +package dev.struchkov.autoresponder.test; + +import dev.struchkov.autoresponder.entity.Unit; + +import java.util.HashSet; +import java.util.Set; +import java.util.regex.Pattern; + +public class TestUnit extends Unit { + + private String message; + + public TestUnit(Set keyWords, + String phrase, + Pattern pattern, + Integer matchThreshold, + Integer priority, + Set nextUnits, + String message) { + super(keyWords, phrase, pattern, matchThreshold, priority, nextUnits); + this.message = message; + } + + private TestUnit(Builder builder) { + super(builder.keyWords, builder.phrase, builder.pattern, builder.matchThreshold, builder.priority, builder.nextUnits); + message = builder.message; + } + + public static Builder builder() { + return new Builder(); + } + + public String getMessage() { + return message; + } + + @Override + public String toString() { + return "TestUnit{" + + "keyWords=" + keyWords + + ", phrase='" + phrase + '\'' + + ", pattern=" + pattern + + ", matchThreshold=" + matchThreshold + + ", priority=" + priority + + ", message='" + message + '\'' + + '}'; + } + + + public static final class Builder { + private Set keyWords = new HashSet<>(); + private String phrase; + private Pattern pattern; + private Integer matchThreshold; + private Integer priority; + private Set nextUnits = new HashSet<>(); + private String message; + + public Builder keyWords(Set val) { + keyWords = val; + return this; + } + + public Builder keyWord(String val) { + keyWords.add(val); + return this; + } + + public Builder phrase(String val) { + phrase = val; + return this; + } + + public Builder pattern(Pattern val) { + pattern = val; + return this; + } + + public Builder matchThreshold(Integer val) { + matchThreshold = val; + return this; + } + + public Builder priority(Integer val) { + priority = val; + return this; + } + + public Builder nextUnits(Set val) { + nextUnits = val; + return this; + } + + public Builder nextUnit(TestUnit val) { + nextUnits.add(val); + return this; + } + + public Builder message(String val) { + message = val; + return this; + } + + public TestUnit build() { + return new TestUnit(this); + } + } +} diff --git a/src/test/java/org/sadtech/autoresponder/AutoResponderTest.java b/src/test/java/org/sadtech/autoresponder/AutoResponderTest.java deleted file mode 100644 index 67ad123..0000000 --- a/src/test/java/org/sadtech/autoresponder/AutoResponderTest.java +++ /dev/null @@ -1,141 +0,0 @@ -package org.sadtech.autoresponder; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.sadtech.autoresponder.repository.UnitPointerRepositoryMap; -import org.sadtech.autoresponder.service.UnitPointerServiceImpl; -import org.sadtech.autoresponder.test.TestUnit; - -import java.util.HashSet; -import java.util.Optional; -import java.util.Set; -import java.util.regex.Pattern; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -public class AutoResponderTest { - - private AutoResponder autoresponder; - - @Before - public void setUp() { - TestUnit dela = TestUnit.builder() - .keyWord("дела") - .keyWord("делишки") - .message("хорошо") - .build(); - - TestUnit delaTop = TestUnit.builder() - .priority(100) - .keyWord("делишки") - .message("отлично") - .build(); - - TestUnit hello = TestUnit.builder() - .keyWord("привет") - .message("тест") - .nextUnit(dela) - .nextUnit(delaTop) - .build(); - - - TestUnit number = TestUnit.builder() - .keyWord("89101234567") - .message("ответ") - .build(); - - TestUnit regExp = TestUnit.builder() - .pattern(Pattern.compile("^((8|\\+7)[\\- ]?)?(\\(?\\d{3}\\)?[\\- ]?)?[\\d\\- ]{7,10}$")) - .message("регулярка") - .build(); - dela.setNextUnits(Stream.of(regExp, number).collect(Collectors.toSet())); - - Set strings = Stream.of("витамин", "мультифрукт", "арбуз", "параметр").collect(Collectors.toSet()); - - TestUnit unreal = TestUnit.builder() - .keyWords(strings) - .message("победа") - .matchThreshold(100) - .build(); - - Set testUnits = new HashSet<>(); - testUnits.add(hello); - testUnits.add(regExp); - testUnits.add(unreal); - - UnitPointerServiceImpl unitPointerService = new UnitPointerServiceImpl<>(new UnitPointerRepositoryMap<>()); - autoresponder = new AutoResponder<>(unitPointerService, testUnits); - } - - @Test - public void simpleAnswer() { - String message = autoresponder.answer(1L, "привет это тестирвоание функциональности").orElseThrow(NullPointerException::new).getMessage(); - Assert.assertEquals("тест", message); - String message1 = autoresponder.answer(2L, "привет, еще одно тестирование").orElseThrow(NullPointerException::new).getMessage(); - Assert.assertEquals("тест", message1); - } - - @Test - public void defaultAnswer() { - TestUnit defaultUnit = TestUnit.builder().message("не знаю").build(); - autoresponder.setDefaultUnit(defaultUnit); - - Assert.assertEquals("не знаю", autoresponder.answer(2L, "пока").orElseThrow(NullPointerException::new).getMessage()); - } - - @Test - public void notDefaultAnswer() { - Assert.assertEquals(Optional.empty(), autoresponder.answer(2L, "пока")); - } - - @Test - public void regExpAnswer() { - String message = autoresponder.answer(1L, "79101234567").orElseThrow(NullPointerException::new).getMessage(); - Assert.assertEquals("регулярка", message); - } - - @Test - public void priorityAnswer() { - autoresponder.answer(1L, "привет"); - autoresponder.answer(2L, "привет"); - String message = autoresponder.answer(1L, "как твои делишки").orElseThrow(NullPointerException::new).getMessage(); - Assert.assertEquals("отлично", message); - String message1 = autoresponder.answer(2L, "твои дела все еще хорошо?").orElseThrow(NullPointerException::new).getMessage(); - Assert.assertEquals("хорошо", message1); - } - - @Test - public void showRegExpVsKeyWords() { - autoresponder.answer(1L, "привет"); - autoresponder.answer(1L, "дела"); - Assert.assertEquals("регулярка", autoresponder.answer(1L, "89101234567").orElseThrow(NullPointerException::new).getMessage()); - } - - @Test - public void matchThreshold() { - autoresponder.answer(1L, "витамин я сьем, и арбуз получу"); - String message = "параметр себе задам: покушать витамин и арбуз, а вместе все это мультифрукт"; - String answer = autoresponder.answer(1L, message).orElseThrow(NullPointerException::new).getMessage(); - Assert.assertEquals("победа", answer); - } - - @Test - public void generalAnswer() { - TestUnit defaultUnit = TestUnit.builder().message("не знаю").build(); - autoresponder.setDefaultUnit(defaultUnit); - String answer = autoresponder.answer(1L, "привет это тестирование функциональности").orElseThrow(NullPointerException::new).getMessage(); - Assert.assertEquals("тест", answer); - Assert.assertEquals("хорошо", autoresponder.answer(1L, "как твои дела").orElseThrow(NullPointerException::new).getMessage()); - String answer2 = autoresponder.answer(2L, "привет это тестирование функциональности").orElseThrow(NullPointerException::new).getMessage(); - Assert.assertEquals("тест", answer2); - Assert.assertEquals("не знаю", autoresponder.answer(1L, "нет").orElseThrow(NullPointerException::new).getMessage()); - String message = "параметр себе задам: покушать витамин и арбуз, а вместе все это мультифрукт"; - Assert.assertEquals("победа", autoresponder.answer(3L, message).orElseThrow(NullPointerException::new).getMessage()); - Assert.assertEquals("регулярка", autoresponder.answer(1L, "8912345678").orElseThrow(NullPointerException::new).getMessage()); - String answer3 = autoresponder.answer(1L, "привет это тестирование функциональности").orElseThrow(NullPointerException::new).getMessage(); - Assert.assertEquals("тест", answer3); - } - - -} \ No newline at end of file diff --git a/src/test/java/org/sadtech/autoresponder/test/TestUnit.java b/src/test/java/org/sadtech/autoresponder/test/TestUnit.java deleted file mode 100644 index ee14e9b..0000000 --- a/src/test/java/org/sadtech/autoresponder/test/TestUnit.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.sadtech.autoresponder.test; - -import lombok.Builder; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Singular; -import lombok.ToString; -import org.sadtech.autoresponder.entity.Unit; - -import java.util.Set; -import java.util.regex.Pattern; - -@Getter -@EqualsAndHashCode(callSuper = true) -@ToString -public class TestUnit extends Unit { - - private String message; - - @Builder - public TestUnit(@Singular Set keyWords, - String phrase, - Pattern pattern, - Integer matchThreshold, - Integer priority, - @Singular Set nextUnits, - String message) { - super(keyWords, phrase, pattern, matchThreshold, priority, nextUnits); - this.message = message; - } - -}