KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > enterprise > jsf_jpa_war > UserManager


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the License at
8  * https://javaserverfaces.dev.java.net/CDDL.html or
9  * legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permission and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * your own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * [Name of File] [$Id: UserManager.java,v 1.2 2006/10/12 14:54:39 abadea Exp $] [Date]
22  *
23  * Copyright 2006 Sun Microsystems Inc. All Rights Reserved
24  */

25 package enterprise.jsf_jpa_war;
26
27 import java.util.Date JavaDoc;
28 import java.util.logging.Level JavaDoc;
29 import java.util.logging.Logger JavaDoc;
30 import javax.annotation.Resource;
31 import javax.faces.application.FacesMessage;
32 import javax.faces.context.ExternalContext;
33 import javax.faces.context.FacesContext;
34 import javax.persistence.EntityManager;
35 import javax.persistence.NoResultException;
36 import javax.persistence.PersistenceContext;
37 import javax.servlet.http.HttpSession JavaDoc;
38 import javax.transaction.UserTransaction JavaDoc;
39
40 /**
41  * <p>A simple managed bean to mediate between the user
42  * and the persistence layer.</p>
43  * @author rlubke
44  */

45 public class UserManager {
46     
47     /**
48      * <p>The key for the session scoped attribute holding the
49      * appropriate <code>Wuser</code> instance.</p>
50      */

51     public static final String JavaDoc USER_SESSION_KEY = "user";
52     
53     /**
54      * <p>The <code>PersistenceContext</code>.</p>
55      */

56     @PersistenceContext
57     private EntityManager em;
58     
59     /**
60      * <p>The transaction resource.</p>
61      */

62     @Resource
63     private UserTransaction JavaDoc utx;
64     
65     /**
66      * <p>User properties.</p>
67      */

68     private String JavaDoc username;
69     private String JavaDoc password;
70     private String JavaDoc passwordv;
71     private String JavaDoc fname;
72     private String JavaDoc lname;
73     
74     // -------------------------------------------------------------- Properties
75

76     public String JavaDoc getUsername() {
77         return username;
78     }
79     
80     public void setUsername(String JavaDoc username) {
81         this.username = username;
82     }
83     
84     public String JavaDoc getPassword() {
85         return password;
86     }
87     
88     public void setPassword(String JavaDoc password) {
89         this.password = password;
90     }
91     
92     public String JavaDoc getPasswordv() {
93         return passwordv;
94     }
95     
96     public void setPasswordv(String JavaDoc passwordv) {
97         this.passwordv = passwordv;
98     }
99     
100     public String JavaDoc getFname() {
101         return fname;
102     }
103     
104     public void setFname(String JavaDoc fname) {
105         this.fname = fname;
106     }
107     
108     public String JavaDoc getLname() {
109         return lname;
110     }
111     
112     public void setLname(String JavaDoc lname) {
113         this.lname = lname;
114     }
115     
116     
117     // ---------------------------------------------------------- Public Methods
118

119     
120     /**
121      * <p>Validates the user. If the user doesn't exist or the password
122      * is incorrect, the appropriate message is added to the current
123      * <code>FacesContext</code>. If the user successfully authenticates,
124      * navigate them to the page referenced by the outcome <code>app-main</code>.
125      * </p>
126      *
127      * @return <code>app-main</code> if the user authenticates, otherwise
128      * returns <code>null</code>
129      */

130     public String JavaDoc validateUser() {
131         FacesContext context = FacesContext.getCurrentInstance();
132         Wuser user = getUser();
133         if (user != null) {
134             if (!user.getPassword().equals(password)) {
135                 FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
136                                            "Login Failed!",
137                                            "The password specified is not correct.");
138                 context.addMessage(null, message);
139                 return null;
140             }
141             
142             context.getExternalContext().getSessionMap().put(USER_SESSION_KEY, user);
143             return "app-main";
144         } else {
145             FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
146                     "Login Failed!",
147                     "Username '"
148                     + username
149                     +
150                     "' does not exist.");
151             context.addMessage(null, message);
152             return null;
153         }
154     }
155     
156     /**
157      * <p>Creates a new <code>Wuser</code>. If the specified user name exists
158      * or an error occurs when persisting the Wuser instance, enqueue a message
159      * detailing the problem to the <code>FacesContext</code>. If the
160      * user is created, move the user back to the login view.</p>
161      *
162      * @return <code>login</code> if the user is created, otherwise
163      * returns <code>null</code>
164      */

165     public String JavaDoc createUser() {
166         FacesContext context = FacesContext.getCurrentInstance();
167         Wuser wuser = getUser();
168         if (wuser == null) {
169             if (!password.equals(passwordv)) {
170                 FacesMessage message = new FacesMessage("The specified passwords do not match. Please try again");
171                 context.addMessage(null, message);
172                 return null;
173             }
174             wuser = new Wuser();
175             wuser.setFirstname(fname);
176             wuser.setLastname(lname);
177             wuser.setPassword(password);
178             wuser.setUsername(username);
179             wuser.setSince(new Date JavaDoc());
180             try {
181                 utx.begin();
182                 em.persist(wuser);
183                 utx.commit();
184                 return "login";
185             } catch (Exception JavaDoc e) {
186                 FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
187                                                         "Error creating user!",
188                                                         "Unexpected error when creating your account. Please contact the system Administrator");
189                 context.addMessage(null, message);
190                 Logger.getAnonymousLogger().log(Level.SEVERE,
191                                                 "Unable to create new user",
192                                                 e);
193                 return null;
194             }
195         } else {
196             FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
197                                                     "Username '"
198                                                       + username
199                                                       + "' already exists! ",
200                                                     "Please choose a different username.");
201             context.addMessage(null, message);
202             return null;
203         }
204     }
205     
206     
207     /**
208      * <p>When invoked, it will invalidate the user's session
209      * and move them to the login view.</p>
210      *
211      * @return <code>login</code>
212      */

213     public String JavaDoc logout() {
214         HttpSession JavaDoc session = (HttpSession JavaDoc)
215              FacesContext.getCurrentInstance().getExternalContext().getSession(false);
216         if (session != null) {
217             session.invalidate();
218         }
219         return "login";
220         
221     }
222     
223     // --------------------------------------------------------- Private Methods
224

225     
226     /**
227      * <p>This will attempt to lookup a <code>Wuser</code> object
228      * based on the provided user name.</p>
229      *
230      * @return a <code>Wuser</code> object associated with the current
231      * username, otherwise, if no <code>Wuser</code> can be found,
232      * returns <code>null</code>
233      */

234     private Wuser getUser() {
235         try {
236             Wuser user = (Wuser)
237             em.createNamedQuery("Wuser.findByUsername").
238                     setParameter("username", username).getSingleResult();
239             return user;
240         } catch (NoResultException nre) {
241             return null;
242         }
243     }
244    
245 }
246
Popular Tags