summaryrefslogtreecommitdiff
path: root/orkbasej/java/net/sf/oreka/srvc/UserServiceHbn.java
blob: 8ee6e00de9893b2d15665fd974392a3238bdb6d3 (plain)
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
package net.sf.oreka.srvc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import net.sf.oreka.HibernateManager;
import net.sf.oreka.OrkBase;
import net.sf.oreka.OrkException;
import net.sf.oreka.bo.UserBo;
import net.sf.oreka.persistent.LoginString;
import net.sf.oreka.persistent.User;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Expression;

public class UserServiceHbn implements UserService {

	static Logger logger = Logger.getLogger(UserServiceHbn.class);	
	
	public UserBo login(String username, String password) {
		
		Session hbnSession = null;
		UserBo userBo = null;
		
		logger.debug("Trying to login user:" + username + " with passwd:" + password);
		
		try
		{
			hbnSession = HibernateManager.instance().getSession();
			
			String queryString = new String("from LoginString as ls left join ls.user as user where ls.loginString=:ls and user.deleted=0 ");
			if (OrkBase.instance().isDebugSwitch() == false) {
				queryString = queryString + " and user.password=:password";
			}
			Query query = hbnSession.createQuery(queryString);
			query.setString("ls", username);
			if (OrkBase.instance().isDebugSwitch() == false) {
				query.setString("password", password);
			}
			ArrayList results = (ArrayList)query.list();
			Object[] row = (Object[])query.uniqueResult();
			if (row != null) {
				userBo = new UserBo();
				userBo.setUser((User)row[1]);
				logger.debug("Found userid:" + userBo.getUser().getId() + " for login string:" + username);
			}
		}
		catch ( HibernateException he ) {
			logger.error("login: exception:" + he.getClass().getName());
		}
		catch (Exception e)
		{
			logger.error("login: exception:", e);
		}
		finally {
			if(hbnSession != null) {hbnSession.close();}
		}
		return userBo;
	}

	public boolean changePassword(int userId, String oldPassword, String newPassword) {
		
		Session hbnSession = null;
		Transaction tx = null;
		User user = null;
		boolean success = false;
		
		logger.debug("Trying to change password for userid:" + userId);
		
		try
		{
			hbnSession = HibernateManager.instance().getSession();

			
			user = (User)hbnSession.get(User.class, userId);
			if(user == null) {
				logger.warn("Userid:" + userId + " does not exist");
			}
			else {
				if(user.getPassword().equals(oldPassword)) {
					tx = hbnSession.beginTransaction();
					user.setPassword(newPassword);
					hbnSession.save(user);
					tx.commit();
					success = true;
					logger.debug("Changed password for userid:" + userId);
				}
			}
		}
		catch ( HibernateException he ) {
			logger.error("changePassword: exception:" + he.getClass().getName());
		}
		catch (Exception e)
		{
			logger.error("changePassword: exception:", e);
		}
		finally {
			if(hbnSession != null) {hbnSession.close();}
		}
		return success;		
	}

	public int getUsers(UserFilter filter, int offset, int number, String orderBy, boolean ascending, List<UserBo> results) {
		
		Session hbnSession = null;
		Transaction tx = null;
		logger.debug("Entering getUsers");
		List<User> users;
		int numResults = 0;
		
		try
		{
			hbnSession = HibernateManager.instance().getSession();

			/*
			Criteria crit = hbnSession.createCriteria(User.class);
			//crit.add( Expression.eq( "color", eg.Color.BLACK ) );
			
			// figure out total number of users returned
			ScrollableResults scrollRes = crit.scroll();
			if ( scrollRes.last() ) {
				numResults = scrollRes.getRowNumber();
			}
			
			// get only one page worth of users
			crit.setMaxResults(number);
			crit.setFirstResult(offset);
			users = crit.list();
			
			Iterator it = users.iterator();
			while(it.hasNext()) {
				UserBo ubo = new UserBo();
				ubo.setUser((User)it.next());
				results.add(ubo);
			}
			*/
			
			StringBuffer queryString = new StringBuffer("from User as user where user.deleted=0 ");
			Query query = hbnSession.createQuery(queryString.toString());
			
			ScrollableResults scrollRes = query.scroll();
			if ( scrollRes.last() ) {
				numResults = scrollRes.getRowNumber();
			}
			
			// get only one page worth of users		
			scrollRes.setRowNumber(offset);
			int numRetrieved = 0;
			
			while(scrollRes.next() && numRetrieved<number) {
				numRetrieved++;
				UserBo ubo = new UserBo();
				ubo.setUser((User)scrollRes.get()[0]);
				results.add(ubo);
			}
			
			logger.debug("getUsers: got " + numResults + " users");
		}
		catch ( HibernateException he ) {
			logger.error("getUsers: exception:" + he.getClass().getName());
		}
		catch (Exception e)
		{
			logger.error("getUsers: exception:", e);
		}
		finally {
			if(hbnSession != null) {hbnSession.close();}
		}	
		return numResults;
	}

	public void deleteUser(int userId) {
		
		Session hbnSession = null;
		Transaction tx = null;
		User user = null;
		
		logger.debug("Deleting userid:" + userId);
		
		try
		{
			hbnSession = HibernateManager.instance().getSession();

			
			user = (User)hbnSession.get(User.class, userId);
			if(user == null) {
				logger.warn("Userid:" + userId + " does not exist");
			}
			else {
				tx = hbnSession.beginTransaction();
				user.setDeleted(true);
				hbnSession.save(user);
				tx.commit();
			}
		}
		catch ( HibernateException he ) {
			logger.error("deleteUser: exception:" + he.getClass().getName());
		}
		catch (Exception e)
		{
			logger.error("deleteUser: exception:", e);
		}
		finally {
			if(hbnSession != null) {hbnSession.close();}
		}		
	}

	public void disableUser(int userId) {
		
		Session hbnSession = null;
		Transaction tx = null;
		User user = null;
		
		logger.debug("Disabling userid:" + userId);
		
		try
		{
			hbnSession = HibernateManager.instance().getSession();
			user = (User)hbnSession.get(User.class, userId);
			if(user == null) {
				logger.warn("Userid:" + userId + " does not exist");
			}
			else {
				tx = hbnSession.beginTransaction();
				user.setDisabled(true);
				hbnSession.save(user);
				tx.commit();
			}
		}
		catch ( HibernateException he ) {
			logger.error("disableUser: exception:" + he.getClass().getName());
		}
		catch (Exception e)
		{
			logger.error("disableUser: exception:", e);
		}
		finally {
			if(hbnSession != null) {hbnSession.close();}
		}	
	}
	
	public void setUserLoginStrings(int userId, String loginStringsCsv) {
		
		if(loginStringsCsv == null) {
			loginStringsCsv = "";
		}
		logger.debug("Entering setUserLoginStrings; userId:" + userId + " loginStringsCsv:" + loginStringsCsv);
		
		HashSet<String> oldLoginStrings = new HashSet<String>();
		HashSet<String> newLoginStrings = new HashSet<String>();
		HashMap<String, LoginString> loginStringMap = new HashMap<String, LoginString>();
		
		Session hbnSession = null;
		Transaction tx = null;
		
		try
		{
			hbnSession = HibernateManager.instance().getSession();
			tx = hbnSession.beginTransaction();
		
			// 1. extract all new login strings from CSV
			String[] loginStrings = StringUtils.split(loginStringsCsv, ", ");
			for(int i=0; i<loginStrings.length; i++) {
				newLoginStrings.add(loginStrings[i]);
				
				// see if the login string exists for another user
				String queryString = new String("from LoginString as ls where ls.loginString=:loginString");
				Query query = hbnSession.createQuery(queryString);
				query.setString("loginString", loginStrings[i]);
				List list = query.list();
				LoginString ls = null;
				
				if(list.size() > 0) {
					ls = (LoginString)list.get(0);
					if(ls != null) {
						if(ls.getUser() != null) {
							if(ls.getUser().getId() != userId && !ls.getUser().isDeleted()) {
								throw new OrkException("Login String:" + loginStrings[i] + " belongs to userid:" + ls.getUser().getId());
							}
						}
					}

				}
				// Create a new login string if it does not exist yet in the DB
				if(ls == null) {
					ls = new LoginString();
					ls.setLoginString(loginStrings[i]);
					hbnSession.save(ls);
				}
				loginStringMap.put(loginStrings[i], ls);
			}
			
			// 2. get the user and extract all old login strings
			User user = (User)hbnSession.get(User.class, userId);
			if(user == null) {
				throw new OrkException("UserId:" + userId + " does not exist");			
			}
			String queryString = new String("from LoginString as ls where ls.user=:user");
			Query query = hbnSession.createQuery(queryString);
			query.setEntity("user", user);
			List list = query.list();
			Iterator it = list.iterator();
			while(it.hasNext()) {
				LoginString ls = (LoginString)it.next();
				oldLoginStrings.add(ls.getLoginString());
				loginStringMap.put(ls.getLoginString(), ls);
			}
			
			// Add all new login strings to the user
			it = newLoginStrings.iterator();
			while(it.hasNext()) {
				String ls = (String)it.next();
				if(oldLoginStrings.contains(ls) == false) {
					LoginString lso = loginStringMap.get(ls);
					lso.setUser(user);
					logger.debug("Added loginstring:" + lso.getLoginString() + " to user:" + user.getFirstname());
				}
			}
			
			// Remove all old login strings from the user
			it = oldLoginStrings.iterator();
			while(it.hasNext()) {
				String ls = (String)it.next();
				if(newLoginStrings.contains(ls) == false) {
					LoginString lso = loginStringMap.get(ls);
					lso.setUser(null);
					logger.debug("Removed loginstring:" + lso.getLoginString() + " from user:" + user.getFirstname());
				}
			}			
			
			tx.commit();
		}
		catch ( HibernateException he ) {
			logger.error("setUserLoginStrings: exception:" + he.getClass().getName());
		}
		catch ( OrkException oe ) {
			logger.error("OrkException:" + oe.getMessage());
		}
		catch (Exception e)
		{
			logger.error("setUserLoginStrings: exception:", e);
		}
		finally {
			if(hbnSession != null) {hbnSession.close();}
		}
	}

	
	public String getUserLoginStrings(int userId) {
		
		Session hbnSession = null;
		User user = null;
		String loginStringsCsv = "";
		
		try
		{
			hbnSession = HibernateManager.instance().getSession();
			user = (User)hbnSession.get(User.class, userId);
			String queryString = new String("from LoginString as ls where ls.user=:user");
			Query query = hbnSession.createQuery(queryString);
			query.setEntity("user", user);
			List list = query.list();
			
			Iterator it = list.iterator();
			if(it.hasNext()) {
				loginStringsCsv = ((LoginString)it.next()).getLoginString();
			}
			while(it.hasNext()) {
				loginStringsCsv += ", " + ((LoginString)it.next()).getLoginString();
			}
		}
		catch ( HibernateException he ) {
			logger.error("getUserLoginStrings: exception:" + he.getClass().getName());
		}
		catch (Exception e)
		{
			logger.error("getUserLoginStrings: exception:", e);
		}
		finally {
			if(hbnSession != null) {hbnSession.close();}
		}	
		return loginStringsCsv;
	}

	public int getNumNonDisabledUsers() {
		
		Session hbnSession = null;
		int numUsers = 0;
		
		try
		{
			hbnSession = HibernateManager.instance().getSession();

			Criteria crit = hbnSession.createCriteria(User.class);
			crit.add( Expression.eq( "disabled", false ) );
			crit.add( Expression.eq( "deleted", false ) );			
			
			// figure out total number of objects returned
			ScrollableResults scrollRes = crit.scroll();
			if ( scrollRes.last() ) {
				numUsers = scrollRes.getRowNumber();
			}
		}
		catch ( HibernateException he ) {
			logger.error("getNumNonDisabledUsers: exception:" + he.getClass().getName());
		}
		catch (Exception e)
		{
			logger.error("getNumNonDisabledUsers: exception:", e);
		}
		finally {
			if(hbnSession != null) {hbnSession.close();}
		}
		
		return numUsers;
	}
	
	public User getUserByLoginString(String loginString) {
		Session hbnSession = null;
		User user = null;
		
		try
		{
			hbnSession = HibernateManager.instance().getSession();
			String queryString = new String("from LoginString as ls where ls.loginstring=:ls");
			Query query = hbnSession.createQuery(queryString);
			query.setString("ls", loginString);
			List list = query.list();
			Iterator it = list.iterator();
			if (it.hasNext()) {
				LoginString ls = (LoginString)it.next();
				user = ls.getUser();
			}
		}
		catch ( HibernateException he ) {
			logger.error("getUserByLoginString: exception:" + he.getClass().getName());
		}
		catch (Exception e) {
			logger.error("getUserByLoginString: exception:", e);
		}
		finally {
			if(hbnSession != null) {hbnSession.close();}
		}
		return user;
	}

}