KickJava   Java API By Example, From Geeks To Geeks.

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


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

24
25 package barracudaDiscRack.presentation.personMgmt;
26
27 // import disc rack specifics
28
import barracudaDiscRack.presentation.*;
29 import barracudaDiscRack.presentation.personMgmt.events.*;
30 import barracudaDiscRack.business.person.*;
31 import barracudaDiscRack.business.DiscRackBusinessException;
32
33 // import barracuda specifics
34
import org.enhydra.barracuda.core.event.*;
35 import org.enhydra.barracuda.core.forms.*;
36 import org.enhydra.barracuda.core.forms.validators.*;
37 import org.enhydra.barracuda.core.comp.*;
38 import org.enhydra.barracuda.core.util.dom.*;
39 import org.enhydra.barracuda.plankton.data.CollectionsUtil;
40
41 import org.apache.log4j.*;
42
43 // import dom specifics
44
import org.w3c.dom.*;
45 import org.w3c.dom.html.*;
46
47 // import java specifics
48
import javax.servlet.*;
49 import javax.servlet.http.*;
50 import java.io.*;
51 import java.util.List JavaDoc;
52 import java.util.Iterator JavaDoc;
53
54 /**
55  * LoginEventGateway handles the login functionality of the DiscRack app.
56  *
57  * @author
58  * @version
59  */

60 public class LoginEventGateway extends BaseDiscRackEventGateway {
61
62     public LoginEventGateway() {
63         //specify who's interested in what
64
specifyLocalEventInterests(getLoginFactory, GetLogin.class);
65         specifyLocalEventInterests(renderLoginFactory, RenderLogin.class);
66         specifyLocalEventInterests(doLoginFactory, DoLogin.class);
67     }
68
69     // setup the required listener factories
70
private ListenerFactory getLoginFactory = new DefaultListenerFactory() {
71         public BaseEventListener getInstance() {
72             return new GetLoginHandler();
73         } public String JavaDoc getListenerID() {
74             return getID(GetLoginHandler.class);
75         }
76     };
77
78     private ListenerFactory renderLoginFactory = new DefaultListenerFactory() {
79         public BaseEventListener getInstance() {
80             return new RenderLoginHandler();
81         } public String JavaDoc getListenerID() {
82             return getID(RenderLoginHandler.class);
83         }
84     };
85
86     private ListenerFactory doLoginFactory = new DefaultListenerFactory() {
87         public BaseEventListener getInstance() {
88             return new DoLoginHandler();
89         } public String JavaDoc getListenerID() {
90             return getID(DoLoginHandler.class);
91         }
92     };
93
94     // setup a logger for the class
95
protected static Logger logger = Logger.getLogger(LoginEventGateway.class.getName());
96
97     //private constants
98
private static final String JavaDoc LOGIN_FORM = LoginEventGateway.class.getName()+".LoginForm"; //LoginForm
99
private static final String JavaDoc LOGIN_ERR = LoginEventGateway.class.getName()+".LoginErr"; //ValidationException
100

101     //------------------------------------------------------------
102
// Model 2 - Controller Event Handlers
103
//------------------------------------------------------------
104
/**
105      * GetLoginHandler - this is where we handle any GetLogin event
106      * requests. If they are already logged in, just redirect on.
107      */

108     class GetLoginHandler extends DefaultBaseEventListener {
109         public void handleControlEvent(ControlEventContext context) throws EventException, ServletException, IOException {
110             // MUST DO FIRST - initialize things from the context
111
initUsingContext( context );
112
113             //unpack the necessary entities from the context
114
DispatchQueue queue = context.getQueue();
115
116             // if it looks like we are already logged in, try and auto-login
117
// otherwise, just render the login screen
118
if ( null != getUser() ) {
119                 if ( logger.isDebugEnabled() ) logger.debug("Adding DoLogin to Queue (Auto-login)");
120                 queue.addEvent(new DoLogin(context.getEvent()));
121             } else {
122                 if ( logger.isDebugEnabled() ) logger.debug("Adding RenderLogin to Queue");
123                 queue.addEvent(new RenderLogin(context.getEvent()));
124             }
125         }
126     }
127
128     /**
129      * DoLoginHandler - this is where we handle any AttemptLogin
130      * events. Validate and then redirect accordingly.
131      */

132     class DoLoginHandler extends DefaultBaseEventListener {
133         public void handleControlEvent(ControlEventContext context) throws EventException, ServletException, IOException {
134             // MUST DO FIRST - initialize things from the context
135
initUsingContext( context );
136
137             //unpack the necessary entities from the context
138
HttpServletRequest req = context.getRequest();
139
140             //create the login form
141
ValidationException ve = null;
142             if ( logger.isDebugEnabled() ) logger.debug("Creating login form");
143             LoginForm lf = new LoginForm( getComms().session.getHttpSession() );
144             try {
145                 //map/validate the form
146
if ( logger.isDebugEnabled() ) logger.debug("Mapping/Validating login form");
147                 lf.map(req).validate(true);
148             } catch ( ValidationException e ) {
149                 removeUserFromSession();
150                 if ( logger.isDebugEnabled() ) logger.debug("Validation Exception: "+e);
151
152                 if ( logger.isDebugEnabled() )
153                   CollectionsUtil.printStackTrace(e.getExceptionList(), 0, logger, null);
154
155                 ve = e;
156             }
157
158             //store a copy of the form and any errors in the queue
159
if ( logger.isDebugEnabled() ) logger.debug("Saving form, errors");
160             context.putState(LOGIN_FORM, lf);
161             context.putState(LOGIN_ERR, ve);
162
163             //redirect to the Main screen
164
if ( ve==null ) {
165                 if ( logger.isDebugEnabled() ) logger.debug("Redirecting to " + BasePO.DISC_EVENT_CATALOG_PAGE);
166                 throw new ClientSideRedirectException(BasePO.DISC_EVENT_CATALOG_PAGE);
167             } else {
168                 if ( logger.isDebugEnabled() ) logger.debug("InterruptDispatch to GetLogin");
169                 throw new InterruptDispatchException(new GetLogin());
170             }
171         }
172     }
173
174     //------------------------------------------------------------
175
// Model 2 - View Event Handlers
176
//------------------------------------------------------------
177
/**
178      * RenderLoginHandler -
179      */

180     class RenderLoginHandler extends DefaultBaseEventListener {
181         public void handleViewEvent(ViewEventContext context) throws EventException, ServletException, IOException {
182             // MUST DO FIRST - initialize things from the context
183
initUsingContext( context );
184
185             //unpack the necessary entities from the context
186
HttpServletRequest req = context.getRequest();
187
188             //get the XMLC object
189
LoginHTML page = (LoginHTML) getComms().xmlcFactory.create(LoginHTML.class);
190
191             //create a template component and render it
192
if ( logger.isDebugEnabled() ) logger.debug("Creating template component");
193             Node node = page.getDocument().getElementById("LoginForm");
194 // BTemplate templateComp = new BTemplate(new LoginModel(context), new DefaultTemplateView(node));
195

196         TemplateView tv = new DefaultTemplateView(node);
197         TemplateModel tm = new LoginModel(context);
198         BTemplate templateComp = new BTemplate(tm);
199         templateComp.setView(tv);
200
201             try {
202                 templateComp.render(new DefaultViewContext(context));
203             } catch ( RenderException re ) {
204                 logger.warn("Render err:"+re);
205             }
206
207             //now actually render the page (the DOMWriter will take care of actually
208
//setting the content type)
209
if ( logger.isDebugEnabled() ) logger.debug("Rendering document");
210               new DefaultDOMWriter().write(page, context.getResponse());
211         }
212     }
213
214     //------------------------------------------------------------
215
// Template Models
216
//------------------------------------------------------------
217
/**
218      * LoginModel
219      */

220     class LoginModel extends AbstractTemplateModel {
221
222         LoginForm fm = null;
223         ValidationException ve = null;
224
225         //constructor (extract form, exception from context)
226
public LoginModel(EventContext ec) {
227             fm = (LoginForm) ec.getState(LOGIN_FORM);
228             ve = (ValidationException) ec.getState(LOGIN_ERR);
229         }
230
231         //register the model by name
232
public String JavaDoc getName() {
233             return "Login";
234         }
235
236         //provide items by key
237
public Object JavaDoc getItem(String JavaDoc key) {
238       ViewContext vc = getViewContext();
239             if ( key.equals("Username") ) {
240                 return(fm!=null ? fm.getStringVal(LoginForm.USER, "") : "");
241             } else if ( key.equals("Password") ) {
242                 return(fm!=null ? fm.getStringVal(LoginForm.PASSWORD, "") : "");
243             } else if ( key.equals("Errors") ) {
244                 if ( ve==null ) return "";
245                 List JavaDoc errlist = ve.getExceptionList();
246                 StringBuffer JavaDoc sb = new StringBuffer JavaDoc(errlist.size()>1 ? "There were several errors:" : "");
247                 Iterator JavaDoc it = errlist.iterator();
248                 while ( it.hasNext() ) {
249                     sb.append(" "+((ValidationException) it.next()).getMessage());
250                 }
251                 return sb.toString();
252             } else
253               return super.getItem(key);
254         }
255
256     }
257
258     //------------------------------------------------------------
259
// HTML Form Mappings, Validators
260
//------------------------------------------------------------
261

262     /**
263      * Login form - define the login form
264      */

265     class LoginForm extends DefaultFormMap {
266         //login form constants (these values correspond to the HTML param names)
267
static final String JavaDoc USER = "login";
268         static final String JavaDoc PASSWORD = "password";
269
270         HttpSession session = null;
271
272         public LoginForm(HttpSession isession) {
273             session = isession;
274
275             //define the elements
276
if ( logger.isDebugEnabled() ) logger.debug("Defining Login form elements");
277             this.defineElement(new DefaultFormElement(USER, FormType.STRING, null, new NotNullValidator("You must enter a Login.")));
278             this.defineElement(new DefaultFormElement(PASSWORD, FormType.STRING, null, new NotNullValidator("You must enter a Password.")));
279
280             //define a form validator
281
if ( logger.isDebugEnabled() ) logger.debug("Defining Registration form validator");
282             this.defineValidator(new LoginValidator(session));
283         }
284
285         /**
286          * we override this method because instead of using the default validation
287          * process (validate elements, then form), we don't want to validate at all
288          * if they are already logged in...we just assume they're valid and return.
289          */

290         public FormMap validate(boolean deferExceptions) throws ValidationException {
291             //see if they are already logged in. If so, just consider them valid
292
if ( logger.isDebugEnabled() ) logger.debug("Checking to see if already logged in (prevalidated)");
293             Person p = getUser();
294             if ( null != p ) {
295                 try {
296                     String JavaDoc fuser = this.getStringVal(LoginForm.USER);
297                     String JavaDoc fpassword = this.getStringVal(LoginForm.PASSWORD);
298                     if ( fuser==null && fpassword==null ) return this; //if user/pwd = null, just use the current settings
299
if ( p.getLogin().equals(fuser) &&
300                              p.getPassword().equals(fpassword) ) return this; //if they're != null, make sure they match, otherwise, we'll want to force a complete revalidate
301
} catch ( DiscRackBusinessException e ) {
302                 }
303             }
304
305             //if not, go ahead and validate
306
return super.validate(deferExceptions);
307         }
308     }
309
310     /**
311      * Login validator - define a custom form validator
312      */

313     class LoginValidator extends DefaultFormValidator {
314
315         HttpSession session = null;
316
317         public LoginValidator(HttpSession isession) {
318             session = isession;
319         }
320
321         public void validateForm(FormMap imap, boolean deferExceptions) throws ValidationException {
322             if ( logger.isDebugEnabled() ) logger.debug("Validating login form");
323
324             //validate the login information
325
if ( logger.isDebugEnabled() ) logger.debug("Validate the user/pwd info");
326             LoginForm map = (LoginForm) imap;
327             String JavaDoc user = map.getStringVal(LoginForm.USER);
328             String JavaDoc password = map.getStringVal(LoginForm.PASSWORD);
329             String JavaDoc errMsg = "Invalid username or password. Please check your information and try again.";
330             try {
331                 //make sure the login exists and the passwords match
332
Person person = PersonFactory.findPerson(user);
333                 if ( person==null ) throw new ValidationException(map.getElement(LoginForm.USER), errMsg);
334                 if ( !person.getPassword().equals(password) ) throw new ValidationException(map.getElement(LoginForm.PASSWORD), errMsg);
335
336                 //log them in
337
setUser(person);
338             } catch ( DiscRackBusinessException e ) {
339                 removeUserFromSession(); //just to be sure we don't get stuck in a loop
340
throw new ValidationException(map.getElement(LoginForm.USER), "System error finding user: " + e.getMessage()+". Please try again. If the problem persists, contact your system administrator.", e);
341             } catch ( DiscRackPresentationException e ) {
342                 throw new ValidationException(map.getElement(LoginForm.USER), "System error setting user: " + e.getMessage()+". Please try again. If the problem persists, contact your system administrator.", e);
343             }
344         }
345     }
346 }
347
348
Popular Tags