From af6acee6750b6c8e2be9e1de4c4f8ab7fbb33e0d Mon Sep 17 00:00:00 2001 From: upagge Date: Sun, 3 May 2020 19:52:44 +0300 Subject: [PATCH] =?UTF-8?q?=D0=BE=D0=B1=D1=89=D0=B8=D0=B9=20=D1=80=D0=B5?= =?UTF-8?q?=D1=84=D0=B0=D0=BA=D1=82=D0=BE=D1=80=D0=B8=D0=BD=D0=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 47 +++++++ pom.xml | 129 ++++++++++++++---- .../core/config/SocialJpaSpringConfig.java | 15 -- .../social/core/domain/content/Comment.java | 6 +- .../core/domain/content/EmptyMessage.java | 1 + .../social/core/domain/content/Message.java | 2 +- .../content/attachment/AudioMessage.java | 1 + .../content/attachment/GeoCoordinate.java | 1 + .../core/domain/keyboard/KeyBoardLine.java | 4 +- .../button/KeyBoardButtonAccount.java | 3 +- .../keyboard/button/KeyBoardButtonText.java | 3 +- .../core/exception/AccessException.java | 2 + .../core/exception/AppBotException.java | 9 -- .../core/exception/ConfigAppException.java | 2 + .../core/repository/AccountRepository.java | 9 +- .../core/repository/ContentRepository.java | 11 +- .../impl/jpa/AccountRepositoryJpaImpl.java | 19 +-- .../impl/jpa/MailRepositoryJpaImpl.java | 11 +- .../impl/local/AccountRepositoryMap.java | 33 ++--- .../impl/local/BoardCommentRepositoryMap.java | 50 ------- .../impl/local/MailRepositoryList.java | 17 +-- .../repository/jpa/AccountRepositoryJpa.java | 2 - .../repository/jpa/MailRepositoryJpa.java | 3 +- .../social/core/service/AccountService.java | 7 +- .../core/service/BoardCommentService.java | 6 - .../social/core/service/MessageService.java | 11 +- .../social/core/service/Modifiable.java | 3 +- .../core/service/impl/AccountServiceImpl.java | 33 +++-- .../service/impl/BoardCommentServiceImpl.java | 12 +- .../core/service/impl/MailServiceImpl.java | 8 +- .../service/sender/email/EmailSending.java | 1 + .../social/core/utils/ExceptionMessages.java | 3 +- .../social/core/utils/InsertWords.java | 9 +- .../social/core/utils/MessageUtils.java | 9 +- .../org/sadtech/social/core/utils/Sender.java | 5 + 35 files changed, 279 insertions(+), 208 deletions(-) create mode 100644 README.md delete mode 100644 src/main/java/org/sadtech/social/core/config/SocialJpaSpringConfig.java delete mode 100644 src/main/java/org/sadtech/social/core/repository/impl/local/BoardCommentRepositoryMap.java delete mode 100644 src/main/java/org/sadtech/social/core/service/BoardCommentService.java diff --git a/README.md b/README.md new file mode 100644 index 0000000..9949e10 --- /dev/null +++ b/README.md @@ -0,0 +1,47 @@ +# Social Core + +Набор классов для реализации абстрактных проектов для социальных сетей и месенджеров, без привязки к конкретным реализациям. + +## Общая информация + +Возьмем класс `Mail`, которые отвечает за сообщение. Это одновременно конкретный и абстрактный класс. Конкретный он, +потому что у него есть определенные поля и не предполагается его дальнешее расширение разработчиком, который использует +данную библиотеку. А абстрактный он, потому что не предполагает привязки к какой-либо социальной сети. + +Это может быть сообщение во ВКонтакте или Telegram, на данном уровне абстракции это не важно. Из таких обобщенных +сущностей, а так же сервисов и репозиториев к ним и состоит библиотека. + +Все сущности имеют свой сервис и репозиторий для сохранения. Так же реализована JPA версия репозиториев. + +## Примеры использований + +1. [Social Bot](https://github.com/uPagge/social-bot) - Абстрактный SDK для бота под любую социальную сеть и мессенджер. + +## Пакеты проекта + +- domain - доменные сущности проекта. Например, сообщение пользователя, комментарий к фотографии, сообщение в беседе. + - content + - attachment - вложения к сообщениям пользователя. Прикрепленная фотография, или аудио, или голосовое сообщение. + - keyboard - сущности для реализации клавиаутры + - button - кнопки клавиатуры разных типов +- exception - классы для объектов исключений +- repository - интерфейсы репозиториев для доменных сущностей + - impl - реализации интерфейсов + - local - Реализация на какой-либо колекции Java (Map, List и т.к.) + - jpa - Реализация для сохранения в БД. + - jpa - Интерфейсы для работы с Spring Jpa +- service - интерфейсы сервисов для доменных сущностей + - impl - реализации интерфейсов + - sender - реализации интерфейса `Sending` +- utils - прочие классы утилиты + +## Dependency + +``` + + org.sadtech.social + social-bot + 0.6.3-RELEASE + +``` + diff --git a/pom.xml b/pom.xml index 030d9ff..d99aeb0 100644 --- a/pom.xml +++ b/pom.xml @@ -9,22 +9,28 @@ 0.6.3-SNAPSHOT jar - - - - org.apache.maven.plugins - maven-compiler-plugin - - 8 - 8 - - - - + Social Core + + Набор классов для реализации абстрактных проектов для социальных сетей и месенджеров, без привязки к конкретным + сервисам. + + https://github.com/uPagge/social-core + + + scm:git:https://github.com/uPagge/social-core.git + https://github.com/uPagge/social-core + scm:git:https://github.com/uPagge/social-core.git + + + + + ossrh + https://oss.sonatype.org/content/repositories/snapshots + + 2.8.5 - 1.7.29 1.4 1.18.10 2.1.3.RELEASE @@ -39,12 +45,6 @@ ${gson.ver} - - org.slf4j - slf4j-api - ${slf4j.ver} - - javax.mail mail @@ -71,13 +71,93 @@ validation-api ${validation.api.ver} - - org.springframework.boot - spring-boot-autoconfigure - 2.1.3.RELEASE - + + + 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 + + 8 + 8 + + + + + uPagge @@ -87,5 +167,4 @@ - \ No newline at end of file diff --git a/src/main/java/org/sadtech/social/core/config/SocialJpaSpringConfig.java b/src/main/java/org/sadtech/social/core/config/SocialJpaSpringConfig.java deleted file mode 100644 index ebf6709..0000000 --- a/src/main/java/org/sadtech/social/core/config/SocialJpaSpringConfig.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.sadtech.social.core.config; - -import org.springframework.boot.autoconfigure.domain.EntityScan; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; - -/** - * Конфигуратор для использования в {@link org.springframework.context.annotation.Import}. - * - * @author upagge [28/07/2019] - */ -@EnableJpaRepositories(basePackages = "org.sadtech.social.core.repository.jpa") -@EntityScan(basePackages = "org.sadtech.social.core.domain") -public class SocialJpaSpringConfig { - -} diff --git a/src/main/java/org/sadtech/social/core/domain/content/Comment.java b/src/main/java/org/sadtech/social/core/domain/content/Comment.java index db00e88..e614b63 100644 --- a/src/main/java/org/sadtech/social/core/domain/content/Comment.java +++ b/src/main/java/org/sadtech/social/core/domain/content/Comment.java @@ -1,7 +1,8 @@ package org.sadtech.social.core.domain.content; -import lombok.Data; import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; import org.sadtech.social.core.utils.Description; /** @@ -9,8 +10,9 @@ import org.sadtech.social.core.utils.Description; * * @author upagge [08/07/2019] */ +@Getter +@Setter @EqualsAndHashCode(callSuper = true) -@Data public abstract class Comment extends Message { @Description("Идентификатор контента, к которому ставлено сообщение") diff --git a/src/main/java/org/sadtech/social/core/domain/content/EmptyMessage.java b/src/main/java/org/sadtech/social/core/domain/content/EmptyMessage.java index d628827..d00c8fa 100644 --- a/src/main/java/org/sadtech/social/core/domain/content/EmptyMessage.java +++ b/src/main/java/org/sadtech/social/core/domain/content/EmptyMessage.java @@ -24,4 +24,5 @@ public class EmptyMessage extends Message { public void setText(String text) { throw new AppBotException("EmptyMessage no setText"); } + } diff --git a/src/main/java/org/sadtech/social/core/domain/content/Message.java b/src/main/java/org/sadtech/social/core/domain/content/Message.java index eb3a322..012b6d8 100644 --- a/src/main/java/org/sadtech/social/core/domain/content/Message.java +++ b/src/main/java/org/sadtech/social/core/domain/content/Message.java @@ -13,7 +13,7 @@ import javax.validation.constraints.NotNull; import java.time.LocalDateTime; /** - * Аьстрактная сущность - Сообщение от пользователя. + * Абстрактная сущность - Сообщение от пользователя. * * @author upagge [08/07/2019] */ diff --git a/src/main/java/org/sadtech/social/core/domain/content/attachment/AudioMessage.java b/src/main/java/org/sadtech/social/core/domain/content/attachment/AudioMessage.java index 419fe82..a2c3f18 100644 --- a/src/main/java/org/sadtech/social/core/domain/content/attachment/AudioMessage.java +++ b/src/main/java/org/sadtech/social/core/domain/content/attachment/AudioMessage.java @@ -26,4 +26,5 @@ public class AudioMessage extends Attachment { public AudioMessage() { type = AttachmentType.AUDIO_MESSAGE; } + } diff --git a/src/main/java/org/sadtech/social/core/domain/content/attachment/GeoCoordinate.java b/src/main/java/org/sadtech/social/core/domain/content/attachment/GeoCoordinate.java index afdfada..9c1c3b5 100644 --- a/src/main/java/org/sadtech/social/core/domain/content/attachment/GeoCoordinate.java +++ b/src/main/java/org/sadtech/social/core/domain/content/attachment/GeoCoordinate.java @@ -15,6 +15,7 @@ public class GeoCoordinate { @Description("Широта") private Float latitude; + @Description("Долгота") private Float longitude; diff --git a/src/main/java/org/sadtech/social/core/domain/keyboard/KeyBoardLine.java b/src/main/java/org/sadtech/social/core/domain/keyboard/KeyBoardLine.java index 6a0867f..85677fe 100644 --- a/src/main/java/org/sadtech/social/core/domain/keyboard/KeyBoardLine.java +++ b/src/main/java/org/sadtech/social/core/domain/keyboard/KeyBoardLine.java @@ -15,10 +15,10 @@ import java.util.List; * * @author upagge [08/07/2019] */ -@Builder @Getter -@EqualsAndHashCode +@Builder @ToString +@EqualsAndHashCode public class KeyBoardLine { @Description("Кнопки в строке") diff --git a/src/main/java/org/sadtech/social/core/domain/keyboard/button/KeyBoardButtonAccount.java b/src/main/java/org/sadtech/social/core/domain/keyboard/button/KeyBoardButtonAccount.java index bb784e2..221ea0a 100644 --- a/src/main/java/org/sadtech/social/core/domain/keyboard/button/KeyBoardButtonAccount.java +++ b/src/main/java/org/sadtech/social/core/domain/keyboard/button/KeyBoardButtonAccount.java @@ -14,8 +14,8 @@ import org.sadtech.social.core.utils.Description; * @author upagge [08/07/2019] */ @Getter -@EqualsAndHashCode(callSuper = true) @ToString +@EqualsAndHashCode(callSuper = true) public class KeyBoardButtonAccount extends KeyBoardButton { @Description("Сумма к оплате") @@ -34,4 +34,5 @@ public class KeyBoardButtonAccount extends KeyBoardButton { this.accountId = accountId; this.description = description; } + } diff --git a/src/main/java/org/sadtech/social/core/domain/keyboard/button/KeyBoardButtonText.java b/src/main/java/org/sadtech/social/core/domain/keyboard/button/KeyBoardButtonText.java index 3a0fb29..428cb3a 100644 --- a/src/main/java/org/sadtech/social/core/domain/keyboard/button/KeyBoardButtonText.java +++ b/src/main/java/org/sadtech/social/core/domain/keyboard/button/KeyBoardButtonText.java @@ -10,8 +10,8 @@ import org.sadtech.social.core.domain.keyboard.KeyBoardButton; import org.sadtech.social.core.utils.Description; @Getter -@EqualsAndHashCode(callSuper = true) @ToString +@EqualsAndHashCode(callSuper = true) public class KeyBoardButtonText extends KeyBoardButton { @Description("Надпись на кнопке") @@ -30,4 +30,5 @@ public class KeyBoardButtonText extends KeyBoardButton { public static KeyBoardButtonText of(String label) { return KeyBoardButtonText.builder().label(label).build(); } + } diff --git a/src/main/java/org/sadtech/social/core/exception/AccessException.java b/src/main/java/org/sadtech/social/core/exception/AccessException.java index ddf55ed..16f1515 100644 --- a/src/main/java/org/sadtech/social/core/exception/AccessException.java +++ b/src/main/java/org/sadtech/social/core/exception/AccessException.java @@ -6,7 +6,9 @@ package org.sadtech.social.core.exception; * @author upagge [08/07/2019] */ public class AccessException extends AppBotException { + public AccessException(String message) { super(message); } + } diff --git a/src/main/java/org/sadtech/social/core/exception/AppBotException.java b/src/main/java/org/sadtech/social/core/exception/AppBotException.java index 4e2bb04..93d04ba 100644 --- a/src/main/java/org/sadtech/social/core/exception/AppBotException.java +++ b/src/main/java/org/sadtech/social/core/exception/AppBotException.java @@ -11,17 +11,11 @@ public class AppBotException extends RuntimeException { private static final String TYPE = "ERROR"; private final LocalDateTime timeError = LocalDateTime.now(); - protected String description; public AppBotException(String message) { super(message); } - public AppBotException(String message, String description) { - super(message); - this.description = description; - } - public String getType() { return TYPE; } @@ -30,7 +24,4 @@ public class AppBotException extends RuntimeException { return timeError; } - public String getDescription() { - return description; - } } diff --git a/src/main/java/org/sadtech/social/core/exception/ConfigAppException.java b/src/main/java/org/sadtech/social/core/exception/ConfigAppException.java index e39e11c..bdd2cca 100644 --- a/src/main/java/org/sadtech/social/core/exception/ConfigAppException.java +++ b/src/main/java/org/sadtech/social/core/exception/ConfigAppException.java @@ -6,7 +6,9 @@ package org.sadtech.social.core.exception; * @author upagge [11/07/2019] */ public class ConfigAppException extends AppBotException { + public ConfigAppException(String message) { super(message); } + } diff --git a/src/main/java/org/sadtech/social/core/repository/AccountRepository.java b/src/main/java/org/sadtech/social/core/repository/AccountRepository.java index 68386ec..7da2cc9 100644 --- a/src/main/java/org/sadtech/social/core/repository/AccountRepository.java +++ b/src/main/java/org/sadtech/social/core/repository/AccountRepository.java @@ -1,7 +1,10 @@ package org.sadtech.social.core.repository; +import lombok.NonNull; import org.sadtech.social.core.domain.money.Account; +import java.util.Optional; + /** * Репозиторий для взаимодействия с хранилищем счетов {@link Account}. * @@ -9,10 +12,10 @@ import org.sadtech.social.core.domain.money.Account; */ public interface AccountRepository { - Integer add(Account account); + Account save(@NonNull Account account); - void edit(Integer accountId, Account account); + Optional findById(@NonNull Integer accountId); - Account findById(Integer accountId); + boolean existsById(Integer id); } diff --git a/src/main/java/org/sadtech/social/core/repository/ContentRepository.java b/src/main/java/org/sadtech/social/core/repository/ContentRepository.java index 1cfc585..636afb4 100644 --- a/src/main/java/org/sadtech/social/core/repository/ContentRepository.java +++ b/src/main/java/org/sadtech/social/core/repository/ContentRepository.java @@ -1,5 +1,6 @@ package org.sadtech.social.core.repository; +import lombok.NonNull; import org.sadtech.social.core.domain.content.Message; import java.time.LocalDateTime; @@ -18,17 +19,17 @@ public interface ContentRepository { * @param content Объект сообщени * @return Идентификатор сообщения в хранилище */ - T add(T content); + T add(@NonNull T content); /** * Получить все сообщения за определенный временной диапазон * - * @param timeFrom Начало временного диапазона - * @param timeTo Конец диапазона + * @param dateFrom Начало временного диапазона + * @param dateTo Конец диапазона * @return Список сообщений */ - List betweenByCreateDateTime(LocalDateTime timeFrom, LocalDateTime timeTo); + List betweenByCreateDateTime(@NonNull LocalDateTime dateFrom, @NonNull LocalDateTime dateTo); - List betweenByAddDateTime(LocalDateTime from, LocalDateTime to); + List betweenByAddDateTime(@NonNull LocalDateTime dateFrom, @NonNull LocalDateTime dateTo); } diff --git a/src/main/java/org/sadtech/social/core/repository/impl/jpa/AccountRepositoryJpaImpl.java b/src/main/java/org/sadtech/social/core/repository/impl/jpa/AccountRepositoryJpaImpl.java index e1fb171..1cae137 100644 --- a/src/main/java/org/sadtech/social/core/repository/impl/jpa/AccountRepositoryJpaImpl.java +++ b/src/main/java/org/sadtech/social/core/repository/impl/jpa/AccountRepositoryJpaImpl.java @@ -1,13 +1,14 @@ package org.sadtech.social.core.repository.impl.jpa; +import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.sadtech.social.core.domain.money.Account; import org.sadtech.social.core.repository.AccountRepository; import org.sadtech.social.core.repository.jpa.AccountRepositoryJpa; +import java.util.Optional; + /** - * TODO: Добавить описание класса. - * * @author upagge [27/07/2019] */ @RequiredArgsConstructor @@ -16,18 +17,18 @@ public class AccountRepositoryJpaImpl implements AccountRepository { private final AccountRepositoryJpa accountRepositoryJpa; @Override - public Integer add(Account account) { - return accountRepositoryJpa.saveAndFlush(account).getId(); + public Account save(@NonNull Account account) { + return accountRepositoryJpa.save(account); } @Override - public void edit(Integer accountId, Account account) { - account.setId(accountId); - accountRepositoryJpa.saveAndFlush(account); + public Optional findById(@NonNull Integer accountId) { + return accountRepositoryJpa.findById(accountId); } @Override - public Account findById(Integer accountId) { - return accountRepositoryJpa.getOne(accountId); + public boolean existsById(Integer id) { + return accountRepositoryJpa.existsById(id); } + } diff --git a/src/main/java/org/sadtech/social/core/repository/impl/jpa/MailRepositoryJpaImpl.java b/src/main/java/org/sadtech/social/core/repository/impl/jpa/MailRepositoryJpaImpl.java index 3379725..833751f 100644 --- a/src/main/java/org/sadtech/social/core/repository/impl/jpa/MailRepositoryJpaImpl.java +++ b/src/main/java/org/sadtech/social/core/repository/impl/jpa/MailRepositoryJpaImpl.java @@ -1,5 +1,6 @@ package org.sadtech.social.core.repository.impl.jpa; +import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.sadtech.social.core.domain.content.Mail; import org.sadtech.social.core.repository.ContentRepository; @@ -19,18 +20,18 @@ public class MailRepositoryJpaImpl implements ContentRepository { private final MailRepositoryJpa mailRepositoryJpa; @Override - public Mail add(Mail content) { + public Mail add(@NonNull Mail content) { return mailRepositoryJpa.saveAndFlush(content); } @Override - public List betweenByCreateDateTime(LocalDateTime timeFrom, LocalDateTime timeTo) { - return mailRepositoryJpa.findByCreateDateBetween(timeFrom, timeTo); + public List betweenByCreateDateTime(@NonNull LocalDateTime dateFrom, @NonNull LocalDateTime dateTo) { + return mailRepositoryJpa.findByCreateDateBetween(dateFrom, dateTo); } @Override - public List betweenByAddDateTime(LocalDateTime from, LocalDateTime to) { - return mailRepositoryJpa.findByAddDateBetween(from, to); + public List betweenByAddDateTime(@NonNull LocalDateTime dateFrom, @NonNull LocalDateTime dateTo) { + return mailRepositoryJpa.findByAddDateBetween(dateFrom, dateTo); } } diff --git a/src/main/java/org/sadtech/social/core/repository/impl/local/AccountRepositoryMap.java b/src/main/java/org/sadtech/social/core/repository/impl/local/AccountRepositoryMap.java index d495aa6..3cabae2 100644 --- a/src/main/java/org/sadtech/social/core/repository/impl/local/AccountRepositoryMap.java +++ b/src/main/java/org/sadtech/social/core/repository/impl/local/AccountRepositoryMap.java @@ -1,9 +1,7 @@ package org.sadtech.social.core.repository.impl.local; +import lombok.NonNull; import org.sadtech.social.core.domain.money.Account; -import org.sadtech.social.core.exception.AccessException; -import org.sadtech.social.core.exception.NotFoundException; -import org.sadtech.social.core.exception.PaymentException; import org.sadtech.social.core.repository.AccountRepository; import java.util.HashMap; @@ -13,36 +11,25 @@ import java.util.Optional; public class AccountRepositoryMap implements AccountRepository { private final Map saveMap = new HashMap<>(); - private Integer id = 1; + private int id = 1; @Override - public Integer add(Account account) { - if (check(account.getId())) { + public Account save(@NonNull Account account) { + if (existsById(account.getId())) { account.setId(id); - saveMap.put(id, account); - return id++; + return saveMap.put(id++, account); } else { - throw new AccessException("Счет " + account.getId() + " уже существует"); - } - - } - - @Override - public void edit(Integer accountId, Account account) { - if (check(id)) { - account.setId(accountId); - saveMap.put(accountId, account); - } else { - throw new NotFoundException("Счет " + accountId + " не найден"); + return saveMap.put(id, account); } } @Override - public Account findById(Integer accountId) { - return Optional.ofNullable(saveMap.get(accountId)).orElseThrow(() -> new PaymentException("Счет " + accountId + " не найден")); + public Optional findById(@NonNull Integer accountId) { + return Optional.ofNullable(saveMap.get(accountId)); } - private boolean check(Integer id) { + public boolean existsById(Integer id) { return !saveMap.containsKey(id); } + } diff --git a/src/main/java/org/sadtech/social/core/repository/impl/local/BoardCommentRepositoryMap.java b/src/main/java/org/sadtech/social/core/repository/impl/local/BoardCommentRepositoryMap.java deleted file mode 100644 index 3a97de7..0000000 --- a/src/main/java/org/sadtech/social/core/repository/impl/local/BoardCommentRepositoryMap.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.sadtech.social.core.repository.impl.local; - -import org.sadtech.social.core.domain.content.BoardComment; -import org.sadtech.social.core.repository.ContentRepository; - -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class BoardCommentRepositoryMap implements ContentRepository { - - private final Map saveMap = new HashMap<>(); - private Long count = 0L; - - @Override - public BoardComment add(BoardComment comment) { - comment.setId(count); - saveMap.put(count++, comment); - return comment; - } - - @Override - public List betweenByCreateDateTime(LocalDateTime timeFrom, LocalDateTime timeTo) { - ArrayList rezultMails = new ArrayList<>(); - for (int i = saveMap.size() - 1; i >= 0; i--) { - if (!(saveMap.get(i).getCreateDate().isBefore(timeFrom) || saveMap.get(i).getCreateDate().isAfter(timeTo)) && saveMap.get(i).getCreateDate().equals(timeFrom)) { - rezultMails.add(this.saveMap.get(i)); - } else if (saveMap.get(i).getCreateDate().isBefore(timeFrom)) { - break; - } - } - return rezultMails; - } - - @Override - public List betweenByAddDateTime(LocalDateTime from, LocalDateTime to) { - ArrayList rezultMails = new ArrayList<>(); - for (int i = saveMap.size() - 1; i >= 0; i--) { - if (!(saveMap.get(i).getAddDate().isBefore(from) || saveMap.get(i).getAddDate().isAfter(to)) && saveMap.get(i).getAddDate().equals(from)) { - rezultMails.add(this.saveMap.get(i)); - } else if (saveMap.get(i).getCreateDate().isBefore(to)) { - break; - } - } - return rezultMails; - } - -} diff --git a/src/main/java/org/sadtech/social/core/repository/impl/local/MailRepositoryList.java b/src/main/java/org/sadtech/social/core/repository/impl/local/MailRepositoryList.java index b3aaf2f..3dd9d6f 100644 --- a/src/main/java/org/sadtech/social/core/repository/impl/local/MailRepositoryList.java +++ b/src/main/java/org/sadtech/social/core/repository/impl/local/MailRepositoryList.java @@ -1,5 +1,6 @@ package org.sadtech.social.core.repository.impl.local; +import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import org.sadtech.social.core.domain.content.Mail; import org.sadtech.social.core.repository.ContentRepository; @@ -27,13 +28,13 @@ public class MailRepositoryList implements ContentRepository { } @Override - public List betweenByCreateDateTime(LocalDateTime from, LocalDateTime to) { + public List betweenByCreateDateTime(@NonNull LocalDateTime dateFrom, @NonNull LocalDateTime dateTo) { ArrayList rezultMails = new ArrayList<>(); for (int i = mails.size() - 1; i >= 0; i--) { Mail mail = mails.get(i); - if (isTimePeriod(from, to, mail.getAddDate())) { + if (isTimePeriod(dateFrom, dateTo, mail.getAddDate())) { rezultMails.add(mail); - } else if (mail.getCreateDate().isBefore(from)) { + } else if (mail.getCreateDate().isBefore(dateFrom)) { break; } } @@ -41,22 +42,22 @@ public class MailRepositoryList implements ContentRepository { } @Override - public List betweenByAddDateTime(LocalDateTime from, LocalDateTime to) { + public List betweenByAddDateTime(@NonNull LocalDateTime dateFrom, @NonNull LocalDateTime dateTo) { ArrayList rezultMails = new ArrayList<>(); for (int i = mails.size() - 1; i >= 0; i--) { Mail mail = mails.get(i); LocalDateTime addDate = mail.getAddDate(); - if (isTimePeriod(from, to, addDate)) { + if (isTimePeriod(dateFrom, dateTo, addDate)) { rezultMails.add(mail); - } else if (addDate.isBefore(from)) { + } else if (addDate.isBefore(dateFrom)) { break; } } return rezultMails; } - private boolean isTimePeriod(LocalDateTime from, LocalDateTime to, LocalDateTime dateTime) { - return from.isBefore(dateTime) && to.isAfter(dateTime); + private boolean isTimePeriod(@NonNull LocalDateTime dateFrom, @NonNull LocalDateTime dateTo, @NonNull LocalDateTime dateTime) { + return dateFrom.isBefore(dateTime) && dateTo.isAfter(dateTime); } diff --git a/src/main/java/org/sadtech/social/core/repository/jpa/AccountRepositoryJpa.java b/src/main/java/org/sadtech/social/core/repository/jpa/AccountRepositoryJpa.java index b1e08e2..919ea31 100644 --- a/src/main/java/org/sadtech/social/core/repository/jpa/AccountRepositoryJpa.java +++ b/src/main/java/org/sadtech/social/core/repository/jpa/AccountRepositoryJpa.java @@ -5,8 +5,6 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** - * TODO: Добавить описание интерфейса. - * * @author upagge [27/07/2019] */ @Repository diff --git a/src/main/java/org/sadtech/social/core/repository/jpa/MailRepositoryJpa.java b/src/main/java/org/sadtech/social/core/repository/jpa/MailRepositoryJpa.java index 57b6715..dc93f80 100644 --- a/src/main/java/org/sadtech/social/core/repository/jpa/MailRepositoryJpa.java +++ b/src/main/java/org/sadtech/social/core/repository/jpa/MailRepositoryJpa.java @@ -1,6 +1,7 @@ package org.sadtech.social.core.repository.jpa; import org.sadtech.social.core.domain.content.Mail; +import org.sadtech.social.core.repository.impl.jpa.MailRepositoryJpaImpl; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @@ -9,7 +10,7 @@ import java.util.List; /** * Интерфейс JPA репозитория для сущности {@link Mail}. При этом сам не является репозиторием, а подставляется в - * {@link org.sadtech.social.core.repository.impl.jpa.MailRepositoryJpaImpl} + * {@link MailRepositoryJpaImpl} * * @author upagge [27/07/2019] */ diff --git a/src/main/java/org/sadtech/social/core/service/AccountService.java b/src/main/java/org/sadtech/social/core/service/AccountService.java index f6594de..f840405 100644 --- a/src/main/java/org/sadtech/social/core/service/AccountService.java +++ b/src/main/java/org/sadtech/social/core/service/AccountService.java @@ -1,5 +1,6 @@ package org.sadtech.social.core.service; +import lombok.NonNull; import org.sadtech.social.core.domain.money.Account; /** @@ -9,7 +10,7 @@ import org.sadtech.social.core.domain.money.Account; */ public interface AccountService { - Integer add(Account account); + Account add(@NonNull Account account); /** * Метод для оплаты счета @@ -19,7 +20,7 @@ public interface AccountService { * @param sum Сумма оплаты * @return true - в случае успешной оплаты */ - Boolean pay(Integer accountId, Integer extinguishedPersonId, Integer sum); + boolean pay(@NonNull Integer accountId, @NonNull Integer extinguishedPersonId, @NonNull Integer sum); /** * Проверка оплаты счета @@ -27,6 +28,6 @@ public interface AccountService { * @param accountId Идентификатор счета * @return true - если счет оплачен */ - Boolean paymentVerification(Integer accountId); + boolean paymentVerification(@NonNull Integer accountId); } diff --git a/src/main/java/org/sadtech/social/core/service/BoardCommentService.java b/src/main/java/org/sadtech/social/core/service/BoardCommentService.java deleted file mode 100644 index ad0800f..0000000 --- a/src/main/java/org/sadtech/social/core/service/BoardCommentService.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.sadtech.social.core.service; - -import org.sadtech.social.core.domain.content.BoardComment; - -public interface BoardCommentService extends MessageService { -} diff --git a/src/main/java/org/sadtech/social/core/service/MessageService.java b/src/main/java/org/sadtech/social/core/service/MessageService.java index faf5125..9ed2deb 100644 --- a/src/main/java/org/sadtech/social/core/service/MessageService.java +++ b/src/main/java/org/sadtech/social/core/service/MessageService.java @@ -1,18 +1,19 @@ package org.sadtech.social.core.service; +import lombok.NonNull; import org.sadtech.social.core.domain.content.Message; import java.time.LocalDateTime; import java.util.List; /** - * Интерфейс взаимодйствия с наследниками текстовых запросов пользователей. + * Интерфейс взаимодйствия с наследниками текстовых сообщений пользователей. * * @author upagge [08/07/2019] */ public interface MessageService { - void add(T event); + void add(@NonNull T event); /** * Получить список сообщений за заданный временной интервал @@ -21,7 +22,7 @@ public interface MessageService { * @param timeTo Конец интервала * @return Список сообщений */ - List getByAddDateTime(LocalDateTime timeFrom, LocalDateTime timeTo); + List getByAddDateTime(@NonNull LocalDateTime timeFrom, @NonNull LocalDateTime timeTo); /** * Получить список ПОСЛЕДНИХ сообщений для каждого пользователя за заданных временной интервал @@ -30,9 +31,9 @@ public interface MessageService { * @param timeTo Конец интервала * @return Список сообщений */ - List getLastEventByCreateDateTime(LocalDateTime timeFrom, LocalDateTime timeTo); + List getLastEventByCreateDateTime(@NonNull LocalDateTime timeFrom, @NonNull LocalDateTime timeTo); - List getLastEventByAddDateTime(LocalDateTime timeFrom, LocalDateTime timeTo); + List getLastEventByAddDateTime(@NonNull LocalDateTime timeFrom, @NonNull LocalDateTime timeTo); /** * Возвращает новые сообщения от последнего запроса. diff --git a/src/main/java/org/sadtech/social/core/service/Modifiable.java b/src/main/java/org/sadtech/social/core/service/Modifiable.java index b60caec..dc52b10 100644 --- a/src/main/java/org/sadtech/social/core/service/Modifiable.java +++ b/src/main/java/org/sadtech/social/core/service/Modifiable.java @@ -1,5 +1,6 @@ package org.sadtech.social.core.service; +import lombok.NonNull; import org.sadtech.social.core.domain.content.Message; /** @@ -11,6 +12,6 @@ import org.sadtech.social.core.domain.content.Message; @FunctionalInterface public interface Modifiable { - void change(T content); + void change(@NonNull T content); } diff --git a/src/main/java/org/sadtech/social/core/service/impl/AccountServiceImpl.java b/src/main/java/org/sadtech/social/core/service/impl/AccountServiceImpl.java index 0789326..c291aae 100644 --- a/src/main/java/org/sadtech/social/core/service/impl/AccountServiceImpl.java +++ b/src/main/java/org/sadtech/social/core/service/impl/AccountServiceImpl.java @@ -1,8 +1,11 @@ package org.sadtech.social.core.service.impl; +import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.sadtech.social.core.domain.money.Account; import org.sadtech.social.core.domain.money.AccountStatus; +import org.sadtech.social.core.exception.AccessException; +import org.sadtech.social.core.exception.NotFoundException; import org.sadtech.social.core.exception.PaymentException; import org.sadtech.social.core.repository.AccountRepository; import org.sadtech.social.core.service.AccountService; @@ -13,22 +16,27 @@ public class AccountServiceImpl implements AccountService { private final AccountRepository accountRepository; @Override - public Integer add(Account account) { - account.setAccountStatus(AccountStatus.EXPOSED); - return accountRepository.add(account); + public Account add(@NonNull Account account) { + if (accountRepository.existsById(account.getId())) { + account.setAccountStatus(AccountStatus.EXPOSED); + return accountRepository.save(account); + } else { + throw new AccessException("Счет " + account.getId() + " уже присутствует в базе"); + } } @Override - public Boolean pay(Integer accountId, Integer extinguishedPersonId, Integer sum) { - Account account = accountRepository.findById(accountId); + public boolean pay(@NonNull Integer accountId, @NonNull Integer extinguishedPersonId, @NonNull Integer sum) { + Account account = accountRepository.findById(accountId) + .orElseThrow(() -> new NotFoundException("Счет " + accountId + " не найден")); if (validStatus(account.getAccountStatus())) { if (account.getTotalSum().equals(sum)) { account.setAccountStatus(AccountStatus.CLOSED); account.setExtinguishedPersonId(extinguishedPersonId); - accountRepository.edit(accountId, account); + accountRepository.save(account); } else { account.setAccountStatus(AccountStatus.EXCEPTION); - accountRepository.edit(accountId, account); + accountRepository.save(account); throw new PaymentException("Неверная сумма"); } } else { @@ -37,12 +45,17 @@ public class AccountServiceImpl implements AccountService { return true; } - private boolean validStatus(AccountStatus accountStatus) { + private boolean validStatus(@NonNull AccountStatus accountStatus) { return AccountStatus.EXCEPTION.equals(accountStatus) || AccountStatus.EXPOSED.equals(accountStatus); } @Override - public Boolean paymentVerification(Integer accountId) { - return AccountStatus.CLOSED.equals(accountRepository.findById(accountId).getAccountStatus()); + public boolean paymentVerification(@NonNull Integer accountId) { + return AccountStatus.CLOSED.equals( + accountRepository.findById(accountId) + .orElseThrow(() -> new NotFoundException("Счет " + accountId + " не найден")) + .getAccountStatus() + ); } + } diff --git a/src/main/java/org/sadtech/social/core/service/impl/BoardCommentServiceImpl.java b/src/main/java/org/sadtech/social/core/service/impl/BoardCommentServiceImpl.java index 1d98beb..cdede63 100644 --- a/src/main/java/org/sadtech/social/core/service/impl/BoardCommentServiceImpl.java +++ b/src/main/java/org/sadtech/social/core/service/impl/BoardCommentServiceImpl.java @@ -4,7 +4,7 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.sadtech.social.core.domain.content.BoardComment; import org.sadtech.social.core.repository.ContentRepository; -import org.sadtech.social.core.service.BoardCommentService; +import org.sadtech.social.core.service.MessageService; import java.time.LocalDateTime; import java.util.ArrayList; @@ -14,7 +14,7 @@ import java.util.Set; @Slf4j @RequiredArgsConstructor -public class BoardCommentServiceImpl implements BoardCommentService { +public class BoardCommentServiceImpl implements MessageService { private final ContentRepository commentRepository; @@ -25,26 +25,26 @@ public class BoardCommentServiceImpl implements BoardCommentService { @Override public List getByAddDateTime(LocalDateTime timeFrom, LocalDateTime timeTo) { - return null; + throw new IllegalStateException("Не реализовано"); } @Override public List getLastEventByCreateDateTime(LocalDateTime timeFrom, LocalDateTime timeTo) { - log.info("Запрошены последние комментарии к обсуждению {} - {} ", timeFrom, timeTo); + log.trace("Запрошены последние комментарии к обсуждению {} - {} ", timeFrom, timeTo); List mails = commentRepository.betweenByCreateDateTime(timeFrom, timeTo); return getBoardComments(mails); } @Override public List getLastEventByAddDateTime(LocalDateTime timeFrom, LocalDateTime timeTo) { - log.info("Запрошены последние комментарии к обсуждению {} - {} ", timeFrom, timeTo); + log.trace("Запрошены последние комментарии к обсуждению {} - {} ", timeFrom, timeTo); List mails = commentRepository.betweenByAddDateTime(timeFrom, timeTo); return getBoardComments(mails); } @Override public List getNewMessage() { - return null; + throw new IllegalStateException("Не реализовано"); } private List getBoardComments(List mails) { diff --git a/src/main/java/org/sadtech/social/core/service/impl/MailServiceImpl.java b/src/main/java/org/sadtech/social/core/service/impl/MailServiceImpl.java index 74ddf72..e62e4ee 100644 --- a/src/main/java/org/sadtech/social/core/service/impl/MailServiceImpl.java +++ b/src/main/java/org/sadtech/social/core/service/impl/MailServiceImpl.java @@ -27,18 +27,18 @@ public class MailServiceImpl implements MailService { public void add(Mail mail) { mailRepository.add(mail); newMessage = true; - log.info("Сообщение добавлено в репозиторий | {}", mail); + log.trace("Сообщение добавлено в репозиторий | {}", mail); } @Override public List getByAddDateTime(LocalDateTime timeFrom, LocalDateTime timeTo) { - log.debug("Запрошены все сообщения {} - {} ", timeFrom, timeTo); + log.trace("Запрошены все сообщения {} - {} ", timeFrom, timeTo); return mailRepository.betweenByAddDateTime(timeFrom, timeTo); } @Override public List getLastEventByCreateDateTime(LocalDateTime timeFrom, LocalDateTime timeTo) { - log.debug("Запрошены последние сообщения {} - {} ", timeFrom, timeTo); + log.trace("Запрошены последние сообщения {} - {} ", timeFrom, timeTo); List mails = mailRepository.betweenByCreateDateTime(timeFrom, timeTo); if (mails != null && !mails.isEmpty()) { return getReturnMails(mails); @@ -49,7 +49,7 @@ public class MailServiceImpl implements MailService { @Override public List getLastEventByAddDateTime(LocalDateTime timeFrom, LocalDateTime timeTo) { - log.debug("Запрошены последние сообщения {} - {} ", timeFrom, timeTo); + log.trace("Запрошены последние сообщения {} - {} ", timeFrom, timeTo); List mails = mailRepository.betweenByAddDateTime(timeFrom, timeTo); if (mails != null && !mails.isEmpty()) { return getReturnMails(mails); diff --git a/src/main/java/org/sadtech/social/core/service/sender/email/EmailSending.java b/src/main/java/org/sadtech/social/core/service/sender/email/EmailSending.java index 324dec2..94c2bc0 100644 --- a/src/main/java/org/sadtech/social/core/service/sender/email/EmailSending.java +++ b/src/main/java/org/sadtech/social/core/service/sender/email/EmailSending.java @@ -53,4 +53,5 @@ public class EmailSending implements Sending { public SendType getType() { return SendType.PUBLIC; } + } diff --git a/src/main/java/org/sadtech/social/core/utils/ExceptionMessages.java b/src/main/java/org/sadtech/social/core/utils/ExceptionMessages.java index c7d0f87..4e29891 100644 --- a/src/main/java/org/sadtech/social/core/utils/ExceptionMessages.java +++ b/src/main/java/org/sadtech/social/core/utils/ExceptionMessages.java @@ -7,9 +7,10 @@ package org.sadtech.social.core.utils; */ public class ExceptionMessages { - public final static String UTILITY_CLASS = "Класс утилита"; + public static final String UTILITY_CLASS = "Класс утилита"; private ExceptionMessages() { throw new IllegalStateException(UTILITY_CLASS); } + } diff --git a/src/main/java/org/sadtech/social/core/utils/InsertWords.java b/src/main/java/org/sadtech/social/core/utils/InsertWords.java index 35c8c87..7b8a954 100644 --- a/src/main/java/org/sadtech/social/core/utils/InsertWords.java +++ b/src/main/java/org/sadtech/social/core/utils/InsertWords.java @@ -1,11 +1,11 @@ package org.sadtech.social.core.utils; +import lombok.NonNull; + import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; -import static org.sadtech.social.core.utils.ExceptionMessages.UTILITY_CLASS; - /** * Класс для вставки слов в текстовую строку вместо подстрок - шаблонов маркеров. * @@ -16,7 +16,7 @@ public class InsertWords { private static final Pattern pattern = Pattern.compile("\\{(\\d+)}"); private InsertWords() { - throw new IllegalStateException(UTILITY_CLASS); + throw new IllegalStateException(ExceptionMessages.UTILITY_CLASS); } /** @@ -26,7 +26,7 @@ public class InsertWords { * @param words Список слов, которые необходимо поместить вместо шаблона * @return Модифицированная строка */ - public static String insert(String text, List words) { + public static String insert(@NonNull String text, List words) { Matcher m = pattern.matcher(text); StringBuffer result = new StringBuffer(); while (m.find()) { @@ -39,6 +39,7 @@ public class InsertWords { m.appendTail(result); return result.toString(); } + } diff --git a/src/main/java/org/sadtech/social/core/utils/MessageUtils.java b/src/main/java/org/sadtech/social/core/utils/MessageUtils.java index eacd1c7..fe02569 100644 --- a/src/main/java/org/sadtech/social/core/utils/MessageUtils.java +++ b/src/main/java/org/sadtech/social/core/utils/MessageUtils.java @@ -3,8 +3,6 @@ package org.sadtech.social.core.utils; import org.sadtech.social.core.domain.content.EmptyMessage; import org.sadtech.social.core.domain.content.Message; -import static org.sadtech.social.core.utils.ExceptionMessages.UTILITY_CLASS; - /** * Класс для хранения объекта заглушки для {@link Message}. * @@ -12,11 +10,10 @@ import static org.sadtech.social.core.utils.ExceptionMessages.UTILITY_CLASS; */ public class MessageUtils { - private MessageUtils() { - throw new IllegalStateException(UTILITY_CLASS); - } - public static final EmptyMessage EMPTY_MESSAGE = new EmptyMessage(); + private MessageUtils() { + throw new IllegalStateException(ExceptionMessages.UTILITY_CLASS); + } } diff --git a/src/main/java/org/sadtech/social/core/utils/Sender.java b/src/main/java/org/sadtech/social/core/utils/Sender.java index 8d19c51..758888f 100644 --- a/src/main/java/org/sadtech/social/core/utils/Sender.java +++ b/src/main/java/org/sadtech/social/core/utils/Sender.java @@ -7,6 +7,11 @@ import org.sadtech.social.core.service.sender.Sending; import static org.sadtech.social.core.utils.ExceptionMessages.UTILITY_CLASS; +/** + * Используется для отправки сообщений определенного типа. + * + * @author upagge + */ public class Sender { private Sender() {