KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jivesoftware > messenger > user > DefaultUserProvider


1 /**
2  * $RCSfile: DefaultUserProvider.java,v $
3  * $Revision: 1.9 $
4  * $Date: 2005/07/20 03:21:12 $
5  *
6  * Copyright (C) 2004 Jive Software. All rights reserved.
7  *
8  * This software is published under the terms of the GNU Public License (GPL),
9  * a copy of which is included in this distribution.
10  */

11
12 package org.jivesoftware.messenger.user;
13
14 import org.jivesoftware.database.DbConnectionManager;
15 import org.jivesoftware.messenger.vcard.VCardManager;
16 import org.jivesoftware.util.LocaleUtils;
17 import org.jivesoftware.util.Log;
18 import org.jivesoftware.util.StringUtils;
19
20 import java.sql.*;
21 import java.util.*;
22 import java.util.Date JavaDoc;
23
24
25 /**
26  * Default implementation of the UserProvider interface, which reads and writes data
27  * from the <tt>jiveUser</tt> database table.
28  *
29  * @author Matt Tucker
30  */

31 public class DefaultUserProvider implements UserProvider {
32
33     private static final String JavaDoc LOAD_USER =
34             "SELECT name, email, creationDate, modificationDate FROM jiveUser WHERE username=?";
35     private static final String JavaDoc USER_COUNT =
36             "SELECT count(*) FROM jiveUser";
37     private static final String JavaDoc ALL_USERS =
38             "SELECT username FROM jiveUser";
39     private static final String JavaDoc INSERT_USER =
40             "INSERT INTO jiveUser (username,password,name,email,creationDate,modificationDate) " +
41             "VALUES (?,?,?,?,?,?)";
42     private static final String JavaDoc DELETE_USER_PROPS =
43             "DELETE FROM jiveUserProp WHERE username=?";
44     private static final String JavaDoc DELETE_USER =
45             "DELETE FROM jiveUser WHERE username=?";
46     private static final String JavaDoc UPDATE_NAME =
47             "UPDATE jiveUser SET name=? WHERE username=?";
48     private static final String JavaDoc UPDATE_EMAIL =
49             "UPDATE jiveUser SET email=? WHERE username=?";
50     private static final String JavaDoc UPDATE_CREATION_DATE =
51             "UPDATE jiveUser SET creationDate=? WHERE username=?";
52     private static final String JavaDoc UPDATE_MODIFICATION_DATE =
53             "UPDATE jiveUser SET modificationDate=? WHERE username=?";
54     private static final String JavaDoc LOAD_PASSWORD =
55             "SELECT password FROM jiveUser WHERE username=?";
56     private static final String JavaDoc UPDATE_PASSWORD =
57             "UPDATE jiveUser SET password=? WHERE username=?";
58
59     public User loadUser(String JavaDoc username) throws UserNotFoundException {
60         Connection con = null;
61         PreparedStatement pstmt = null;
62         try {
63             con = DbConnectionManager.getConnection();
64             pstmt = con.prepareStatement(LOAD_USER);
65             pstmt.setString(1, username);
66             ResultSet rs = pstmt.executeQuery();
67             if (!rs.next()) {
68                 throw new UserNotFoundException();
69             }
70             String JavaDoc name = rs.getString(1);
71             String JavaDoc email = rs.getString(2);
72             Date JavaDoc creationDate = new Date JavaDoc(Long.parseLong(rs.getString(3).trim()));
73             Date JavaDoc modificationDate = new Date JavaDoc(Long.parseLong(rs.getString(4).trim()));
74             rs.close();
75
76             return new User(username, name, email, creationDate, modificationDate);
77         }
78         catch (Exception JavaDoc e) {
79             throw new UserNotFoundException(e);
80         }
81         finally {
82             try { if (pstmt != null) { pstmt.close(); } }
83             catch (Exception JavaDoc e) { Log.error(e); }
84             try { if (con != null) { con.close(); } }
85             catch (Exception JavaDoc e) { Log.error(e); }
86         }
87     }
88
89     public User createUser(String JavaDoc username, String JavaDoc password, String JavaDoc name, String JavaDoc email)
90             throws UserAlreadyExistsException
91     {
92         try {
93             loadUser(username);
94             // The user already exists since no exception, so:
95
throw new UserAlreadyExistsException("Username " + username + " already exists");
96         }
97         catch (UserNotFoundException unfe) {
98             // The user doesn't already exist so we can create a new user
99
Date JavaDoc now = new Date JavaDoc();
100             Connection con = null;
101             PreparedStatement pstmt = null;
102             try {
103                 con = DbConnectionManager.getConnection();
104                 pstmt = con.prepareStatement(INSERT_USER);
105                 pstmt.setString(1, username);
106                 pstmt.setString(2, password);
107                 if (name == null) {
108                     pstmt.setNull(3, Types.VARCHAR);
109                 }
110                 else {
111                     pstmt.setString(3, name);
112                 }
113                 if (email == null) {
114                     pstmt.setNull(4, Types.VARCHAR);
115                 }
116                 else {
117                     pstmt.setString(4, email);
118                 }
119                 pstmt.setString(5, StringUtils.dateToMillis(now));
120                 pstmt.setString(6, StringUtils.dateToMillis(now));
121                 pstmt.execute();
122             }
123             catch (Exception JavaDoc e) {
124                 Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
125             }
126             finally {
127                 try { if (pstmt != null) { pstmt.close(); } }
128                 catch (Exception JavaDoc e) { Log.error(e); }
129                 try { if (con != null) { con.close(); } }
130                 catch (Exception JavaDoc e) { Log.error(e); }
131             }
132             return new User(username, name, email, now, now);
133         }
134     }
135
136     public void deleteUser(String JavaDoc username) {
137         Connection con = null;
138         PreparedStatement pstmt = null;
139         boolean abortTransaction = false;
140         try {
141             con = DbConnectionManager.getTransactionConnection();
142             // Delete all of the users's extended properties
143
pstmt = con.prepareStatement(DELETE_USER_PROPS);
144             pstmt.setString(1, username);
145             pstmt.execute();
146             pstmt.close();
147             // Delete all of the users's vcard properties
148
try {
149                 VCardManager.getInstance().deleteVCard(username);
150             }
151             catch (UnsupportedOperationException JavaDoc e) {}
152             // Delete the actual user entry
153
pstmt = con.prepareStatement(DELETE_USER);
154             pstmt.setString(1, username);
155             pstmt.execute();
156         }
157         catch (Exception JavaDoc e) {
158             Log.error(e);
159             abortTransaction = true;
160         }
161         finally {
162             try { if (pstmt != null) { pstmt.close(); } }
163             catch (Exception JavaDoc e) { Log.error(e); }
164             DbConnectionManager.closeTransactionConnection(con, abortTransaction);
165         }
166     }
167
168     public int getUserCount() {
169         int count = 0;
170         Connection con = null;
171         PreparedStatement pstmt = null;
172         try {
173             con = DbConnectionManager.getConnection();
174             pstmt = con.prepareStatement(USER_COUNT);
175             ResultSet rs = pstmt.executeQuery();
176             if (rs.next()) {
177                 count = rs.getInt(1);
178             }
179             rs.close();
180         }
181         catch (SQLException e) {
182             Log.error(e);
183         }
184         finally {
185             try { if (pstmt != null) { pstmt.close(); } }
186             catch (Exception JavaDoc e) { Log.error(e); }
187             try { if (con != null) { con.close(); } }
188             catch (Exception JavaDoc e) { Log.error(e); }
189         }
190         return count;
191     }
192
193     public Collection<User> getUsers() {
194         List<String JavaDoc> usernames = new ArrayList<String JavaDoc>(500);
195         Connection con = null;
196         PreparedStatement pstmt = null;
197         try {
198             con = DbConnectionManager.getConnection();
199             pstmt = con.prepareStatement(ALL_USERS);
200             ResultSet rs = pstmt.executeQuery();
201             // Set the fetch size. This will prevent some JDBC drivers from trying
202
// to load the entire result set into memory.
203
DbConnectionManager.setFetchSize(rs, 500);
204             while (rs.next()) {
205                 usernames.add(rs.getString(1));
206             }
207             rs.close();
208         }
209         catch (SQLException e) {
210             Log.error(e);
211         }
212         finally {
213             try { if (pstmt != null) { pstmt.close(); } }
214             catch (Exception JavaDoc e) { Log.error(e); }
215             try { if (con != null) { con.close(); } }
216             catch (Exception JavaDoc e) { Log.error(e); }
217         }
218         return new UserCollection((String JavaDoc[])usernames.toArray(new String JavaDoc[usernames.size()]));
219     }
220
221     public Collection<User> getUsers(int startIndex, int numResults) {
222         List<String JavaDoc> usernames = new ArrayList<String JavaDoc>(numResults);
223         Connection con = null;
224         PreparedStatement pstmt = null;
225         try {
226             con = DbConnectionManager.getConnection();
227             pstmt = con.prepareStatement(ALL_USERS);
228             ResultSet rs = pstmt.executeQuery();
229             DbConnectionManager.setFetchSize(rs, startIndex + numResults);
230             DbConnectionManager.scrollResultSet(rs, startIndex);
231             int count = 0;
232             while (rs.next() && count < numResults) {
233                 usernames.add(rs.getString(1));
234                 count++;
235             }
236             rs.close();
237         }
238         catch (SQLException e) {
239             Log.error(e);
240         }
241         finally {
242             try { if (pstmt != null) { pstmt.close(); } }
243             catch (Exception JavaDoc e) { Log.error(e); }
244             try { if (con != null) { con.close(); } }
245             catch (Exception JavaDoc e) { Log.error(e); }
246         }
247         return new UserCollection((String JavaDoc[])usernames.toArray(new String JavaDoc[usernames.size()]));
248     }
249
250     public void setName(String JavaDoc username, String JavaDoc name) throws UserNotFoundException {
251         Connection con = null;
252         PreparedStatement pstmt = null;
253         try {
254             con = DbConnectionManager.getConnection();
255             pstmt = con.prepareStatement(UPDATE_NAME);
256             pstmt.setString(1, name);
257             pstmt.setString(2, username);
258             pstmt.executeUpdate();
259         }
260         catch (SQLException sqle) {
261             throw new UserNotFoundException(sqle);
262         }
263         finally {
264             try { if (pstmt != null) pstmt.close(); }
265             catch (Exception JavaDoc e) { Log.error(e); }
266             try { if (con != null) con.close(); }
267             catch (Exception JavaDoc e) { Log.error(e); }
268         }
269     }
270
271     public void setEmail(String JavaDoc username, String JavaDoc email) throws UserNotFoundException {
272         Connection con = null;
273         PreparedStatement pstmt = null;
274         try {
275             con = DbConnectionManager.getConnection();
276             pstmt = con.prepareStatement(UPDATE_EMAIL);
277             pstmt.setString(1, email);
278             pstmt.setString(2, username);
279             pstmt.executeUpdate();
280         }
281         catch (SQLException sqle) {
282             throw new UserNotFoundException(sqle);
283         }
284         finally {
285             try { if (pstmt != null) pstmt.close(); }
286             catch (Exception JavaDoc e) { Log.error(e); }
287             try { if (con != null) con.close(); }
288             catch (Exception JavaDoc e) { Log.error(e); }
289         }
290     }
291
292     public void setCreationDate(String JavaDoc username, Date JavaDoc creationDate) throws UserNotFoundException {
293         Connection con = null;
294         PreparedStatement pstmt = null;
295         try {
296             con = DbConnectionManager.getConnection();
297             pstmt = con.prepareStatement(UPDATE_CREATION_DATE);
298             pstmt.setString(1, StringUtils.dateToMillis(creationDate));
299             pstmt.setString(2, username);
300             pstmt.executeUpdate();
301         }
302         catch (SQLException sqle) {
303             throw new UserNotFoundException(sqle);
304         }
305         finally {
306             try { if (pstmt != null) pstmt.close(); }
307             catch (Exception JavaDoc e) { Log.error(e); }
308             try { if (con != null) con.close(); }
309             catch (Exception JavaDoc e) { Log.error(e); }
310         }
311     }
312
313     public void setModificationDate(String JavaDoc username, Date JavaDoc modificationDate) throws UserNotFoundException {
314         Connection con = null;
315         PreparedStatement pstmt = null;
316         try {
317             con = DbConnectionManager.getConnection();
318             pstmt = con.prepareStatement(UPDATE_MODIFICATION_DATE);
319             pstmt.setString(1, StringUtils.dateToMillis(modificationDate));
320             pstmt.setString(2, username);
321             pstmt.executeUpdate();
322         }
323         catch (SQLException sqle) {
324             throw new UserNotFoundException(sqle);
325         }
326         finally {
327             try { if (pstmt != null) pstmt.close(); }
328             catch (Exception JavaDoc e) { Log.error(e); }
329             try { if (con != null) con.close(); }
330             catch (Exception JavaDoc e) { Log.error(e); }
331         }
332     }
333
334     public String JavaDoc getPassword(String JavaDoc username) throws UserNotFoundException {
335         Connection con = null;
336         PreparedStatement pstmt = null;
337         try {
338             con = DbConnectionManager.getConnection();
339             pstmt = con.prepareStatement(LOAD_PASSWORD);
340             pstmt.setString(1, username);
341             ResultSet rs = pstmt.executeQuery();
342             if (!rs.next()) {
343                 throw new UserNotFoundException(username);
344             }
345             return rs.getString(1);
346         }
347         catch (SQLException sqle) {
348             throw new UserNotFoundException(sqle);
349         }
350         finally {
351             try { if (pstmt != null) pstmt.close(); }
352             catch (Exception JavaDoc e) { Log.error(e); }
353             try { if (con != null) con.close(); }
354             catch (Exception JavaDoc e) { Log.error(e); }
355         }
356     }
357
358     public void setPassword(String JavaDoc username, String JavaDoc password) throws UserNotFoundException
359     {
360         Connection con = null;
361         PreparedStatement pstmt = null;
362         try {
363             con = DbConnectionManager.getConnection();
364             pstmt = con.prepareStatement(UPDATE_PASSWORD);
365             pstmt.setString(1, password);
366             pstmt.setString(2, username);
367             pstmt.executeUpdate();
368         }
369         catch (SQLException sqle) {
370             throw new UserNotFoundException(sqle);
371         }
372         finally {
373             try { if (pstmt != null) pstmt.close(); }
374             catch (Exception JavaDoc e) { Log.error(e); }
375             try { if (con != null) con.close(); }
376             catch (Exception JavaDoc e) { Log.error(e); }
377         }
378     }
379
380     public Set<String JavaDoc> getSearchFields() throws UnsupportedOperationException JavaDoc {
381         return new LinkedHashSet<String JavaDoc>(Arrays.asList("Username", "Name", "Email"));
382     }
383
384     public Collection<User> findUsers(Set<String JavaDoc> fields, String JavaDoc query)
385             throws UnsupportedOperationException JavaDoc
386     {
387         if (fields.isEmpty()) {
388             return Collections.emptyList();
389         }
390         if (!getSearchFields().containsAll(fields)) {
391             throw new IllegalArgumentException JavaDoc("Search fields " + fields + " are not valid.");
392         }
393         if (query == null || "".equals(query)) {
394             return Collections.emptyList();
395         }
396         // SQL LIKE queries don't map directly into a keyword/wildcard search like we want.
397
// Therefore, we do a best approximiation by replacing '*' with '%' and then
398
// surrounding the whole query with two '%'. This will return more data than desired,
399
// but is better than returning less data than desired.
400
query = "%" + query.replace('*', '%') + "%";
401         if (query.endsWith("%%")) {
402             query = query.substring(0, query.length()-1);
403         }
404
405         List<String JavaDoc> usernames = new ArrayList<String JavaDoc>(50);
406         Connection con = null;
407         Statement stmt = null;
408         try {
409             con = DbConnectionManager.getConnection();
410             stmt = con.createStatement();
411             StringBuilder JavaDoc sql = new StringBuilder JavaDoc();
412             sql.append("SELECT username FROM jiveUser WHERE");
413             boolean first = true;
414             if (fields.contains("Username")) {
415                 sql.append(" username LIKE '").append(StringUtils.escapeForSQL(query)).append("'");
416                 first = false;
417             }
418             if (fields.contains("Name")) {
419                 if (!first) {
420                     sql.append(" AND");
421                 }
422                 sql.append(" name LIKE '").append(StringUtils.escapeForSQL(query)).append("'");
423                 first = false;
424             }
425             if (fields.contains("Email")) {
426                 if (!first) {
427                     sql.append(" AND");
428                 }
429                 sql.append(" email LIKE '").append(StringUtils.escapeForSQL(query)).append("'");
430             }
431             ResultSet rs = stmt.executeQuery(sql.toString());
432             while (rs.next()) {
433                 usernames.add(rs.getString(1));
434             }
435             rs.close();
436         }
437         catch (SQLException e) {
438             Log.error(e);
439         }
440         finally {
441             try { if (stmt != null) { stmt.close(); } }
442             catch (Exception JavaDoc e) { Log.error(e); }
443             try { if (con != null) { con.close(); } }
444             catch (Exception JavaDoc e) { Log.error(e); }
445         }
446         return new UserCollection((String JavaDoc[])usernames.toArray(new String JavaDoc[usernames.size()]));
447     }
448
449     public Collection<User> findUsers(Set<String JavaDoc> fields, String JavaDoc query, int startIndex,
450             int numResults) throws UnsupportedOperationException JavaDoc
451     {
452         if (fields.isEmpty()) {
453             return Collections.emptyList();
454         }
455         if (!getSearchFields().containsAll(fields)) {
456             throw new IllegalArgumentException JavaDoc("Search fields " + fields + " are not valid.");
457         }
458         if (query == null || "".equals(query)) {
459             return Collections.emptyList();
460         }
461         // SQL LIKE queries don't map directly into a keyword/wildcard search like we want.
462
// Therefore, we do a best approximiation by replacing '*' with '%' and then
463
// surrounding the whole query with two '%'. This will return more data than desired,
464
// but is better than returning less data than desired.
465
query = "%" + query.replace('*', '%') + "%";
466         if (query.endsWith("%%")) {
467             query = query.substring(0, query.length()-1);
468         }
469
470         List<String JavaDoc> usernames = new ArrayList<String JavaDoc>(50);
471         Connection con = null;
472         Statement stmt = null;
473         try {
474             con = DbConnectionManager.getConnection();
475             stmt = con.createStatement();
476             StringBuilder JavaDoc sql = new StringBuilder JavaDoc();
477             sql.append("SELECT username FROM jiveUser WHERE");
478             boolean first = true;
479             if (fields.contains("Username")) {
480                 sql.append(" username LIKE '").append(StringUtils.escapeForSQL(query)).append("'");
481                 first = false;
482             }
483             if (fields.contains("Name")) {
484                 if (!first) {
485                     sql.append(" AND");
486                 }
487                 sql.append(" name LIKE '").append(StringUtils.escapeForSQL(query)).append("'");
488                 first = false;
489             }
490             if (fields.contains("Email")) {
491                 if (!first) {
492                     sql.append(" AND");
493                 }
494                 sql.append(" email LIKE '").append(StringUtils.escapeForSQL(query)).append("'");
495             }
496             ResultSet rs = stmt.executeQuery(sql.toString());
497             // Scroll to the start index.
498
DbConnectionManager.scrollResultSet(rs, startIndex);
499             int count = 0;
500             while (rs.next() && count < numResults) {
501                 usernames.add(rs.getString(1));
502                 count++;
503             }
504             rs.close();
505         }
506         catch (SQLException e) {
507             Log.error(e);
508         }
509         finally {
510             try { if (stmt != null) { stmt.close(); } }
511             catch (Exception JavaDoc e) { Log.error(e); }
512             try { if (con != null) { con.close(); } }
513             catch (Exception JavaDoc e) { Log.error(e); }
514         }
515         return new UserCollection((String JavaDoc[])usernames.toArray(new String JavaDoc[usernames.size()]));
516     }
517
518     public boolean isReadOnly() {
519         return false;
520     }
521 }
Popular Tags