Liboskat

Untitled

Feb 26th, 2021
693
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package com.simbirsoft.registrationtesttask.services;
  2.  
  3. import com.simbirsoft.registrationtesttask.dto.*;
  4. import com.simbirsoft.registrationtesttask.mappers.UserMapper;
  5. import com.simbirsoft.registrationtesttask.models.EmailAddress;
  6. import com.simbirsoft.registrationtesttask.models.EmailContent;
  7. import com.simbirsoft.registrationtesttask.models.User;
  8. import com.simbirsoft.registrationtesttask.models.UserStatus;
  9. import com.simbirsoft.registrationtesttask.repositories.UserRepository;
  10. import lombok.RequiredArgsConstructor;
  11. import lombok.SneakyThrows;
  12. import lombok.extern.slf4j.Slf4j;
  13. import org.springframework.stereotype.Service;
  14.  
  15. import java.util.Optional;
  16. import java.util.concurrent.ExecutorService;
  17. import java.util.concurrent.Executors;
  18. import java.util.concurrent.TimeUnit;
  19. import java.util.concurrent.TimeoutException;
  20.  
  21. @Service
  22. @RequiredArgsConstructor
  23. @Slf4j
  24. public class UserServiceImpl implements UserService {
  25.     public static final String REGISTRATION_APPROVE_MAIL_SUBJECT = "Информация о регистрации";
  26.     public static final String SUCCESS_REGISTRATION_APPROVE_MAIL_BODY = "Регистрация пройдена успешно";
  27.     public static final String FAIL_REGISTRATION_APPROVE_MAIL_BODY = "Регистрация не одобрена";
  28.  
  29.     private final UserRepository repository;
  30.     private final UserMapper userMapper;
  31.     private final MessagingService messagingService;
  32.     private final SendMailer sendMailer;
  33.     private final ExecutorService getApprovalExecutorService = Executors.newFixedThreadPool(20);
  34.     private final ExecutorService sendMailExecutorService = Executors.newFixedThreadPool(20);
  35.  
  36.     /**
  37.      * Метод регистрации пользователя
  38.      * Данные пользователя сохраняются в БД и происходит асинхронное получение подтверждения регистрации
  39.      *
  40.      * @return {@link RegistrationResponseDto}.
  41.      * Если уже использованы логин или почта, то возвращается со статусом {@link RegistrationStatus#EMAIL_OR_LOGIN_IS_IN_USE}
  42.      * Иначе возвращается со статусом {@link RegistrationStatus#WAITING_APPROVAL}
  43.      */
  44.     @Override
  45.     public RegistrationResponseDto registerUser(UserForm userForm) {
  46.         if (repository.existsByLoginOrEmail(userForm.getLogin(), userForm.getEmail())) {
  47.             log.debug("User {} email or login is already in use", userForm);
  48.             return RegistrationResponseDto.builder()
  49.                     .login(userForm.getLogin())
  50.                     .email(userForm.getEmail())
  51.                     .registrationStatus(RegistrationStatus.EMAIL_OR_LOGIN_IS_IN_USE)
  52.                     .build();
  53.         }
  54.  
  55.         User user = userMapper.toEntity(userForm);
  56.         user.setStatus(UserStatus.WAITING_APPROVAL);
  57.         repository.save(user);
  58.         log.debug("User {} saved", user);
  59.  
  60.         getRegistrationApproval(userForm);
  61.  
  62.         return RegistrationResponseDto.builder()
  63.                 .login(user.getLogin())
  64.                 .email(user.getEmail())
  65.                 .registrationStatus(RegistrationStatus.WAITING_APPROVAL)
  66.                 .build();
  67.     }
  68.  
  69.     /**
  70.      * @param userForm
  71.      * @param registrationApproval
  72.      */
  73.     @Override
  74.     public void updateUserByRegistrationApproval(UserForm userForm, RegistrationApprovalDto registrationApproval) {
  75.         String email = userForm.getEmail();
  76.         if (email == null) {
  77.             log.error("Approve user email is null");
  78.             return;
  79.         }
  80.  
  81.         Optional<User> userOptional = repository.getByEmail(email);
  82.         if (!userOptional.isPresent()) {
  83.             log.error("User with email {} is not found", email);
  84.             return;
  85.         }
  86.  
  87.         User user = userOptional.get();
  88.  
  89.         if (registrationApproval.getApproved() != null && registrationApproval.getApproved()) {
  90.             user.setStatus(UserStatus.APPROVED);
  91.             repository.save(user);
  92.             log.debug("User: {} status set to APPROVED", userForm);
  93.         } else {
  94.             repository.delete(user);
  95.             log.debug("Not approved user: {} is deleted", userForm);
  96.         }
  97.     }
  98.  
  99.     @Override
  100.     public void getRegistrationApproval(UserForm userForm) {
  101.         getApprovalExecutorService.submit(new GetApprovalRunnable(userForm));
  102.         log.debug("Async approval getting is started for User: {}", userForm);
  103.     }
  104.  
  105.     @Override
  106.     public void sendRegistrationApprovalMessage(UserForm userForm, RegistrationApprovalDto registrationApprovalDto) {
  107.         sendMailExecutorService.submit(new SendRegistrationApproveMailRunnable(userForm, registrationApprovalDto));
  108.     }
  109.  
  110.     @RequiredArgsConstructor
  111.     private final class GetApprovalRunnable implements Runnable {
  112.         private final UserForm userForm;
  113.  
  114.         @Override
  115.         public void run() {
  116.             Message<RegistrationApprovalDto> registrationApprovalMessage;
  117.             try {
  118.                 registrationApprovalMessage = getApprovalMessage();
  119.             } catch (TimeoutException ex) {
  120.                 log.error("Timeout on getting registration approval for user {}", userForm);
  121.                 retryGetRegistrationApproval();
  122.                 return;
  123.             }
  124.             if (registrationApprovalMessage == null || registrationApprovalMessage.getData() == null) {
  125.                 log.error("Registration approval message for user {} is null", userForm);
  126.                 retryGetRegistrationApproval();
  127.                 return;
  128.             }
  129.             RegistrationApprovalDto registrationApproval = registrationApprovalMessage.getData();
  130.             updateUserByRegistrationApproval(userForm, registrationApproval);
  131.             sendMail(registrationApproval);
  132.         }
  133.  
  134.         private Message<RegistrationApprovalDto> getApprovalMessage() throws TimeoutException {
  135.             MessageId messageId = messagingService.send(new Message<>(userForm));
  136.             return messagingService.receive(messageId, RegistrationApprovalDto.class);
  137.         }
  138.  
  139.         private void retryGetRegistrationApproval() {
  140.             sleep();
  141.             getRegistrationApproval(userForm);
  142.         }
  143.  
  144.         private void sendMail(RegistrationApprovalDto registrationApprovalDto) {
  145.             sendRegistrationApprovalMessage(userForm, registrationApprovalDto);
  146.         }
  147.  
  148.         @SneakyThrows
  149.         private void sleep() {
  150.             Thread.sleep(TimeUnit.MINUTES.toMillis(1));
  151.         }
  152.     }
  153.  
  154.     @RequiredArgsConstructor
  155.     private final class SendRegistrationApproveMailRunnable implements Runnable {
  156.         private final UserForm userForm;
  157.         private final RegistrationApprovalDto registrationApprovalDto;
  158.  
  159.         @Override
  160.         public void run() {
  161.             EmailAddress address = new EmailAddress(userForm.getEmail());
  162.  
  163.             boolean isApproved = registrationApprovalDto.getApproved() != null && registrationApprovalDto.getApproved();
  164.             EmailContent content = EmailContent.builder()
  165.                     .subject(REGISTRATION_APPROVE_MAIL_SUBJECT)
  166.                     .body(isApproved ? SUCCESS_REGISTRATION_APPROVE_MAIL_BODY : FAIL_REGISTRATION_APPROVE_MAIL_BODY)
  167.                     .build();
  168.  
  169.             try {
  170.                 sendMailer.sendMail(address, content);
  171.             } catch (TimeoutException e) {
  172.                 log.error("Timeout on sending registration approval mail for user {}", userForm);
  173.                 retrySendRegistrationApproveMail();
  174.             }
  175.         }
  176.  
  177.         private void retrySendRegistrationApproveMail() {
  178.             sleep();
  179.             sendRegistrationApprovalMessage(userForm, registrationApprovalDto);
  180.         }
  181.  
  182.         @SneakyThrows
  183.         private void sleep() {
  184.             Thread.sleep(TimeUnit.MINUTES.toMillis(1));
  185.         }
  186.     }
  187. }
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×