KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > barracuda > discRack > pres > screens > RegistrationScreen


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: RegistrationScreen.java,v 1.4 2004/02/05 10:24:50 slobodan Exp $
22  */

23 package org.enhydra.barracuda.discRack.pres.screens;
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.plankton.data.*;
42 import org.enhydra.barracuda.core.util.dom.*;
43 import org.enhydra.barracuda.core.util.http.*;
44 import org.apache.log4j.*;
45
46 import org.enhydra.barracuda.discRack.biz.*;
47 import org.enhydra.barracuda.discRack.biz.person.*;
48 import org.enhydra.barracuda.discRack.pres.events.*;
49 import org.enhydra.barracuda.discRack.pres.services.*;
50 import org.enhydra.barracuda.discRack.pres.xmlc.*;
51
52
53 /**
54  * Event handlers (both Controller and View) for the
55  * Registration screen
56  *
57  * <p>We handle the following Control events:
58  * <ul>
59  * <li>GetRegister - uses an EventForwardingFactory to
60  * automatically fire a RenderRegister event</li>
61  * <li>DoRegister - create the registration form, map the request
62  * to the form and then validate it. If there weren't any errors,
63  * store the Person record, log the user into the session, and
64  * then fire a GetLogin event (which will cause them to be auto-
65  * logged in). Otherwise, fire a GetRegister event (saving the
66  * form and any validation errors in the event context so that
67  * the RenderLogin can update the screen correctly.</li>
68  * </ul>
69  *
70  * <p>We handle the following View events:
71  * <ul>
72  * <li>RenderRegister - Generate the Registration screen. If the event context
73  * contains a RegistrationForm, we repopulate the screen from the form.
74  * If the context contains login errs, we will show those as well</li>
75  * </ul>
76  *
77  * <p>We define the following Forms:
78  * <ul>
79  * <li>RegistrationForm - contains 5 elements: FIRST_NAME, LAST_NAME,
80  * USER, PASSWORD, and REPASSWORD, all of which are Strings and
81  * take NotNullValidators. In addition, registration form uses
82  * RegistrationValidator, which validates the form by making sure
83  * that the passwords match and the person record is not already
84  * on file.</li>
85  * </ul>
86  *
87  * <p>You can <a HREF="sm_barracudaDiscRack_registration.gif">click here to see a diagram...</a>
88  */

89 public class RegistrationScreen extends DefaultEventGateway {
90
91     //public constants
92
// public static int showDebug = 0;
93
protected static Logger logger = Logger.getLogger(RegistrationScreen.class.getName());
94
95     //private constants
96
private static final String JavaDoc REGISTRATION_FORM = RegistrationScreen.class.getName()+".RegistrationForm"; //RegistrationForm
97
private static final String JavaDoc REGISTRATION_ERR = RegistrationScreen.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() {public BaseEventListener getInstance() {return new RenderRegisterHandler();} public String JavaDoc getListenerID() {return getID(RenderRegisterHandler.class);}};
102     private ListenerFactory doRegisterFactory = new DefaultListenerFactory() {public BaseEventListener getInstance() {return new DoRegisterHandler();} public String JavaDoc getListenerID() {return getID(DoRegisterHandler.class);}};
103
104     //private vars
105

106
107     //-------------------- DefaultEventGateway -------------------
108
/**
109      * Public constructor
110      */

111     public RegistrationScreen() {
112         //specify who's interested in what
113
specifyLocalEventInterests(getRegisterFactory, GetRegister.class);
114         specifyLocalEventInterests(renderRegisterFactory, RenderRegister.class);
115         specifyLocalEventInterests(doRegisterFactory, DoRegister.class);
116     }
117
118
119     //------------------------------------------------------------
120
// Model 2 - Controller Event Handlers
121
//------------------------------------------------------------
122
/**
123      * DoRegisterHandler - this is where we handle any attempt to
124      * register.
125      */

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

190     class RenderRegisterHandler extends DefaultBaseEventListener {
191         public void handleViewEvent(ViewEventContext context) throws EventException, ServletException, IOException {
192             //get the XMLC object
193
// XMLCFactory factory = XMLCServices.getXMLCFactory(context.getConfig());
194
// RegisterHTML page = (RegisterHTML) factory.create(RegisterHTML.class);
195
RegisterHTML page = (RegisterHTML) DefaultDOMLoader.getGlobalInstance().getDOM(RegisterHTML.class);
196
197             //repopulate the form if possible
198
/*
199             if (showDebug>0) Debug.println (this, 0, "Getting form for view");
200             RegistrationForm rf = (RegistrationForm) context.get(REGISTRATION_FORM);
201             if (rf!=null) {
202                 if (showDebug>0) Debug.println (this, 0, "Repopulating form in view");
203                 page.getElementFirstname().setValue(""+rf.getStringVal(RegistrationForm.FIRST_NAME));
204                 page.getElementLastname().setValue(""+rf.getStringVal(RegistrationForm.LAST_NAME));
205                 page.getElementLogin().setValue(""+rf.getStringVal(RegistrationForm.USER));
206                 page.getElementPassword().setValue(""+rf.getStringVal(RegistrationForm.PASSWORD));
207                 page.getElementRepassword().setValue(""+rf.getStringVal(RegistrationForm.REPASSWORD));
208             }
209
210             //check for errors
211             if (showDebug>0) Debug.println (this, 0, "Checking for errors");
212             ValidationException ve = (ValidationException) context.get(REGISTRATION_ERR);
213             if (ve==null) {
214                 if (showDebug>1) Debug.println (this, 0, "No errors found");
215                 page.getElementErrorText().getParentNode().removeChild(page.getElementErrorText());
216             } else {
217                 List errlist = ve.getExceptionList();
218                 if (showDebug>1) Debug.println (this, 0, errlist.size()+"error(s) found");
219                 StringBuffer sb = new StringBuffer(errlist.size()>1 ? "There were several errors:" : "");
220                 Iterator it = errlist.iterator();
221                 while (it.hasNext()) {
222                     sb.append(" "+((ValidationException) it.next()).getMessage());
223                 }
224                 page.setTextErrorText(sb.toString());
225             }
226 */

227
228             //create a template component and render it
229
if (logger.isDebugEnabled()) logger.debug("Creating template component");
230             Node node = page.getDocument().getElementById("RegistrationForm");
231             BTemplate templateComp = new BTemplate(new RegistrationModel(context));
232             templateComp.setView(new DefaultTemplateView(node));
233             try {templateComp.render(new DefaultViewContext(context));}
234             catch (RenderException re) {logger.warn("Render err:"+re);}
235
236             //now actually render it (the DOMWriter will take care of actually
237
//setting the content type)
238
if (logger.isDebugEnabled()) logger.debug("Rendering document");
239             new DefaultDOMWriter().write(page, context.getResponse());
240         }
241     }
242
243     //------------------------------------------------------------
244
// Template Models
245
//------------------------------------------------------------
246
/**
247      * RegistrationModel
248      */

249     class RegistrationModel extends AbstractTemplateModel {
250
251         RegistrationForm fm = null;
252         ValidationException ve = null;
253
254         //constructor (extract form, exception from context)
255
public RegistrationModel(EventContext ec) {
256             fm = (RegistrationForm) ec.getState(REGISTRATION_FORM);
257             ve = (ValidationException) ec.getState(REGISTRATION_ERR);
258         }
259
260         //register the model by name
261
public String JavaDoc getName() {return "Registration";}
262
263         //provide items by key
264
public Object JavaDoc getItem(String JavaDoc key) {
265             ViewContext vc = getViewContext();
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("LoginButton")) {
277                 BAction baComp = new BAction(new GetLogin());
278                 baComp.setDisableBackButton(true);
279                 return baComp;
280             } else if (key.equals("RegisterButton")) {
281                 BAction baComp = new BAction(new DoRegister());
282                 baComp.setDisableBackButton(true);
283                 return baComp;
284             } else if (key.equals("Errors")) {
285                 if (ve==null) return null;
286                 List errlist = ve.getExceptionList();
287                 StringBuffer JavaDoc sb = new StringBuffer JavaDoc(errlist.size()>1 ? "There were several errors:" : "");
288                 Iterator it = errlist.iterator();
289                 while (it.hasNext()) {
290                     sb.append(" "+((ValidationException) it.next()).getMessage());
291                 }
292                 return sb.toString();
293             } else {
294                 return super.getItem(key);
295             }
296         }
297     }
298
299     //------------------------------------------------------------
300
// HTML Form Mappings, Validators
301
//------------------------------------------------------------
302
/**
303      * Registration form - define the registration form
304      */

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

331     class RegistrationValidator extends DefaultFormValidator {
332         public void validateForm(FormMap imap, boolean deferExceptions) throws ValidationException {
333             if (logger.isDebugEnabled()) logger.debug("Validating registration form");
334
335             //make sure the passwords match
336
if (logger.isDebugEnabled()) logger.debug("Make sure passwords match");
337             RegistrationForm map = (RegistrationForm) imap;
338             DeferredValidationException defValException = new DeferredValidationException();
339             String JavaDoc password = map.getStringVal(RegistrationForm.PASSWORD);
340             String JavaDoc repassword = map.getStringVal(RegistrationForm.REPASSWORD);
341             if ((password != null && repassword != null) && !password.equals(repassword)) defValException.addSubException(new DeferredValidationException(map.getElement(RegistrationForm.PASSWORD), "Passwords do not match. Please re-enter."));
342
343             //validate the login information
344
if (logger.isDebugEnabled()) logger.debug("Make sure the login isn't taken");
345             String JavaDoc user = map.getStringVal(RegistrationForm.USER);
346             if (user != null) {
347                 try {
348                     if (PersonFactory.findPerson(user)!=null) defValException.addSubException(new DeferredValidationException(map.getElement(RegistrationForm.USER), "This login already taken. Please select another."));
349                 } catch (DiscRackBusinessException e) {
350                     defValException.addSubException(new DeferredValidationException(map.getElement(RegistrationForm.USER), "Error checking login against database. Please try again. If the problem persists, contact your system administrator.", e));
351                 }
352             }
353             if (defValException.hasSubExceptions()) {
354                 throw defValException;
355             }
356         }
357     }
358 }
359
360
Popular Tags