3 * Copyright (C) 2009-2021 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.authentication;
22 import javax.annotation.Nullable;
23 import org.sonar.api.utils.System2;
24 import org.sonar.db.DbClient;
25 import org.sonar.db.DbSession;
26 import org.sonar.db.user.UserDto;
27 import org.sonar.db.user.UserTokenDto;
29 public class UserLastConnectionDatesUpdaterImpl implements UserLastConnectionDatesUpdater {
31 private static final long ONE_HOUR_IN_MILLISECONDS = 60 * 60 * 1000L;
33 private final DbClient dbClient;
34 private final System2 system2;
36 public UserLastConnectionDatesUpdaterImpl(DbClient dbClient, System2 system2) {
37 this.dbClient = dbClient;
38 this.system2 = system2;
42 public void updateLastConnectionDateIfNeeded(UserDto user) {
43 Long lastConnectionDate = user.getLastConnectionDate();
44 long now = system2.now();
45 if (doesNotRequireUpdate(lastConnectionDate, now)) {
48 try (DbSession dbSession = dbClient.openSession(false)) {
49 dbClient.userDao().update(dbSession, user.setLastConnectionDate(now), false);
55 public void updateLastConnectionDateIfNeeded(UserTokenDto userToken) {
56 Long lastConnectionDate = userToken.getLastConnectionDate();
57 long now = system2.now();
58 if (doesNotRequireUpdate(lastConnectionDate, now)) {
61 try (DbSession dbSession = dbClient.openSession(false)) {
62 dbClient.userTokenDao().update(dbSession, userToken.setLastConnectionDate(now), false, null);
63 userToken.setLastConnectionDate(now);
68 private static boolean doesNotRequireUpdate(@Nullable Long lastConnectionDate, long now) {
69 // Update date only once per hour in order to decrease pressure on DB
70 return lastConnectionDate != null && (now - lastConnectionDate) < ONE_HOUR_IN_MILLISECONDS;