KickJava   Java API By Example, From Geeks To Geeks.

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


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: RegistrationEventGateway.java,v 1.4 2004/12/03 14:12:34 slobodan Exp $
22  */

23 package barracudaDiscRack.presentation.personMgmt;
24
25 import java.io.*;
26 import java.util.*;
27 import java.net.*;
28 import javax.servlet.*;
29 import javax.servlet.http.*;
30
31 import org.w3c.dom.*;
32 import org.w3c.dom.html.*;
33
34 import org.enhydra.xml.xmlc.*;
35
36 import org.enhydra.barracuda.core.comp.*;
37 import org.enhydra.barracuda.core.event.*;
38 import org.enhydra.barracuda.core.event.helper.*;
39 import org.enhydra.barracuda.core.forms.*;
40 import org.enhydra.barracuda.core.forms.validators.*;
41 import org.enhydra.barracuda.core.util.dom.*;
42 import org.enhydra.barracuda.plankton.data.CollectionsUtil;
43
44 import org.apache.log4j.*;
45
46 // import disc rack specifics
47
import barracudaDiscRack.presentation.*;
48 import barracudaDiscRack.business.*;
49 import barracudaDiscRack.business.person.*;
50 import barracudaDiscRack.presentation.events.*;
51 import barracudaDiscRack.presentation.personMgmt.events.*;
52
53
54 /**
55  * Event handlers (both Controller and View) for the
56  * Registration screen
57  *
58  * <p>We handle the following Control events:
59  * <ul>
60  * <li>GetRegister - uses an EventForwardingFactory to
61  * automatically fire a RenderRegister event</li>
62  * <li>DoRegister - create the registration form, map the request
63  * to the form and then validate it. If there weren't any errors,
64  * store the Person record, log the user into the session, and
65  * then fire a GetLogin event (which will cause them to be auto-
66  * logged in). Otherwise, fire a GetRegister event (saving the
67  * form and any validation errors in the event context so that
68  * the RenderLogin can update the screen correctly.</li>
69  * </ul>
70  *
71  * <p>We handle the following View events:
72  * <ul>
73  * <li>RenderRegister - Generate the Registration screen. If the event context
74  * contains a RegistrationForm, we repopulate the screen from the form.
75  * If the context contains login errs, we will show those as well</li>
76  * </ul>
77  *
78  * <p>We define the following Forms:
79  * <ul>
80  * <li>RegistrationForm - contains 5 elements: FIRST_NAME, LAST_NAME,
81  * USER, PASSWORD, and REPASSWORD, all of which are Strings and
82  * take NotNullValidators. In addition, registration form uses
83  * RegistrationValidator, which validates the form by making sure
84  * that the passwords match and the person record is not already
85  * on file.</li>
86  * </ul>
87  *
88  * <p>You can <a HREF="sm_barracudaDiscRack_registration.gif">click here to see a diagram...</a>
89  */

90 public class RegistrationEventGateway extends BaseDiscRackEventGateway {
91
92         //public constants
93
protected static Logger logger = Logger.getLogger(RegistrationEventGateway.class.getName());
94
95         //private constants
96
private static final String JavaDoc REGISTRATION_FORM = RegistrationEventGateway.class.getName()+".RegistrationForm"; //RegistrationForm
97
private static final String JavaDoc REGISTRATION_ERR = RegistrationEventGateway.class.getName()+".RegistrationErr"; //ValidationException
98

99         //this defines the various event handlers
100
private ListenerFactory getRegisterFactory = new EventForwardingFactory(new RenderRegister());
101         private ListenerFactory renderRegisterFactory = new DefaultListenerFactory() {
102                 public BaseEventListener getInstance() {
103                         return new RenderRegisterHandler();
104                 } public String JavaDoc getListenerID() {
105                         return getID(RenderRegisterHandler.class);
106                 }
107         };
108         private ListenerFactory doRegisterFactory = new DefaultListenerFactory() {
109                 public BaseEventListener getInstance() {
110                         return new DoRegisterHandler();
111                 } public String JavaDoc getListenerID() {
112                         return getID(DoRegisterHandler.class);
113                 }
114         };
115
116         //private vars
117

118
119         //-------------------- DefaultEventGateway -------------------
120
/**
121          * Public constructor
122          */

123         public RegistrationEventGateway() {
124                 //specify who's interested in what
125
specifyLocalEventInterests(getRegisterFactory, GetRegister.class);
126                 specifyLocalEventInterests(renderRegisterFactory, RenderRegister.class);
127                 specifyLocalEventInterests(doRegisterFactory, DoRegister.class);
128         }
129
130
131         //------------------------------------------------------------
132
// Model 2 - Controller Event Handlers
133
//------------------------------------------------------------
134
/**
135          * DoRegisterHandler - this is where we handle any attempt to
136          * register.
137          */

138         class DoRegisterHandler extends DefaultBaseEventListener {
139                 public void handleControlEvent(ControlEventContext context) throws EventException, ServletException, IOException {
140                         // MUST DO FIRST - initialize things from the context
141
initUsingContext( context );
142
143                         //unpack the necessary entities from the context
144
HttpServletRequest req = context.getRequest();
145
146                         //map, validate the registration form
147
if ( logger.isDebugEnabled() ) logger.debug("Creating registration form");
148                         RegistrationForm rf = new RegistrationForm();
149                         ValidationException ve = null;
150                         try {
151                                 //map/validate the form
152
if ( logger.isDebugEnabled() ) logger.debug("Mapping/Validating registration form");
153                                 rf.map(req).validate(true);
154
155                                 //actually store the user
156
if ( logger.isDebugEnabled() ) logger.debug("Creating user account");
157                                 HttpSession session = getComms().session.getHttpSession();
158                                 try {
159                                         Person person = new Person();
160                                         person.setLogin(rf.getStringVal(RegistrationForm.USER));
161                                         person.setPassword(rf.getStringVal(RegistrationForm.PASSWORD));
162                                         person.setFirstname(rf.getStringVal(RegistrationForm.FIRST_NAME));
163                                         person.setLastname(rf.getStringVal(RegistrationForm.LAST_NAME));
164                                         person.save();
165                                         if ( logger.isDebugEnabled() ) logger.debug("Logging user in");
166                                         setUser( person );
167                                 } catch ( DiscRackBusinessException e ) {
168                                         //if we get an error here, it's because it was valid when we
169
//validated, but by the time we stored it it wasn't any longer
170
if ( logger.isDebugEnabled() ) logger.debug("Biz err:"+e+" Make sure user is Logged out");
171                                         removeUserFromSession();
172                                         throw new ValidationException(this, "Error creating account: "+e.getMessage()+" Please try again. If the problem persists contact your system administrator.", e);
173                                 } catch ( DiscRackPresentationException e ) {
174                                         if ( logger.isDebugEnabled() ) logger.debug("Biz err:"+e+" Make sure user is Logged out");
175                                         removeUserFromSession();
176                                         throw new ValidationException(this, "Error creating account: "+e.getMessage()+" Please try again. If the problem persists contact your system administrator.", e);
177                                 }
178                         } catch ( ValidationException e ) {
179                                 if ( logger.isDebugEnabled() ) logger.debug("Validation Exception: "+e);
180
181                                 if ( logger.isDebugEnabled() )
182                                   CollectionsUtil.printStackTrace(e.getExceptionList(), 0, logger, null);
183
184                                 ve = e;
185                         }
186
187                         //store a copy of the form and any errors in the queue
188
if ( logger.isDebugEnabled() ) logger.debug("Saving form, errors");
189                         context.putState(REGISTRATION_FORM, rf);
190                         context.putState(REGISTRATION_ERR, ve);
191
192                         //redirect appropriately: if it's valid, update the session
193
//and head for the login screen. Otherwise, return to the
194
//Registration screen...
195
if ( ve==null ) {
196                                 if ( logger.isDebugEnabled() ) logger.debug("Redirecting to GetLogin");
197                                 throw new ClientSideRedirectException(new GetLogin());
198                         } else {
199                                 if ( logger.isDebugEnabled() ) logger.debug("InterruptDispatch to GetRegister");
200                                 throw new InterruptDispatchException(new GetRegister());
201                         }
202                 }
203         }
204
205
206         //------------------------------------------------------------
207
// Model 2 - View Event Handlers
208
//------------------------------------------------------------
209
/**
210          * RenderRegisterHandler - this is where we render the registration screen
211          */

212         class RenderRegisterHandler extends DefaultBaseEventListener {
213                 public void handleViewEvent(ViewEventContext context) throws EventException, ServletException, IOException {
214                         // MUST DO FIRST - initialize things from the context
215
initUsingContext( context );
216
217                         //get the XMLC object
218
RegisterHTML page = (RegisterHTML) getComms().xmlcFactory.create(RegisterHTML.class);
219
220                         //create a template component and render it
221
if ( logger.isDebugEnabled() ) logger.debug("Creating template component");
222                         Node node = page.getDocument().getElementById("RegistrationForm");
223
224         TemplateView tv = new DefaultTemplateView(node);
225         TemplateModel tm = new RegistrationModel(context);
226         BTemplate templateComp = new BTemplate(tm);
227         templateComp.setView(tv);
228
229                         try {
230                                 templateComp.render(new DefaultViewContext(context));
231                         } catch ( RenderException re ) {
232                                 logger.warn("Render err:"+re);
233                         }
234
235                         //now actually render it (the DOMWriter will take care of actually
236
//setting the content type)
237
if ( logger.isDebugEnabled() ) logger.debug("Rendering document");
238                         new DefaultDOMWriter().write(page, context.getResponse());
239                 }
240         }
241
242         //------------------------------------------------------------
243
// Template Models
244
//------------------------------------------------------------
245
/**
246          * RegistrationModel
247          */

248         class RegistrationModel extends AbstractTemplateModel {
249
250                 RegistrationForm fm = null;
251                 ValidationException ve = null;
252
253                 //constructor (extract form, exception from context)
254
public RegistrationModel(EventContext ec) {
255                         fm = (RegistrationForm) ec.getState(REGISTRATION_FORM);
256                         ve = (ValidationException) ec.getState(REGISTRATION_ERR);
257                 }
258
259                 //register the model by name
260
public String JavaDoc getName() {
261                         return "Registration";
262                 }
263
264                 //provide items by key
265
public Object JavaDoc getItem(String JavaDoc key) {
266                         if ( key.equals("FirstName") ) {
267                                 return(fm!=null ? fm.getStringVal(RegistrationForm.FIRST_NAME, "") : "");
268                         } else if ( key.equals("LastName") ) {
269                                 return(fm!=null ? fm.getStringVal(RegistrationForm.LAST_NAME, "") : "");
270                         } else if ( key.equals("Username") ) {
271                                 return(fm!=null ? fm.getStringVal(RegistrationForm.USER, "") : "");
272                         } else if ( key.equals("Password") ) {
273                                 return(fm!=null ? fm.getStringVal(RegistrationForm.PASSWORD, "") : "");
274                         } else if ( key.equals("Repassword") ) {
275                                 return(fm!=null ? fm.getStringVal(RegistrationForm.REPASSWORD, "") : "");
276                         } else if ( key.equals("Errors") ) {
277                                 if ( ve==null ) return "";
278                                 List errlist = ve.getExceptionList();
279                                 StringBuffer JavaDoc sb = new StringBuffer JavaDoc(errlist.size()>1 ? "There were several errors:" : "");
280                                 Iterator it = errlist.iterator();
281                                 while ( it.hasNext() ) {
282                                         sb.append(" "+((ValidationException) it.next()).getMessage());
283                                 }
284                                 return sb.toString();
285                         } else
286                           return super.getItem(key);
287                 }
288
289         }
290
291         //------------------------------------------------------------
292
// HTML Form Mappings, Validators
293
//------------------------------------------------------------
294
/**
295          * Registration form - define the registration form
296          */

297         class RegistrationForm extends DefaultFormMap {
298                 //registration form constants (these values correspond to the HTML params)
299
static final String JavaDoc FIRST_NAME = "firstname";
300                 static final String JavaDoc LAST_NAME = "lastname";
301                 static final String JavaDoc USER = "login";
302                 static final String JavaDoc PASSWORD = "password";
303                 static final String JavaDoc REPASSWORD = "repassword";
304
305                 public RegistrationForm() {
306                         //define the elements
307
if ( logger.isDebugEnabled() ) logger.debug("Defining Registration form elements");
308                         this.defineElement(new DefaultFormElement(FIRST_NAME, FormType.STRING, null, new NotNullValidator("You must enter a First name.")));
309                         this.defineElement(new DefaultFormElement(LAST_NAME, FormType.STRING, null, new NotNullValidator("You must enter a Last name.")));
310                         this.defineElement(new DefaultFormElement(USER, FormType.STRING, null, new NotNullValidator("You must enter a Login.")));
311                         this.defineElement(new DefaultFormElement(PASSWORD, FormType.STRING, null, new NotNullValidator("You must enter a Password.")));
312                         this.defineElement(new DefaultFormElement(REPASSWORD, FormType.STRING, null, new NotNullValidator("You must Confirm your password.")));
313
314                         //define a form validator
315
if ( logger.isDebugEnabled() ) logger.debug("Defining Registration form validator");
316                         this.defineValidator(new RegistrationValidator());
317                 }
318         }
319
320         /**
321          * Registration validator - define a custom form validator
322          */

323         class RegistrationValidator extends DefaultFormValidator {
324                 public void validateForm(FormMap imap, boolean deferExceptions) throws ValidationException {
325                         if ( logger.isDebugEnabled() ) logger.debug("Validating registration form");
326
327                         //make sure the passwords match
328
if ( logger.isDebugEnabled() ) logger.debug("Make sure passwords match");
329                         RegistrationForm map = (RegistrationForm) imap;
330                         String JavaDoc password = map.getStringVal(RegistrationForm.PASSWORD);
331                         String JavaDoc repassword = map.getStringVal(RegistrationForm.REPASSWORD);
332                         if ( !password.equals(repassword) ) throw new ValidationException(map.getElement(RegistrationForm.PASSWORD), "Passwords do not match. Please re-enter.");
333
334                         //validate the login information
335
if ( logger.isDebugEnabled() ) logger.debug("Make sure the login isn't taken");
336                         String JavaDoc user = map.getStringVal(RegistrationForm.USER);
337                         try {
338                                 if ( PersonFactory.findPerson(user)!=null ) throw new ValidationException(map.getElement(RegistrationForm.USER), "This login already taken. Please select another.");
339                         } catch ( DiscRackBusinessException e ) {
340                                 throw new ValidationException(map.getElement(RegistrationForm.USER), "Error checking login against database. Please try again. If the problem persists, contact your system administrator.", e);
341                         }
342                 }
343         }
344 }
345
346
Popular Tags