-
Notifications
You must be signed in to change notification settings - Fork 0
/
UserSqlMapDao.java
246 lines (220 loc) · 9.74 KB
/
UserSqlMapDao.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
/*
* Copyright 2018 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.server.dao;
import com.thoughtworks.go.domain.NullUser;
import com.thoughtworks.go.domain.User;
import com.thoughtworks.go.domain.Users;
import com.thoughtworks.go.server.cache.GoCache;
import com.thoughtworks.go.server.exceptions.UserEnabledException;
import com.thoughtworks.go.server.exceptions.UserNotFoundException;
import com.thoughtworks.go.server.transaction.TransactionSynchronizationManager;
import com.thoughtworks.go.server.transaction.TransactionTemplate;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.*;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Component
public class UserSqlMapDao extends HibernateDaoSupport implements UserDao {
private SessionFactory sessionFactory;
private TransactionTemplate transactionTemplate;
private GoCache goCache;
private final TransactionSynchronizationManager transactionSynchronizationManager;
protected static final String ENABLED_USER_COUNT_CACHE_KEY = "ENABLED_USER_COUNT_CACHE_KEY".intern();
@Autowired
public UserSqlMapDao(SessionFactory sessionFactory,
TransactionTemplate transactionTemplate,
GoCache goCache,
TransactionSynchronizationManager transactionSynchronizationManager) {
this.sessionFactory = sessionFactory;
this.transactionTemplate = transactionTemplate;
this.goCache = goCache;
this.transactionSynchronizationManager = transactionSynchronizationManager;
setSessionFactory(sessionFactory);
}
public void saveOrUpdate(final User user) {
assertUserNotAnonymous(user);
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
@Override
public void afterCommit() {
clearEnabledUserCountFromCache();
}
});
sessionFactory.getCurrentSession().saveOrUpdate(copyLoginToDisplayNameIfNotPresent(user));
}
});
}
public User findUser(final String userName) {
return (User) transactionTemplate.execute((TransactionCallback) transactionStatus -> {
User user = (User) sessionFactory.getCurrentSession()
.createCriteria(User.class)
.add(Restrictions.eq("name", userName))
.setCacheable(true).uniqueResult();
return user == null ? new NullUser() : user;
});
}
public Users findNotificationSubscribingUsers() {
return (Users) transactionTemplate.execute((TransactionCallback) transactionStatus -> {
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(User.class);
criteria.setCacheable(true);
criteria.add(Restrictions.isNotEmpty("notificationFilters"));
criteria.add(Restrictions.eq("enabled", true));
return new Users(criteria.list());
});
}
public Users allUsers() {
return new Users((List<User>) transactionTemplate.execute((TransactionCallback) transactionStatus -> {
Query query = sessionFactory.getCurrentSession().createQuery("FROM User");
query.setCacheable(true);
return query.list();
}));
}
public long enabledUserCount() {
Long value = (Long) goCache.get(ENABLED_USER_COUNT_CACHE_KEY);
if (value != null) {
return value;
}
synchronized (ENABLED_USER_COUNT_CACHE_KEY) {
value = (Long) goCache.get(ENABLED_USER_COUNT_CACHE_KEY);
if (value == null) {
value = hibernateTemplate().execute(session -> (Long) session.createCriteria(User.class).add(Restrictions.eq("enabled", true)).setProjection(Projections.rowCount()).setCacheable(true).uniqueResult());
goCache.put(ENABLED_USER_COUNT_CACHE_KEY, value);
}
return value;
}
}
// Used only by Twist tests
public void deleteAll() {
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
@Override
public void afterCommit() {
clearEnabledUserCountFromCache();
}
});
sessionFactory.getCurrentSession().createQuery("DELETE FROM User").executeUpdate();
}
});
}
public void disableUsers(List<String> usernames) {
changeEnabledStatus(usernames, false);
}
public void enableUsers(List<String> usernames) {
changeEnabledStatus(usernames, true);
}
@Override
public List<User> enabledUsers() {
List<User> enabledUsers = new ArrayList<>();
for (User user : allUsers()) {
if (user.isEnabled()) {
enabledUsers.add(user);
}
}
return enabledUsers;
}
public Set<String> findUsernamesForIds(final Set<Long> userIds) {
List<User> users = allUsers();
Set<String> userNames = new HashSet<>();
for (User user : users) {
if (userIds.contains(user.getId())) {
userNames.add(user.getName());
}
}
return userNames;
}
public User load(final long id) {
return (User) transactionTemplate.execute((TransactionCallback) transactionStatus -> sessionFactory.getCurrentSession().get(User.class, id));
}
@Override
public boolean deleteUser(final String username) {
return (Boolean) transactionTemplate.execute((TransactionCallback) status -> {
User user = findUser(username);
if (user instanceof NullUser) {
throw new UserNotFoundException();
}
if (user.isEnabled()) {
throw new UserEnabledException();
}
sessionFactory.getCurrentSession().delete(user);
return Boolean.TRUE;
});
}
@Override
public boolean deleteUsers(List<String> userNames) {
return (Boolean) transactionTemplate.execute((TransactionCallback) status -> {
String queryString = "delete from User where name in (:userNames)";
Query query = sessionFactory.getCurrentSession().createQuery(queryString);
query.setParameterList("userNames", userNames);
query.executeUpdate();
return Boolean.TRUE;
});
}
private void clearEnabledUserCountFromCache() {
synchronized (ENABLED_USER_COUNT_CACHE_KEY) {
goCache.remove(ENABLED_USER_COUNT_CACHE_KEY);
}
}
protected HibernateTemplate hibernateTemplate() {
return getHibernateTemplate();
}
private void assertUserNotAnonymous(User user) {
if (user.isAnonymous()) {
throw new IllegalArgumentException(String.format("User name '%s' is not permitted.", user.getName()));
}
}
private User copyLoginToDisplayNameIfNotPresent(User user) {
if (StringUtils.isBlank(user.getDisplayName())) {
user.setDisplayName(user.getName());
}
return user;
}
private void changeEnabledStatus(final List<String> usernames, final boolean enabled) {
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
@Override
public void afterCommit() {
clearEnabledUserCountFromCache();
}
});
String queryString = String.format("update %s set enabled = :enabled where name in (:userNames)", User.class.getName());
Query query = sessionFactory.getCurrentSession().createQuery(queryString);
query.setParameter("enabled", enabled);
query.setParameterList("userNames", usernames);
query.executeUpdate();
}
});
}
}