KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > javabb > transaction > UserTransaction


1 package org.javabb.transaction;
2
3 import java.util.Date JavaDoc;
4 import java.util.HashMap JavaDoc;
5 import java.util.List JavaDoc;
6 import java.util.Map JavaDoc;
7
8 import org.apache.commons.lang.StringUtils;
9 import org.javabb.component.VelocityTemplate;
10 import org.javabb.dao.entity.IUserDAO;
11 import org.javabb.dao.entity.IUserSecurityDAO;
12 import org.javabb.infra.Configuration;
13 import org.javabb.infra.ConfigurationFactory;
14 import org.javabb.infra.Constants;
15 import org.javabb.infra.Email;
16 import org.javabb.infra.Paging;
17 import org.javabb.infra.UserContext;
18 import org.javabb.infra.Utils;
19 import org.javabb.vo.User;
20 import org.javabb.vo.UserRank;
21
22 /*
23  * Copyright 2004 JavaFree.org
24  *
25  * Licensed under the Apache License, Version 2.0 (the "License");
26  * you may not use this file except in compliance with the License.
27  * You may obtain a copy of the License at
28  *
29  * http://www.apache.org/licenses/LICENSE-2.0
30  *
31  * Unless required by applicable law or agreed to in writing, software
32  * distributed under the License is distributed on an "AS IS" BASIS,
33  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
34  * See the License for the specific language governing permissions and
35  * limitations under the License.
36  */

37
38 /**
39  * $Id: UserTransaction.java,v 1.34.2.4.2.1.2.4 2006/08/01 18:13:26 daltoncamargo Exp $
40  * @author Dalton Camargo - <a HREF="mailto:dalton@javabb.org">dalton@javabb.org </a>
41  * @author Ronald Tetsuo Miura
42  */

43 public class UserTransaction extends Transaction {
44
45
46     private IUserDAO _userDAO;
47     
48     //UserRank Caches
49
private static List JavaDoc userRanksCache;
50     
51     public void setUserDAO(IUserDAO userDAO) {
52         _userDAO = userDAO;
53     }
54
55     public User getUser(Long JavaDoc userId) {
56         return _userDAO.loadUser(userId);
57     }
58
59     private IUserSecurityDAO userSecurityDAO;
60     public void setUserSecurityDAO(IUserSecurityDAO userSecurityDAO) {
61         this.userSecurityDAO = userSecurityDAO;
62     }
63     
64     /**
65      * @param userId
66      */

67     public void sumNumberMsgUser(Long JavaDoc userId) {
68         User user = _userDAO.loadUser(userId);
69         long count = user.getUser_posts().longValue();
70         count++;
71         user.setUser_posts(new Long JavaDoc(count));
72     }
73
74     /**
75      * @param userId
76      */

77     public void subNumberMsgUser(Long JavaDoc userId) {
78         User u = _userDAO.loadUser(userId);
79
80         long count = u.getUser_posts().longValue();
81         count--;
82         u.setUser_posts(new Long JavaDoc(count));
83     }
84
85     /**
86      * @param name
87      * @param passwd
88      * @return user
89      */

90     public User verifyLogin(String JavaDoc name, String JavaDoc passwd) {
91         User user = _userDAO.verificaLogin(name, passwd);
92         if (!UserContext.getContext().isAuthenticated()) {
93             UserContext.getContext().setUser(user);
94         }
95         return user;
96     }
97
98     /**
99      * @param userId
100      * @param usercode
101      * @return user
102      */

103     public User verifyUserCode(Long JavaDoc userId, String JavaDoc usercode) {
104         User user = _userDAO.loadByUsercode(usercode);
105         if (!UserContext.getContext().isAuthenticated()) {
106             UserContext.getContext().setUser(user);
107         }
108         return user;
109     }
110
111     /**
112      * @param username
113      * @return user
114      */

115     public User findUserByUserName(String JavaDoc username) {
116         return _userDAO.loadByUsername(username);
117     }
118     
119     public List JavaDoc findUserListByUserName(String JavaDoc username) {
120         return _userDAO.loadListByUsername(username);
121     }
122
123     /**
124      * @param email
125      * @return user
126      */

127     public boolean isEmailValid(String JavaDoc email, Long JavaDoc userId) {
128         List JavaDoc users = _userDAO.findByEmail(email, userId);
129         return !users.isEmpty();
130     }
131
132     /**
133      * @param email
134      * @return user
135      */

136     public boolean isEmailValid(String JavaDoc email) {
137         List JavaDoc users = _userDAO.findByEmail(email);
138         return !users.isEmpty();
139     }
140     
141     
142     /**
143      * @return user
144      */

145     public User lastUserRegistered() {
146         return _userDAO.lastUserRegistered();
147     }
148
149     /**
150      * Delete an user and move your messages to user Guest - ID=0
151      * @param user
152      */

153     public void deleteUser(User user) {
154         _userDAO.deleteUser(user);
155     }
156
157     /**
158      * @param sortBy
159      * @param sortOrder
160      * @param pageNumber
161      * @return list of registered users
162      */

163     public List JavaDoc listAllRegisteredUsers(String JavaDoc sortBy, String JavaDoc sortOrder, int pageNumber) {
164
165         // PAGING ** Obtendo informações
166
int rowsPerPage = ConfigurationFactory.getConf().topicsPage.intValue();
167         long nroRecords = _userDAO.countAllUsers();
168         long totalPages = Paging.getNroPages(rowsPerPage, nroRecords);
169         Paging.setPageList(pageNumber, totalPages);
170
171         List JavaDoc users = _userDAO.findAllSortedBy(pageNumber,
172             rowsPerPage,"o." +
173             StringUtils.defaultString(sortBy, "idUser"),
174             StringUtils.defaultString(sortOrder, "asc"));
175
176         return users;
177     }
178
179     /**
180      * This method search or not(case userName parameter has null) users by username
181      * @param userName - Can be null, case this, the method return all users
182      * @param pageNumber - For paging
183      * @return list of users
184      */

185     public List JavaDoc listUsersByWhere(User user, int pageNumber) {
186
187         int itemsPerPage = ConfigurationFactory.getConf().topicsPage.intValue();
188
189         List JavaDoc users = null;
190
191         if (user != null && user.getUser() != null
192                 && !user.getUser().equals("")) {
193             users = _userDAO.findAllUsernameLike(user.getUser(), pageNumber, itemsPerPage);
194         }else if(user != null && user.getAdmin() != null && user.getAdmin().intValue() == 1){
195             users = _userDAO.findAllUserAdmin(pageNumber, itemsPerPage);
196         } else {
197             long userCount = _userDAO.countAllUsers();
198             int pageCount = Paging.getNroPages(itemsPerPage, userCount);
199             Paging.setPageList(pageNumber, pageCount);
200             users = _userDAO.findAll(pageNumber, itemsPerPage);
201         }
202         return users;
203     }
204
205     /**
206      * @param user
207      */

208     public User updateProfileUser(User _user, boolean byAdmin) {
209         
210         User loggedUser = null;
211         
212 // user updated by Admin Panel control
213
if(byAdmin){
214             loggedUser = _user;
215         } else {
216             loggedUser = UserContext.getContext().getUser();
217         }
218         
219         Long JavaDoc userId = loggedUser.getId();
220         
221         User userToUpdate = getUser(userId);
222         if ((_user.getEmail() != null) && !"".equals(_user.getEmail())) {
223             userToUpdate.setEmail(_user.getEmail());
224         }
225
226         userToUpdate.setName(_user.getName());
227         userToUpdate.setUser_icq(_user.getUser_icq());
228         userToUpdate.setUser_aim(_user.getUser_aim());
229         userToUpdate.setUser_msnm(_user.getUser_msnm());
230         userToUpdate.setUser_yim(_user.getUser_yim());
231         userToUpdate.setWebsite(Utils.validateWebSite(_user.getWebsite()));
232         userToUpdate.setLocalizacao(_user.getLocalizacao());
233         userToUpdate.setOccupation(_user.getOccupation());
234         userToUpdate.setUser_interests(_user.getUser_interests());
235         userToUpdate.setUserSig(_user.getUserSig());
236         userToUpdate.setShow_mail(_user.getShow_mail());
237         userToUpdate.setShow_signature(_user.getShow_signature());
238         userToUpdate.setUser_avatar(Utils.validateWebSite(_user.getUser_avatar()));
239
240         if ((_user.getPasswordHash() != null) && !"".equals(_user.getPasswordHash())) {
241             String JavaDoc psw = Utils.encrypt(_user.getPasswordHash());
242             userToUpdate.setPasswordHash(psw);
243         }
244         return userToUpdate;
245     }
246
247     public void updateAmRights(User _user){
248         User userToUpdate = this.getUser(_user.getIdUser());
249         userToUpdate.setAdmin(_user.getAdmin());
250     }
251     
252     /**
253      * @param user
254      */

255     public void createUser(User user) throws Exception JavaDoc{
256         _userDAO.create(user);
257     }
258
259     /**
260      */

261     public void updateVisitTimestamp() {
262         User user = UserContext.getContext().getUser();
263         if (user == null) {
264             return;
265         }
266         Long JavaDoc userId = user.getId();
267         if (userId == null) {
268             return;
269         }
270         user = _userDAO.loadUser(userId);
271         user.setLastVisitTimestamp(new Date JavaDoc());
272     }
273     
274     public void sendSecurityCode(User user){
275         Configuration conf = new Configuration();
276         
277         user = _userDAO.loadUser(user.getId());
278         
279         //cria o hash para ser enviado ao user
280
String JavaDoc hash = System.currentTimeMillis()+user.getUserCode()+"";
281         
282         //salva o hash no BD
283
String JavaDoc hashEncrypt = Utils.encrypt(hash);
284         user.setHash_fpwd(hashEncrypt);
285         _userDAO.update(user);
286         
287         //url q redireciona o user para receber sua nova senha
288
String JavaDoc url = "verify_forget_pwd.jbb?u="+user.getIdUser()+"&userHash="+hash;
289         
290         //envia o meail para o user confirmando sua solicitação de nova senha
291
Map JavaDoc mailMap = new HashMap JavaDoc();
292         mailMap.put("conf", conf);
293         mailMap.put("url", url);
294         mailMap.put("user", user);
295        
296         String JavaDoc message = VelocityTemplate.makeTemplate(mailMap, Constants.mailForgetPwd);
297         Email.sendMail(conf.adminMail, user.getEmail(), "Solicitação de Nova Senha", message, true);
298          
299     }
300     
301     public void verifyForgetPwd(Long JavaDoc userId, String JavaDoc hash){
302         User user = new User();
303         user.setIdUser(userId);
304         user = _userDAO.loadUser(user.getId());
305         if(user.getHash_fpwd() != null && hash != null && Utils.encrypt(hash).equals(user.getHash_fpwd())){
306             //gera a nova senha q será enviada ao user
307
String JavaDoc novaSenha = user.getUserCode().substring(0, 6);
308             
309             //criptografa a nova senha e inseri no BD
310
user.setPasswordHash(Utils.encrypt(novaSenha));
311             _userDAO.update(user);
312             
313             //envia um email para o user com a nova senha
314
Configuration conf = new Configuration();
315             
316             Map JavaDoc mailMap = new HashMap JavaDoc();
317             mailMap.put("conf", conf);
318             mailMap.put("user", user);
319             mailMap.put("pwd", novaSenha);
320            
321             String JavaDoc message = VelocityTemplate.makeTemplate(mailMap, Constants.sendNewPassword);
322             Email.sendMail(conf.adminMail, user.getEmail(), "Nova Senha", message, true);
323         }
324         
325     }
326
327     /**
328      * Get a list of UserRanks in the cache
329      * @return
330      */

331     public List JavaDoc getUserRanks(){
332         if(userRanksCache == null){
333             userRanksCache = _userDAO.loadUserRanks();
334         }
335         return userRanksCache;
336     }
337     
338     /**
339      * Load the UserRank by a Long value
340      * @param postCount
341      * @return
342      */

343     public UserRank getUserRank(Long JavaDoc postCount){
344         return getUniqueUserRankByCache(postCount);
345     }
346
347     /**
348      * Use Long value to search by the UserRank
349      * @param postCount
350      * @return
351      */

352     private UserRank getUniqueUserRankByCache(Long JavaDoc postCount){
353         if(postCount == null || getUserRanks() == null){
354             return null;
355         }
356
357         int pCount = postCount.intValue();
358         for(int i=0; i<userRanksCache.size(); i++){
359             UserRank usrRank = (UserRank)userRanksCache.get(i);
360             if(pCount > usrRank.getRankMin().intValue()
361                     && pCount < usrRank.getRankMax().intValue()){
362                 return usrRank;
363             }
364         }
365         return null;
366     }
367     
368     /**
369      * Used by Quartz task to renew
370      * all hashs security codes
371      */

372     public void renewUserSecurityCode(){
373         List JavaDoc users = _userDAO.findAll(0, Integer.MAX_VALUE);
374         if(users != null){
375             for(int i=0; i < users.size(); i++){
376                 try {
377                     User user = (User)users.get(i);
378                     log.debug("Setting new SecurityCode to user "+ user.getUser());
379                     
380                     String JavaDoc hashCode = Utils.getCodeUser(user.getUser());
381                     Long JavaDoc userId = user.getId();
382                     userSecurityDAO.createHashCode(userId, hashCode);
383                     
384                     log.debug("SecurityCode setted!");
385                 } catch (Exception JavaDoc e) {
386                     log.debug("Hidden the Exception on SecurityCode update");
387                 }
388             }
389         }
390     }
391 }
Popular Tags