3 * Copyright (C) 2009-2023 SonarSource SA
4 * mailto:info AT sonarsource DOT com
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 3 of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 package org.sonar.server.usertoken.notification;
23 import java.util.stream.Collectors;
24 import java.util.stream.Stream;
25 import org.sonar.api.utils.log.Logger;
26 import org.sonar.api.utils.log.Loggers;
27 import org.sonar.db.DbClient;
28 import org.sonar.db.user.UserDto;
29 import org.sonar.db.user.UserTokenDto;
31 public class TokenExpirationNotificationSender {
32 private static final Logger LOG = Loggers.get(TokenExpirationNotificationSender.class);
33 private final DbClient dbClient;
34 private final TokenExpirationEmailComposer emailComposer;
36 public TokenExpirationNotificationSender(DbClient dbClient, TokenExpirationEmailComposer emailComposer) {
37 this.dbClient = dbClient;
38 this.emailComposer = emailComposer;
41 public void sendNotifications() {
42 if (!emailComposer.areEmailSettingsSet()) {
43 LOG.debug("Emails for token expiration notification have not been sent because email settings are not configured.");
46 try (var dbSession = dbClient.openSession(false)) {
47 var expiringTokens = dbClient.userTokenDao().selectTokensExpiredInDays(dbSession, 7);
48 var expiredTokens = dbClient.userTokenDao().selectTokensExpiredInDays(dbSession, 0);
49 var tokensToNotify = Stream.concat(expiringTokens.stream(), expiredTokens.stream()).collect(Collectors.toList());
50 var usersToNotify = tokensToNotify.stream().map(UserTokenDto::getUserUuid).collect(Collectors.toSet());
51 Map<String, String> userUuidToEmail = dbClient.userDao().selectByUuids(dbSession, usersToNotify).stream()
52 .collect(Collectors.toMap(UserDto::getUuid, UserDto::getEmail));
53 tokensToNotify.stream().map(token -> new TokenExpirationEmail(userUuidToEmail.get(token.getUserUuid()), token)).forEach(emailComposer::send);