EmailServiceImpl.java

  1. package no.nav.data.common.mail;

  2. import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
  3. import no.nav.data.common.security.SecurityProperties;
  4. import no.nav.data.common.storage.StorageService;
  5. import org.apache.logging.log4j.LogManager;
  6. import org.apache.logging.log4j.Logger;
  7. import org.springframework.scheduling.annotation.Scheduled;
  8. import org.springframework.stereotype.Service;

  9. @Service
  10. public class EmailServiceImpl implements EmailService {

  11.     public static final Logger logger = LogManager.getLogger(EmailServiceImpl.class);

  12.     private final StorageService storage;
  13.     private final SecurityProperties securityProperties;

  14.     private final EmailClient emailClient;

  15.     public EmailServiceImpl(StorageService storage, SecurityProperties securityProperties,
  16.                             EmailClient emailClient) {
  17.         this.storage = storage;
  18.         this.securityProperties = securityProperties;
  19.         this.emailClient = emailClient;
  20.     }

  21.     @Override
  22.     public void sendMail(MailTask mailTask) {
  23.         var toSend = securityProperties.isDev() ? mailTask.withSubject("[DEV] " + mailTask.getSubject()) : mailTask;

  24.         emailClient.sendEmail(toSend).subscribe();
  25.     }

  26.     @Override
  27.     public void scheduleMail(MailTask mailTask) {
  28.         storage.save(mailTask);
  29.     }

  30.     @SchedulerLock(name = "sendMail")
  31.     @Scheduled(initialDelayString = "PT2M", fixedRateString = "PT1M")
  32.     public void sendMail() {
  33.         var tasks = storage.getAll(MailTask.class);

  34.         tasks.forEach(task -> {
  35.             sendMail(task);
  36.             storage.delete(task);
  37.         });
  38.     }
  39. }