KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > barracudaDiscRack > presentation > personMgmt > Login


1 /*
2  * Enhydra Java Application Server Project
3  *
4  * The contents of this file are subject to the Enhydra Public License
5  * Version 1.1 (the "License"); you may not use this file except in
6  * compliance with the License. You may obtain a copy of the License on
7  * the Enhydra web site ( http://www.enhydra.org/ ).
8  *
9  * Software distributed under the License is distributed on an "AS IS"
10  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
11  * the License for the specific terms governing rights and limitations
12  * under the License.
13  *
14  * The Initial Developer of the Enhydra Application Server is Lutris
15  * Technologies, Inc. The Enhydra Application Server and portions created
16  * by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
17  * All Rights Reserved.
18  *
19  * Contributor(s):
20  *
21  * $Id: Login.java,v 1.4 2004/12/03 14:12:34 slobodan Exp $
22  */

23
24 package barracudaDiscRack.presentation.personMgmt;
25
26 import barracudaDiscRack.business.person.*;
27 import barracudaDiscRack.presentation.BasePO;
28 import com.lutris.appserver.server.httpPresentation.*;
29 import com.lutris.appserver.server.session.*;
30 import com.lutris.util.*;
31 import org.enhydra.xml.xmlc.*;
32 import org.enhydra.xml.xmlc.html.*;
33 import org.w3c.dom.*;
34 import org.w3c.dom.html.*;
35 import org.enhydra.xml.xmlc.XMLObject;
36 import barracudaDiscRack.business.DiscRackBusinessException;
37 import barracudaDiscRack.presentation.DiscRackPresentationException;
38
39 // import barracuda specifics
40
import org.enhydra.barracuda.core.comp.*;
41 import org.enhydra.barracuda.core.forms.*;
42 import org.enhydra.barracuda.core.forms.validators.*;
43 import org.enhydra.barracuda.plankton.data.*;
44 import org.enhydra.barracuda.core.view.ViewCapabilities;
45 import org.enhydra.barracuda.core.event.*;
46 import org.enhydra.barracuda.core.comp.model.*;
47 import org.enhydra.barracuda.plankton.data.CollectionsUtil;
48
49 // import java specifics
50
import javax.servlet.http.*;
51 import javax.servlet.http.HttpServletRequest JavaDoc;
52 import javax.servlet.http.HttpServletResponse JavaDoc;
53 import java.io.*;
54 import java.util.List JavaDoc;
55 import java.util.Iterator JavaDoc;
56 import java.util.Collection JavaDoc;
57
58 import org.apache.log4j.*;
59
60 /**
61  * Login.java handles the login functionality of the DiscRack app.
62  *
63  * @author
64  * @version
65  */

66 public class Login extends BasePO {
67
68   /**
69    * Constants
70    */

71   private static String JavaDoc SUBMIT_NAME = "submit";
72   private static String JavaDoc LOGIN_NAME = "login";
73   private static String JavaDoc PASSWORD_NAME = "password";
74   private static String JavaDoc ERROR_NAME = "ERROR_NAME";
75
76   /**
77    * Superclass method override
78    */

79   public boolean loggedInUserRequired() {
80     return false;
81   }
82
83   /**
84    * Default event. Just show the page.
85    */

86   public XMLObject handleDefault() throws HttpPresentationException {
87     return showPage(null);
88   }
89
90   /**
91    * Process login data
92    *
93    * @return wml document
94    * @exception HttpPresentationException
95    */

96   public XMLObject handleLogin() throws HttpPresentationException {
97     String JavaDoc login = this.getComms().request.getParameter(LOGIN_NAME);
98     String JavaDoc password = this.getComms().request.getParameter(PASSWORD_NAME);
99     Person user = null;
100
101     try {
102       user = PersonFactory.findPerson(login);
103       if (null == user || !user.getPassword().equals(password)) {
104         return showPage("Invalid username or password");
105         // Show error message that user not found (bad username/password)
106
}
107       else {
108         this.setUser(user);
109                 throw new ClientPageRedirectException(getComms().request.getApplicationPath()+DISC_CATALOG_PAGE);
110       }
111     }
112     catch (DiscRackBusinessException ex) {
113       this.writeDebugMsg("System error finding user: " + ex.getMessage());
114       throw new DiscRackPresentationException("System error finding user", ex);
115     }
116   }
117
118   /**
119    * handle logout event
120    *
121    * @return html document
122    * @exception HttpPresentationException
123    */

124   public XMLObject handleLogout() throws HttpPresentationException {
125     this.removeUserFromSession();
126     return new ExitHTML();
127   }
128
129   /**
130    * handle throw exception event.
131    *
132    * @return html document
133    * @exception Exception
134    */

135   public XMLObject handleThrowException() throws Exception JavaDoc {
136     throw new Exception JavaDoc(
137         "This is a test exception thrown from Login.java handleThrowException()");
138   }
139
140   /**
141    * display page
142    *
143    * @param errorMsg, the error messages
144    * @return html document
145    */

146   public XMLObject showPage(String JavaDoc errorMsg) {
147
148     LoginHTML page = (LoginHTML) myComms.xmlcFactory.create(LoginHTML.class);
149
150     if (null != errorMsg ||
151         null != (errorMsg = this.getSessionData().getAndClearUserMessage())) {
152       page.setTextErrorText(errorMsg);
153     }
154     else {
155       page.getElementErrorText().getParentNode().removeChild(page.
156           getElementErrorText());
157     }
158
159     return page;
160   }
161
162   //------------------------------------------------------------
163
// Use Barracuda Component Model
164
//------------------------------------------------------------
165

166   /**
167    * handle special event to show page using Barracuda
168    */

169   public XMLObject handleShowUsingBarracuda() throws HttpPresentationException {
170     return this.showPageUsingBarracuda(new DefaultStateMap());
171   }
172
173   /**
174    * handle special event to login using Barracuda
175    */

176   public XMLObject handleLoginUsingBarracuda() throws HttpPresentationException {
177
178     //create the login form
179
ValidationException ve = null;
180     if (logger.isDebugEnabled())
181       logger.debug("Creating login form");
182     LoginForm lf = new LoginForm(getComms().session.getHttpSession());
183     try {
184       //map/validate the form
185
if (logger.isDebugEnabled())
186         logger.debug("Mapping/Validating login form");
187       lf.map(this.getComms().request.getHttpServletRequest()).validate(true);
188     }
189     catch (ValidationException e) {
190       removeUserFromSession();
191       if (logger.isDebugEnabled())
192         logger.debug("Validation Exception: " + e);
193
194       if (logger.isDebugEnabled()){
195         CollectionsUtil.printStackTrace(e.getExceptionList(), 0, logger, null);
196       }
197
198       ve = e;
199     }
200
201     //if no errors redirect to the catalog screen
202
if (ve == null) {
203       if (logger.isDebugEnabled())
204         logger.debug("Redirecting to " + BasePO.DISC_CATALOG_PAGE);
205       throw new ClientPageRedirectException(getComms().request.getApplicationPath()+DISC_CATALOG_PAGE);
206     }
207
208     if (logger.isDebugEnabled())
209       logger.debug("Displaying login page");
210
211       // create a context for the rendering
212
StateMap context = new DefaultStateMap();
213
214     //store a copy of the form and any errors in the context
215
if (logger.isDebugEnabled())
216       logger.debug("Saving form, errors");
217     context.putState(LOGIN_FORM, lf);
218     context.putState(LOGIN_ERR, ve);
219
220     return this.showPageUsingBarracuda(context);
221   }
222
223   /**
224    * display page using Barracuda
225    *
226    * @param context, the error messages
227    * @return html document
228    */

229   public XMLObject showPageUsingBarracuda(StateMap context) {
230
231     LoginHTML page = (LoginHTML) myComms.xmlcFactory.create(LoginHTML.class);
232
233     //create a template component and render it
234
Node node = page.getDocument().getElementById("LoginForm");
235
236     TemplateView tv = new DefaultTemplateView(node);
237     TemplateModel tm = new LoginModel(context);
238     BTemplate templateComp = new BTemplate(tm);
239     templateComp.setView(tv);
240
241     try {
242       HttpServletRequest JavaDoc ireq = this.getComms().request.getHttpServletRequest();
243       HttpServletResponse JavaDoc ires = this.getComms().response.getHttpServletResponse();
244
245       ViewContext vc = new DefaultViewContext(new ViewCapabilities(),
246                                               ireq,
247                                               ires);
248       templateComp.render(vc);
249
250     }
251     catch (RenderException re) {
252       this.writeDebugMsg("Render err:" + re);
253     }
254
255     return page;
256   }
257
258   //=================================================================
259
// NOTE - the following are duplicated from LoginEventGateway.java
260
// (with modifications to remove any event model dependencies)
261
// purely for illustration of the standalone use of the
262
// Barracuda component/form models.
263
//=================================================================
264

265   // setup a logger for the class
266
protected static Logger logger = Logger.getLogger(Login.class.getName());
267
268   //private constants
269
private static final String JavaDoc LOGIN_FORM = LoginEventGateway.class.getName() +
270       ".LoginForm"; //LoginForm
271
private static final String JavaDoc LOGIN_ERR = LoginEventGateway.class.getName() +
272       ".LoginErr"; //ValidationException
273

274   //------------------------------------------------------------
275
// Template Models
276
//------------------------------------------------------------
277
/**
278    * LoginModel
279    */

280   class LoginModel extends AbstractTemplateModel {
281
282     LoginForm fm = null;
283     ValidationException ve = null;
284
285     //constructor (extract form, exception from context)
286
public LoginModel(StateMap context) {
287       fm = (LoginForm) context.getState(LOGIN_FORM);
288       ve = (ValidationException) context.getState(LOGIN_ERR);
289     }
290
291     //register the model by name
292
public String JavaDoc getName() {
293       return "Login";
294     }
295
296       public Object JavaDoc getItem(String JavaDoc key) {
297         ViewContext vc = getViewContext();
298         if (key.equals("Username")) {
299           return (fm != null ? fm.getStringVal(LoginForm.USER, "") : "");
300         }
301         else if (key.equals("Password")) {
302           return (fm != null ? fm.getStringVal(LoginForm.PASSWORD, "") : "");
303         }
304         else if (key.equals("Errors")) {
305           if (ve == null) return "";
306           List JavaDoc errlist = ve.getExceptionList();
307           StringBuffer JavaDoc sb = new StringBuffer JavaDoc(errlist.size() > 1 ?
308                                              "There were several errors:" : "");
309           Iterator JavaDoc it = errlist.iterator();
310           while (it.hasNext()) {
311             sb.append(" " + ( (ValidationException) it.next()).getMessage());
312           }
313           return sb.toString();
314         }
315         else {
316           return super.getItem(key);
317         }
318
319       }
320   }
321
322   //------------------------------------------------------------
323
// HTML Form Mappings, Validators
324
//------------------------------------------------------------
325

326   /**
327    * Login form - define the login form
328    */

329   class LoginForm extends DefaultFormMap {
330     //login form constants (these values correspond to the HTML param names)
331
static final String JavaDoc USER = "login";
332     static final String JavaDoc PASSWORD = "password";
333
334     HttpSession session = null;
335
336     public LoginForm(HttpSession isession) {
337       session = isession;
338
339       //define the elements
340
if (logger.isDebugEnabled())
341         logger.debug("Defining Login form elements");
342       this.defineElement(new DefaultFormElement(USER, FormType.STRING, null,
343                                                 new
344                                                 NotNullValidator(
345           "You must enter a Login.")));
346       this.defineElement(new DefaultFormElement(PASSWORD, FormType.STRING, null,
347                                                 new
348                                                 NotNullValidator(
349           "You must enter a Password.")));
350
351       //define a form validator
352
if (logger.isDebugEnabled())
353         logger.debug("Defining Registration form validator");
354       this.defineValidator(new LoginValidator(session));
355     }
356
357     /**
358      * we override this method because instead of using the default validation
359      * process (validate elements, then form), we don't want to validate at all
360      * if they are already logged in...we just assume they're valid and return.
361      */

362     public FormMap validate(boolean deferExceptions) throws ValidationException {
363       //see if they are already logged in. If so, just consider them valid
364
if (logger.isDebugEnabled())
365         logger.debug("Checking to see if already logged in (prevalidated)");
366       Person p = getUser();
367       if (null != p) {
368         try {
369           String JavaDoc fuser = this.getStringVal(LoginForm.USER);
370           String JavaDoc fpassword = this.getStringVal(LoginForm.PASSWORD);
371           if (fuser == null && fpassword == null)
372             return this; //if user/pwd = null, just use the current settings
373
if (p.getLogin().equals(fuser) &&
374               p.getPassword().equals(fpassword))
375             return this; //if they're != null, make sure they match, otherwise, we'll want to force a complete revalidate
376
}
377         catch (DiscRackBusinessException e) {
378         }
379       }
380
381       //if not, go ahead and validate
382
return super.validate(deferExceptions);
383     }
384   }
385
386   /**
387    * Login validator - define a custom form validator
388    */

389   class LoginValidator extends DefaultFormValidator {
390
391     HttpSession session = null;
392
393     public LoginValidator(HttpSession isession) {
394       session = isession;
395     }
396
397     public void validateForm(FormMap imap, boolean deferExceptions) throws
398         ValidationException {
399       if (logger.isDebugEnabled())
400         logger.debug("Validating login form");
401
402         //validate the login information
403
if (logger.isDebugEnabled())
404         logger.debug("Validate the user/pwd info");
405       LoginForm map = (LoginForm) imap;
406       String JavaDoc user = map.getStringVal(LoginForm.USER);
407       String JavaDoc password = map.getStringVal(LoginForm.PASSWORD);
408       String JavaDoc errMsg = "Invalid username or password from LoginValidator. Please check your information and try again.";
409       try {
410         //make sure the login exists and the passwords match
411
Person person = PersonFactory.findPerson(user);
412         if (person == null)
413           throw new ValidationException(map.getElement(LoginForm.USER), errMsg);
414         if (!person.getPassword().equals(password))
415           throw new ValidationException(map.getElement(LoginForm.PASSWORD),
416                                         errMsg);
417
418         //log them in
419
setUser(person);
420       }
421       catch (DiscRackBusinessException e) {
422         removeUserFromSession(); //just to be sure we don't get stuck in a loop
423
throw new ValidationException(map.getElement(LoginForm.USER),
424                                       "System error finding user: " +
425                                       e.getMessage() + ". Please try again. If the problem persists, contact your system administrator.",
426                                       e);
427       }
428       catch (DiscRackPresentationException e) {
429         throw new ValidationException(map.getElement(LoginForm.USER),
430                                       "System error setting user: " +
431                                       e.getMessage() + ". Please try again. If the problem persists, contact your system administrator.",
432                                       e);
433       }
434     }
435   }
436 }
Popular Tags