KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jcorporate > expresso > services > controller > SimpleRegistration


1 /* ====================================================================
2  * The Jcorporate Apache Style Software License, Version 1.2 05-07-2002
3  *
4  * Copyright (c) 1995-2002 Jcorporate Ltd. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in
15  * the documentation and/or other materials provided with the
16  * distribution.
17  *
18  * 3. The end-user documentation included with the redistribution,
19  * if any, must include the following acknowledgment:
20  * "This product includes software developed by Jcorporate Ltd.
21  * (http://www.jcorporate.com/)."
22  * Alternately, this acknowledgment may appear in the software itself,
23  * if and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. "Jcorporate" and product names such as "Expresso" must
26  * not be used to endorse or promote products derived from this
27  * software without prior written permission. For written permission,
28  * please contact info@jcorporate.com.
29  *
30  * 5. Products derived from this software may not be called "Expresso",
31  * or other Jcorporate product names; nor may "Expresso" or other
32  * Jcorporate product names appear in their name, without prior
33  * written permission of Jcorporate Ltd.
34  *
35  * 6. No product derived from this software may compete in the same
36  * market space, i.e. framework, without prior written permission
37  * of Jcorporate Ltd. For written permission, please contact
38  * partners@jcorporate.com.
39  *
40  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
41  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
42  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
43  * DISCLAIMED. IN NO EVENT SHALL JCORPORATE LTD OR ITS CONTRIBUTORS
44  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
45  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
46  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
47  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
48  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
49  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
50  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This software consists of voluntary contributions made by many
55  * individuals on behalf of the Jcorporate Ltd. Contributions back
56  * to the project(s) are encouraged when you make modifications.
57  * Please send them to support@jcorporate.com. For more information
58  * on Jcorporate Ltd. and its products, please see
59  * <http://www.jcorporate.com/>.
60  *
61  * Portions of this software are based upon other open source
62  * products and are subject to their respective licenses.
63  */

64
65 /**
66  * ControllerSecurityMatrix.java Copyright 2000, 2001 Jcorporate Ltd.
67  */

68 package com.jcorporate.expresso.services.controller;
69
70 import com.jcorporate.expresso.core.controller.Block;
71 import com.jcorporate.expresso.core.controller.Controller;
72 import com.jcorporate.expresso.core.controller.ControllerException;
73 import com.jcorporate.expresso.core.controller.ControllerRequest;
74 import com.jcorporate.expresso.core.controller.ControllerResponse;
75 import com.jcorporate.expresso.core.controller.ErrorCollection;
76 import com.jcorporate.expresso.core.controller.Input;
77 import com.jcorporate.expresso.core.controller.NonHandleableException;
78 import com.jcorporate.expresso.core.controller.Output;
79 import com.jcorporate.expresso.core.controller.ServletControllerRequest;
80 import com.jcorporate.expresso.core.controller.State;
81 import com.jcorporate.expresso.core.controller.Transition;
82 import com.jcorporate.expresso.core.dataobjects.DataObjectMetaData;
83 import com.jcorporate.expresso.core.dataobjects.jdbc.JDBCObjectMetaData;
84 import com.jcorporate.expresso.core.db.DBException;
85 import com.jcorporate.expresso.core.dbobj.DBObject;
86 import com.jcorporate.expresso.core.dbobj.SecuredDBObject;
87 import com.jcorporate.expresso.core.logging.LogException;
88 import com.jcorporate.expresso.core.misc.ConfigManager;
89 import com.jcorporate.expresso.core.misc.StringUtil;
90 import com.jcorporate.expresso.core.security.User;
91 import com.jcorporate.expresso.kernel.util.FastStringBuffer;
92 import com.jcorporate.expresso.services.controller.ui.DefaultAutoElement;
93 import com.jcorporate.expresso.services.dbobj.GroupMembers;
94 import com.jcorporate.expresso.services.dbobj.RegistrationDomain;
95 import com.jcorporate.expresso.services.dbobj.RegistrationObjectMap;
96 import com.jcorporate.expresso.services.dbobj.Setup;
97 import com.jcorporate.expresso.services.dbobj.UserGroup;
98 import com.jcorporate.expresso.services.validation.AuthValidationException;
99 import com.jcorporate.expresso.services.validation.ValidationEntry;
100 import org.apache.log4j.Logger;
101
102 import javax.servlet.http.HttpServletRequest JavaDoc;
103 import java.util.Iterator JavaDoc;
104 import java.util.Map JavaDoc;
105 import java.util.StringTokenizer JavaDoc;
106
107
108 /**
109  * SimpleRegistration Controller. This is the implementation example of
110  * Registration. Depends on:
111  * <p/>
112  * <ul>
113  * <li>
114  * Login Controller
115  * </li>
116  * <li>
117  * Email Validator
118  * </li>
119  * <li>
120  * Registration Validator
121  * </li>
122  * <li>
123  * Reg Domain DBObjects
124  * </li>
125  * <li>
126  * Reg Domain DBObject Map
127  * </li>
128  * </ul>
129  * <p/>
130  * <h4>
131  * <p/>
132  * <p/>
133  * The following states are the usual entry points into the registration
134  * controller
135  * </p>
136  * <p/>
137  * <ul>
138  * <li>
139  * showDBMenu - For users that want to change/edit their registraiton info
140  * </li>
141  * <li>
142  * promptAddRecord - Where we prompt the user to fill out the registration
143  * information
144  * </li>
145  * <li>
146  * promptSelfRegister - Where we prompt for login information et.al. from users
147  * who wish to self-register
148  * </li>
149  * <li>
150  * promptApproval - For approval administrators only. Shows the registration
151  * information and asks if a user should be approved or not.
152  * </li>
153  * </ul>
154  * <p/>
155  * <p/>
156  * Parameter Explanation: Login Controller == the classname of the login
157  * controller that should be forwarded to upon transfer back to the login
158  * controller.
159  * </p>
160  * Creation date: (6/23/2001 4:05:05 PM)
161  *
162  * @author Shash Chatterjee, refactored by Michael Rimov
163  */

164 public class SimpleRegistration
165         extends com.jcorporate.expresso.services.controller.Registration {
166     private static Logger log = Logger.getLogger(SimpleRegistration.class);
167
168     /**
169      * Registration constructor comment.
170      */

171     public SimpleRegistration() {
172         super();
173
174         State showDBMenu = new State("showDBMenu", "Menu of Registration Data");
175         showDBMenu.addOptionalParameter("loginController");
176         addState(showDBMenu);
177
178         State emailValidate = new State("emailValidate",
179                 "Validate User's Email Address");
180         emailValidate.addRequiredParameter("db");
181         emailValidate.addRequiredParameter("UserName");
182         emailValidate.addOptionalParameter("loginController");
183         emailValidate.addOptionalParameter("registrationController");
184         addState(emailValidate);
185
186         State promptAddRecord = new State("promptAddRecord",
187                 "Prompt Add Registration Info");
188         promptAddRecord.addRequiredParameter("dbobj");
189         promptAddRecord.addOptionalParameter("loginController");
190         addState(promptAddRecord);
191
192         State processAddRecord = new State("processAddRecord",
193                 "Continue Registration");
194         processAddRecord.addOptionalParameter("loginController");
195         addState(processAddRecord);
196
197         State promptUpdateRecord = new State("promptUpdateRecord",
198                 "Prompt Update Registration Info");
199         promptUpdateRecord.addRequiredParameter("dbobj");
200         promptUpdateRecord.addRequiredParameter("keys");
201         promptUpdateRecord.addOptionalParameter("loginController");
202         addState(promptUpdateRecord);
203
204         State processUpdateRecord = new State("processUpdateRecord", "Update");
205         processUpdateRecord.addRequiredParameter("keys"); //Needed to transition back to promptUpdate upon error.
206
processUpdateRecord.addOptionalParameter("loginController");
207         addState(processUpdateRecord);
208
209         State promptDeleteRecord = new State("promptDeleteRecord",
210                 "Prompt Delete Registration Info");
211         promptDeleteRecord.addOptionalParameter("loginController");
212         addState(promptDeleteRecord);
213
214         State processDeleteRecord = new State("processDeleteRecord", "Delete");
215         processDeleteRecord.addOptionalParameter("loginController");
216         addState(processDeleteRecord);
217
218         State processListRecords = new State("processListRecords",
219                 "List Registration Records");
220         processListRecords.addOptionalParameter("loginController");
221         addState(processListRecords);
222
223         State promptSelfRegister = new State("promptSelfRegister",
224                 "Prompt the user for basic account setup");
225         addState(promptSelfRegister);
226         promptSelfRegister.addRequiredParameter("dbContext");
227         promptSelfRegister.addOptionalParameter("loginController");
228
229         State processSelfRegister = new State("processSelfRegister",
230                 "Process the self-registration request");
231         processSelfRegister.addOptionalParameter("loginController");
232         processSelfRegister.addOptionalParameter("LoginName");
233         processSelfRegister.addParameter("Email", false, DBObject.EMAIL_MASK,
234                 "You must enter a valid email address");
235         processSelfRegister.addOptionalParameter("Email_verify"); // verify field is already matched for equality against email field
236
processSelfRegister.addOptionalParameter("Password");
237         processSelfRegister.addOptionalParameter("Password_verify");
238         processSelfRegister.addRequiredParameter("dbContext");
239         processSelfRegister.addRequiredParameter("regDomain");
240         addState(processSelfRegister);
241
242         State promptApproval = new State("promptApproval",
243                 "Prompt adminsitrators for approving users' registration");
244         promptApproval.addOptionalParameter("loginController");
245         promptApproval.addRequiredParameter("db");
246         promptApproval.addRequiredParameter("UserName");
247         addState(promptApproval);
248
249         State processApproval = new State("processApproval",
250                 "Process adminsitrator action for approving users' registration");
251         processApproval.addOptionalParameter("loginController");
252         processApproval.addRequiredParameter("db");
253         processApproval.addRequiredParameter("UserName");
254         processApproval.addRequiredParameter("command");
255         addState(processApproval);
256
257         State processRevalidate = new State("processRevalidate",
258                 "Process Revalidate Registration");
259         processRevalidate.addRequiredParameter("Email");
260         addState(processRevalidate);
261
262         setInitialState("showDBMenu");
263     }
264
265     /**
266      * Get the title of this registration controller
267      *
268      * @return the String title of this registration.
269      */

270     public String JavaDoc getTitle() {
271         return ("Detailed Registration");
272     }
273
274     /**
275      * Based upon customization of the registration domain, should a particular
276      * field name be displayed in the registration form.
277      *
278      * @param rd The registration domain that this request is under
279      * @param db The secured dbobject that will be the container for the
280      * resulting data
281      * @param fieldName the field name of the database object.
282      * @param forListView is this for showing the registration list
283      * @return true if the field should be visible to the end user.
284      * @throws ControllerException if there's trouble talking with the dbobject
285      */

286     protected boolean isShowable(RegistrationDomain rd, DBObject db,
287                                  String JavaDoc fieldName, boolean forListView) throws ControllerException {
288         try {
289             if (db.getMetaData().getFieldMetadata(fieldName).isReadOnly() ||
290                     db.getMetaData().getFieldMetadata(fieldName).isVirtual()) {
291                 return false;
292             }
293
294             String JavaDoc dbname = db.getClass().getName();
295             RegistrationObjectMap rom = new RegistrationObjectMap();
296             rom.setDataContext(rd.getDataContext());
297             rom.setField("RegDomId", rd.getField("RegDomId"));
298             rom.setField("RegObj", dbname);
299
300             if (!rom.find()) {
301                 throw new ControllerException("Registration object map not created for domain/dbname '" +
302                         rd.getField("Name") + "/" + dbname + " '");
303             }
304
305             if (fieldName.equals(rom.getField("UidField"))) {
306                 return false;
307             }
308
309             String JavaDoc oneFieldName = null;
310             String JavaDoc fields = "" + rom.getField("RegFields");
311
312             if (fields.equals("")) {
313                 return true;
314             }
315
316             StringTokenizer JavaDoc stk = new StringTokenizer JavaDoc(fields, ",");
317
318             while (stk.hasMoreTokens()) {
319                 oneFieldName = stk.nextToken();
320                 oneFieldName = oneFieldName.trim();
321
322                 if (oneFieldName.startsWith("!")) {
323                     if (oneFieldName.substring(1).equals(fieldName)) {
324                         return false;
325                     }
326                 }
327
328                 if (oneFieldName.startsWith("+")) {
329                     if (forListView &&
330                             (oneFieldName.substring(1).equals(fieldName))) {
331                         return true;
332                     }
333                 }
334
335                 if (fieldName.equals(oneFieldName)) {
336                     return true;
337                 }
338             }
339         } catch (DBException dbe) {
340             throw new ControllerException("Database error", dbe);
341         }
342
343         return true;
344     }
345
346     /**
347      * Builds the registration fill-in form.
348      *
349      * @param rd The registration domain of this request
350      * @param db The secured DBObject that contains the data to fill out.
351      * @param response The controllerResponse handed down by the framework
352      * @return A block that represents all the fill in forms for this object.
353      * @throws ControllerException upon error.
354      */

355     protected Block buildForm(RegistrationDomain rd, DBObject db,
356                               ControllerResponse response) throws ControllerException {
357         String JavaDoc dbobjName = db.getClass().getName() + ".";
358         Block block = new Block("dbobject");
359         Map map = (Map) response.getCurrentState().getSession().getAttribute(DefaultAutoElement.SESSION_KEY);
360         DBObject dbobj2 = db;
361
362         if (map != null) {
363             DBObject temp = (DBObject) map.get(db.getClass().getName());
364
365             if (temp != null) {
366                 dbobj2 = temp;
367             }
368         }
369
370         response.getCurrentState().getSession().removeAttribute(DefaultAutoElement.SESSION_KEY);
371
372         //block.setForm("true");
373
String JavaDoc fieldName = null;
374
375         try {
376             JDBCObjectMetaData metaData = db.getJDBCMetaData();
377             block.add(new Output("block-title",
378                     metaData.getDescription(response.getRequest().getLocale())));
379
380             for (Iterator JavaDoc e = metaData.getFieldListArray().iterator();
381                  e.hasNext();) {
382                 fieldName = (String JavaDoc) e.next();
383
384                 if (isShowable(rd, dbobj2, fieldName, false)) {
385                     String JavaDoc fieldValue = StringUtil.notNull(dbobj2.getField(fieldName));
386
387                     if (fieldValue.length() == 0) {
388                         try {
389                             fieldValue = (String JavaDoc) response.getFormCache().get(dbobj2.getClass()
390                                     .getName() +
391                                     "." + fieldName);
392                         } catch (Exception JavaDoc ex) {
393                             //Ignore this error, we were only trying to see if the
394
//form cache had anything.
395
}
396                     }
397
398                     Input field = DefaultAutoElement.getAutoControllerElement()
399                             .renderDBObjectField(response,
400                                     dbobj2, fieldName, fieldValue, false);
401
402                     if (field != null) {
403                         field.setName(dbobjName + field.getName());
404                         block.add(field);
405                     }
406                 }
407             }
408         } catch (DBException dbe) {
409             throw new ControllerException(dbe);
410         }
411
412         return block;
413     }
414
415     /**
416      * Builds the specially pre-defined block of login information.
417      *
418      * @param rd The Registration Domain the user is to register for.
419      * @param request the ControllerRequest object
420      * @param response The ControllerResponse object
421      * @return an instantiated and filled out Block for login information
422      */

423     protected Block buildLoginBlock(RegistrationDomain rd,
424                                     ControllerRequest request, ControllerResponse response)
425             throws ControllerException {
426         Block b = new Block("login-information");
427         b.add(new Output("block-title", "Login Information"));
428
429         // Retrieve the registration domain information
430
boolean emailAsLogin = false;
431         boolean userPasswd = false;
432
433         try {
434             if (rd.getField("EmailAsLogin").equals("Y")) {
435                 emailAsLogin = true;
436             }
437
438             if (rd.getField("UserPasswd").equals("Y")) {
439                 userPasswd = true;
440             }
441         } catch (DBException dbe) {
442             throw new ControllerException("DB failure on domain \"" + rd +
443                     "\"", dbe);
444         }
445
446         String JavaDoc errorStyle = null;
447
448         //Unless this site uses the email address as login name, create an input to specify login name
449
if (!emailAsLogin) {
450             Input loginName = new Input();
451             loginName.setName("LoginName");
452             loginName.setLabel("Login Name*");
453
454             String JavaDoc ln = StringUtil.notNull(response.getFormCache("LoginName"));
455             loginName.setDefaultValue(ln);
456             loginName.setDisplayLength(60);
457             loginName.setMaxLength(60);
458             errorStyle = (String JavaDoc) response.getFormCacheAttribute("LoginName");
459
460             if (errorStyle != null && errorStyle.length() > 0) {
461                 loginName.setAttribute(Input.ATTRIBUTE_CSS_STYLE, errorStyle);
462             } else {
463                 loginName.setAttribute(Input.ATTRIBUTE_CSS_STYLE,
464                         DefaultAutoElement.getAutoControllerElement()
465                         .getRequiredStyle());
466             }
467
468             b.add(loginName);
469         }
470
471         //
472
//
473
//
474
Input email = new Input();
475         email.setName("Email");
476         email.setLabel("E-Mail Address*");
477
478         String JavaDoc em = StringUtil.notNull(response.getFormCache("Email"));
479         email.setDefaultValue(em);
480         email.setDisplayLength(60);
481         email.setMaxLength(80);
482         errorStyle = (String JavaDoc) response.getFormCacheAttribute("Email");
483
484         if (errorStyle != null) {
485             email.setAttribute(Input.ATTRIBUTE_CSS_STYLE, errorStyle);
486         } else {
487             email.setAttribute(Input.ATTRIBUTE_CSS_STYLE,
488                     DefaultAutoElement.getAutoControllerElement().getRequiredStyle());
489         }
490
491         b.add(email);
492
493         Input email_verify = new Input();
494         email_verify.setName("Email_verify");
495         email_verify.setLabel("E-Mail Address(confirm)*");
496
497         String JavaDoc emv = StringUtil.notNull(response.getFormCache("Email_verify"));
498         email_verify.setDefaultValue(emv);
499         email_verify.setDisplayLength(60);
500         email_verify.setMaxLength(80);
501         errorStyle = (String JavaDoc) response.getFormCacheAttribute("Email_verify");
502
503         if (errorStyle != null && errorStyle.length() > 0) {
504             email_verify.setAttribute(Input.ATTRIBUTE_CSS_STYLE, errorStyle);
505         } else {
506             email_verify.setAttribute(Input.ATTRIBUTE_CSS_STYLE,
507                     DefaultAutoElement.getAutoControllerElement().getRequiredStyle());
508         }
509
510         b.add(email_verify);
511
512         if (userPasswd) {
513             Input password = new Input();
514             password.setName("Password");
515             password.setLabel("Password*");
516
517             String JavaDoc pw = StringUtil.notNull(response.getFormCache("Password"));
518             password.setDefaultValue(pw);
519             password.setDisplayLength(30);
520             password.setMaxLength(30);
521             password.setType("password");
522             password.setAttribute(Input.ATTRIBUTE_PASSWORD, "Y");
523             errorStyle = (String JavaDoc) response.getFormCacheAttribute("Password");
524
525             if (errorStyle != null && errorStyle.length() > 0) {
526                 password.setAttribute(Input.ATTRIBUTE_CSS_STYLE, errorStyle);
527             } else {
528                 password.setAttribute(Input.ATTRIBUTE_CSS_STYLE,
529                         DefaultAutoElement.getAutoControllerElement()
530                         .getRequiredStyle());
531             }
532
533             b.add(password);
534
535             Input password_verify = new Input();
536             password_verify.setName("Password_verify");
537             password_verify.setLabel("Password (confirm)*");
538
539             String JavaDoc pwv = StringUtil.notNull(response.getFormCache("Password_verify"));
540             password_verify.setDefaultValue(pwv);
541             password_verify.setDisplayLength(30);
542             password_verify.setMaxLength(30);
543             password_verify.setType("password");
544             password_verify.setAttribute(Input.ATTRIBUTE_PASSWORD, "Y");
545             errorStyle = (String JavaDoc) response.getFormCacheAttribute("Password_verify");
546
547             if (errorStyle != null && errorStyle.length() > 0) {
548                 password_verify.setAttribute(Input.ATTRIBUTE_CSS_STYLE,
549                         errorStyle);
550             } else {
551                 password_verify.setAttribute(Input.ATTRIBUTE_CSS_STYLE,
552                         DefaultAutoElement.getAutoControllerElement()
553                         .getRequiredStyle());
554             }
555
556             b.add(password_verify);
557         }
558
559         return b;
560     }
561
562     /**
563      * Step #1 in registration - pick a username and password. This function
564      * performs the guts of the owrk.
565      *
566      * @param errors The system fills out the errors collection if there are
567      * problems with the registration processing.
568      * @param request The ControllerRequest handed off to a controller by the
569      * framework
570      * @param response The ControllerResponse handed off to a controller by the
571      * framework.
572      * @param rd if successful, rd will contain an instantiated registration
573      * domain object representing the registration domain that this
574      * user belongs to.
575      * @return an Instantiated User object or null if errors exist.
576      * @throws DBException upon data access error
577      * @throws ControllerException upon controller error
578      * @throws LogException upon logging error
579      * @throws NonHandleableException upon fatal error
580      */

581     protected User processLoginInformation(ErrorCollection errors,
582                                            ControllerRequest request, ControllerResponse response,
583                                            RegistrationDomain rd)
584             throws DBException, ControllerException, LogException,
585             NonHandleableException {
586         String JavaDoc regDomain = request.getParameter("regDomain");
587         boolean emailAsLogin = false;
588         boolean userPasswd = false;
589         boolean emailValidate = false;
590         boolean approvalRequired = false;
591         rd.setDataContext(request.getDataContext());
592         rd.setField("Name", regDomain);
593
594         if (!rd.find()) {
595             errors.addError("Registration domain \"" + regDomain +
596                     "\" has not been defined");
597         }
598
599         if (rd.getField("EmailAsLogin").equals("Y")) {
600             emailAsLogin = true;
601         }
602
603         if (rd.getField("UserPasswd").equals("Y")) {
604             userPasswd = true;
605         }
606
607         if (rd.getField("EmailValidate").equals("Y")) {
608             emailValidate = true;
609         }
610
611         if (rd.getField("Approve").equals("Y")) {
612             approvalRequired = true;
613         }
614
615         String JavaDoc loginName = "";
616         String JavaDoc email = "";
617         String JavaDoc email_verify = "";
618         String JavaDoc password = "";
619         String JavaDoc password_verify = "";
620
621         // Hashtable theFormCache = response.getFormCache();
622
String JavaDoc errorStyle = DefaultAutoElement.getAutoControllerElement()
623                 .getErrorStyle();
624         email = request.getParameter("Email");
625         email_verify = request.getParameter("Email_verify");
626
627         if (email.equals("")) {
628             response.setFormCacheAttribute("Email", errorStyle);
629             errors.addError("Please specify a non-blank email address");
630         }
631
632         if (!email.equals(email_verify)) {
633             response.setFormCacheAttribute("Email", errorStyle);
634             response.setFormCacheAttribute("Email_verify", errorStyle);
635             errors.addError("Email address did not match the confirmation email address");
636         }
637
638         //Unless this site uses the email address as login name, fill in the login name
639
if (!emailAsLogin) {
640             loginName = request.getParameter("LoginName");
641
642             if (loginName.equals("")) {
643                 response.setFormCacheAttribute("LoginName", errorStyle);
644                 errors.addError("Please specify a non-blank login name");
645             } else if (loginName.indexOf("%") >= 0) {
646                 response.setFormCacheAttribute("LoginName", errorStyle);
647                 errors.addError("You cannot have percent signs in your login name");
648             }
649         } else {
650             loginName = email;
651         }
652
653         if (userPasswd) {
654             password = StringUtil.notNull(request.getParameter("Password"));
655             password_verify = StringUtil.notNull(request.getParameter("Password_verify"));
656
657             if (password.equals("")) {
658                 response.setFormCacheAttribute("Password", errorStyle);
659                 errors.addError("Please specify a non-blank password");
660             } else {
661                 if (!password.equals(password_verify)) {
662                     response.setFormCacheAttribute("Password_verify", errorStyle);
663                     errors.addError("Password did not match the confirmation password");
664                 } else {
665                     try {
666                         int passwordSize = Integer.parseInt(StringUtil.notNull(ConfigManager.getContext(
667                                 request.getDataContext())
668                                 .getMinPasswordSize()));
669
670                         if (passwordSize > password.length()) {
671                             response.setFormCacheAttribute("Password",
672                                     errorStyle);
673                             response.setFormCacheAttribute("Password_verify",
674                                     errorStyle);
675                             errors.addError("Passwords must be greater than " +
676                                     (passwordSize - 1) + " characters in length");
677                         }
678                     } catch (com.jcorporate.expresso.core.misc.ConfigurationException ce) {
679                         log.error("Error getting minimum password length for db context " +
680                                 request.getDataContext(), ce);
681                     }
682                 }
683             }
684         }
685
686         if (errors.getErrorCount() > 0) {
687             return null;
688         }
689
690         User user = new User();
691         user.setDataContext(request.getDataContext());
692         user.setLoginName(loginName);
693
694         if (user.find()) {
695             FastStringBuffer fsb = new FastStringBuffer(64);
696             fsb.append("Login \"");
697             fsb.append(loginName);
698             fsb.append("\" is already registered in db/context '");
699             fsb.append(request.getDataContext());
700             fsb.append("', please choose a new login name");
701             errors.addError(fsb.toString());
702         }
703
704         user.clear();
705         user.setEmail(email);
706
707         if (user.find()) {
708             FastStringBuffer fsb = new FastStringBuffer(64);
709             fsb.append("Email \"");
710             fsb.append(email);
711             fsb.append("\" is already registered in db/context '");
712             fsb.append(request.getDataContext());
713             fsb.append("'");
714             errors.addError(fsb.toString());
715         }
716
717         if (errors.getErrorCount() > 0) {
718             delayLogin(); //Make 'em pay :)
719

720             return user;
721         }
722
723         user.clear();
724         user.setDataContext(request.getDataContext());
725         user.setLoginName(loginName);
726         user.setEmail(email);
727         user.setDisplayName(loginName);
728
729         if (emailValidate) {
730             user.setAccountStatus("I");
731         } else if (approvalRequired) {
732             user.setAccountStatus("W");
733         } else {
734             user.setAccountStatus("A");
735         }
736
737         if (!userPasswd) {
738             password = user.randomPassword();
739         }
740
741         user.setPassword(password);
742         user.setRegistrationDomain(regDomain);
743         user.add();
744
745         if (log.isDebugEnabled()) {
746             log.debug("Added user id '" + user.getUid() + "' for login name '" +
747                     user.getLoginName() + "'");
748         }
749
750         String JavaDoc groupName = null;
751
752         if (rd.getField("RegRequired").equalsIgnoreCase("Y")) {
753             groupName = "NotReg";
754         } else {
755             groupName = rd.getField(GroupMembers.GROUP_NAME);
756         }
757
758         GroupMembers gm = new GroupMembers();
759         gm.setDataContext(request.getDataContext());
760
761         StringTokenizer JavaDoc stk = new StringTokenizer JavaDoc(groupName, " ");
762
763         while (stk.hasMoreTokens()) {
764             gm.setField(GroupMembers.GROUP_NAME, stk.nextToken());
765             gm.setField(GroupMembers.EXPUID, user.getUid());
766             gm.add();
767         }
768
769         // response.clearFormCache();
770
// Output successMessage = null;
771
// Output infoMessage = null;
772
// ServletControllerRequest sparams = (ServletControllerRequest) request;
773
// HttpServletRequest hreq = (HttpServletRequest) sparams.getServletRequest();
774

775         /**
776          * @todo implement code here that gives out the appropriate success
777          * message
778          */

779
780         // response.addOutput(successMessage);
781
// response.addOutput(infoMessage);
782
// String nextObj = request.getParameter("dbobj");
783
// If email validation is required or the system generates a password
784
// for the user, then simply show confirmation of express registration
785
// since the user needs to receive email first.
786
// Otherwise, automatically move on to detailed registration (if needed)
787
// if (nextObj != null) {
788
// Transition continueRegister = new Transition();
789
// continueRegister.addParam(Controller.CONTROLLER_PARAM_KEY,this.getClass().getName());
790
// continueRegister.addParam(STATE_PARAM_KEY, "promptAddRecord");
791
// continueRegister.addParam("dbobj", nextObj);
792
// continueRegister.addParam("dbContext", request.getDBName());
793
// continueRegister.addParam("uid", user.getUidString());
794
// continueRegister.addParam("loginController",loginController);
795
// continueRegister.setLabel("Continue Registration");
796
//
797
//
798
// continueRegister.transition(request, response);
799
// if (log.isDebugEnabled()) {
800
// log.debug("Transitioned to register...");
801
// }
802
// return;
803
// } else {
804
// this.processPostRegistration(request,response, user,rd, loginController);
805
// }
806
return user;
807     }
808
809     /**
810      * Processes post Registration If the user is done.
811      *
812      * @param request the ControllerRequest Object
813      * @param response the ControllerResponse object
814      * @param user An instantiated user object representing the current User
815      * registering
816      * @param rd The RegistrationDomain that this user is registering for
817      * @param loginControllerName The name of the login controller used for
818      * referencing back to this class
819      * @return A completed ControllerResponse object
820      * @throws NonHandleableException upon fatal error
821      */

822     protected ControllerResponse processPostRegistration(ControllerRequest request, ControllerResponse response, User user,
823                                                          RegistrationDomain rd, String JavaDoc loginControllerName)
824             throws DBException, ControllerException, NonHandleableException {
825         boolean backToMenu = false;
826
827         if (StringUtil.notNull(request.getParameter("backToMenu"))
828                 .equalsIgnoreCase("Y")) {
829             backToMenu = true;
830         }
831         //Used for generating messages.
832

833         FastStringBuffer fsb = new FastStringBuffer(56);
834         boolean emailValidate = false;
835         boolean approvalRequired = false;
836
837         //Set up registration domain parameters
838
if (rd.getField("EmailValidate").equalsIgnoreCase("Y")) {
839             emailValidate = true;
840         }
841
842         if (rd.getField("Approve").equalsIgnoreCase("Y")) {
843             approvalRequired = true;
844         }
845
846         Output successMessage = null;
847         Output infoMessage = null;
848         HttpServletRequest JavaDoc hreq = (HttpServletRequest JavaDoc) ((ServletControllerRequest) request).getServletRequest();
849
850         // No more records to add ... complete registration
851
//Make sure that this does not require manual approval
852
if (approvalRequired) {
853             try {
854                 ValidationEntry ve = new ValidationEntry(request.getDataContext());
855                 ve.setValidationHandler("com.jcorporate.expresso.services.validation.ApproveRegistrationValidator");
856                 ve.setTitle("Registration Approval Validation");
857
858                 //
859
//Set admin expiration for 1 week.
860
//
861
ve.expiresAfter(24 * 7, 0, 0);
862                 fsb.clear();
863                 fsb.append("user=");
864                 fsb.append(user.getLoginName());
865                 fsb.append(", db=");
866                 fsb.append(request.getDataContext());
867                 ve.setDesc(fsb.toString());
868                 ve.setServer(hreq.getServerName());
869                 ve.setPort(Integer.toString(hreq.getServerPort()));
870                 ve.setContextPath(hreq.getContextPath());
871                 ve.addParam("db", request.getDataContext());
872                 ve.addParam("UserName", user.getLoginName());
873                 ve.addParam("RegistrationController", this.getClass().getName());
874                 ve.addParam("LoginController", loginControllerName);
875                 ve.submit();
876             } catch (AuthValidationException avex) {
877                 throw new ControllerException("Validation framework exception",
878                         avex);
879             }
880
881             response.addOutput(new Output("successMessage",
882                     response.getString("registration.success.approval", user.getLoginName(),
883                             request.getDataContext())));
884             response.addOutput(new Output("infoMessage",
885                     response.getString("registration.info.approval")));
886         } else if (emailValidate) {
887             setupEmailValidation(request, response, user, rd,
888                     loginControllerName);
889             successMessage = new Output("successMessage",
890                     response.getString("registration.success.validate", user.getLoginName(), request.getDataContext()));
891             infoMessage = new Output("infoMessage", response.getString("registration.info.validate", user.getEmail()));
892         } else {
893             // If the user is a member of the "Not Regsitered Yet" group,
894
// move user to group specified in domain
895
GroupMembers gm = new GroupMembers();
896             gm.setDataContext(request.getDataContext());
897             gm.setField(GroupMembers.EXPUID, user.getUid());
898             gm.setField(GroupMembers.GROUP_NAME, "NotReg");
899
900             if (gm.find()) {
901                 String JavaDoc groupName = rd.getField(GroupMembers.GROUP_NAME);
902
903                 if ((groupName == null) || (groupName.equals(""))) {
904                     groupName = UserGroup.ALL_USERS_GROUP;
905                 }
906
907                 gm.delete();
908                 gm.clear();
909                 gm.setField(GroupMembers.EXPUID, user.getUid());
910                 gm.setField(GroupMembers.GROUP_NAME, groupName);
911                 gm.add();
912             }
913
914             successMessage = new Output("successMessage",
915                     "You are fully registered and may log in now.");
916
917             if (!approvalRequired && !emailValidate) {
918                 StringBuffer JavaDoc msg = new StringBuffer JavaDoc(128);
919                 msg.append(response.getString("loginConfEM",
920                         user.getLoginName(),
921                         "<undisclosed for security reasons>",
922                         Setup.getValue(request.getDataContext(), "CompanyName"),
923                         Setup.getValue(request.getDataContext(), "HomePageURL")));
924
925                 try {
926                     user.notify(response.getString("loginConfSubj"), msg.toString());
927                 } catch (Exception JavaDoc e) {
928                     log.error("Trouble sending registration-welcome email to user: " + request.getUser(), e);
929                     response.addError("Cannot send response email: " + e.getClass().getName() + "; " + e.getMessage());
930                 }
931             }
932
933             if (backToMenu) {
934                 transition("showDBMenu", request, response);
935             }
936
937             Transition doLogin = new Transition();
938             doLogin.setName("promptLogin");
939             doLogin.setLabel("Go To Login");
940             doLogin.addParam(Controller.CONTROLLER_PARAM_KEY, loginControllerName);
941             doLogin.addParam(STATE_PARAM_KEY, "promptLogin");
942             doLogin.addParam("dbContext", request.getDataContext());
943             response.add(doLogin);
944         }
945
946         checkRegComplete(request, user.getUid());
947
948         if (successMessage != null) {
949             response.add(successMessage);
950         }
951
952         if (infoMessage != null) {
953             response.add(infoMessage);
954         }
955
956         return response;
957     }
958
959     /**
960      * If the user validates correctly, this method completes registration and
961      * sends the email notification out. If admin. authorization is required
962      * this will setup the authorization process.
963      *
964      * @param request The ControllerRequest object handed down by the framework
965      * for this request
966      * @param response The ControllerResponse object returned by this
967      * controller
968      * @throws ControllerException upon error of processing this state.
969      */

970     protected void runEmailValidateState(ControllerRequest request,
971                                          ControllerResponse response) throws ControllerException {
972         // Check to make sure the request first went through ValidationController
973
if (request.getSession().getPersistentAttribute(ValidationEntry.SESSION_KEY) == null) {
974             throw new SecurityException JavaDoc("Attempt to run emailValidate without first validating");
975         }
976         else {
977             request.getSession().removePersistentAttribute(ValidationEntry.SESSION_KEY);
978         }
979         
980         String JavaDoc dbname = StringUtil.notNull(request.getParameter("db"));
981
982         // The login name of the user
983
String JavaDoc loginName = StringUtil.notNull(request.getParameter("UserName"));
984         String JavaDoc registrationController = StringUtil.notNull(request.getParameter("RegistrationController"));
985         String JavaDoc loginController = StringUtil.notNull(request.getParameter("LoginController"));
986
987         try {
988             ErrorCollection errors = new ErrorCollection();
989
990             // Make sure that the user with this loginName actually exists
991
User user = new User();
992             user.setDataContext(dbname);
993             user.setLoginName(loginName);
994
995             if (!user.find()) {
996                 errors.addError("Account \"" + loginName + "\" not found");
997             }
998
999             // Make sure the User record has not been disabled for some reason, or, already authenticated
1000
if (errors.isEmpty()) {
1001                if (user.getAccountStatus().equals("D")) {
1002                    errors.addError("Account \"" + loginName +
1003                            "\" has been disabled");
1004                } else if (user.getAccountStatus().equals("A")) {
1005                    errors.addError("Account \"" + loginName +
1006                            "\" was already authenticated");
1007
1008                    Output o = new Output("infoMessage",
1009                            "This account has been activated previously. " +
1010                            "Please use the password that was sent to you via email. " +
1011                            "It takes a few minutes after authentication to receive the email. " +
1012                            "If you have not received the email after waiting a reasonable amount of time, " +
1013                            "please contact us via email so we can assist you.");
1014                    response.add(o);
1015                }
1016
1017                if (!errors.isEmpty()) {
1018                    response.saveErrors(errors);
1019
1020                    return;
1021                }
1022
1023                // If we get here, everything went OK...time to set the user's status as "active"
1024
// Determine if the registration domain defines that the user should specify
1025
// own password or if one should automatically be defined for the user
1026
boolean userPasswd = false;
1027                RegistrationDomain rd = new RegistrationDomain();
1028                rd.setDataContext(dbname);
1029                rd.setField("Name", user.getRegistrationDomain());
1030
1031                if (!rd.find()) {
1032                    throw new ControllerException("Registration domain \"" +
1033                            user.getRegistrationDomain() + "\" not created yet");
1034                }
1035
1036                if (rd.getField("UserPasswd").equals("Y")) {
1037                    userPasswd = true;
1038                }
1039
1040                // Create the content of the registration message to be sent
1041
StringBuffer JavaDoc msg = new StringBuffer JavaDoc();
1042                msg.append(response.getString("loginAuthenticatedEM1",
1043                        user.getLoginName(),
1044                        Setup.getValue(dbname, "CompanyName")));
1045
1046                if (!userPasswd) {
1047                    // User doesn't specify password, create a random password
1048
String JavaDoc password = user.randomPassword();
1049                    user.setPassword(password);
1050                    msg.append(response.getString("loginAuthenticatedEM2",
1051                            password));
1052                } else {
1053                    msg.append(response.getString("loginAuthenticatedEM3"));
1054                }
1055
1056                msg.append(response.getString("loginAuthenticatedEM4",
1057                        Setup.getValue(dbname, "CompanyName"),
1058                        Setup.getValue(dbname, "HomePageURL")));
1059
1060                // mark this user as "activated"
1061
user.setAccountStatus("A");
1062                user.update();
1063
1064                // If the user is a member of the "Not Regsitered Yet" group,
1065
// move user to group specified in domain
1066
GroupMembers gm = new GroupMembers();
1067                gm.setDataContext(request.getDataContext());
1068                gm.setField(GroupMembers.EXPUID, user.getUid());
1069                gm.setField(GroupMembers.GROUP_NAME, "NotReg");
1070                if (gm.find()) {
1071                    gm.delete();
1072                }
1073                
1074                String JavaDoc groupName = rd.getField(GroupMembers.GROUP_NAME);
1075                if ((groupName == null) || (groupName.equals(""))) {
1076                    groupName = UserGroup.ALL_USERS_GROUP;
1077                }
1078                gm.clear();
1079                gm.setField(GroupMembers.EXPUID, user.getUid());
1080                gm.setField(GroupMembers.GROUP_NAME, groupName);
1081                if (!gm.find()) {
1082                    gm.add();
1083                }
1084                
1085                // Send the confirmation email
1086
user.notify(response.getString("loginAuthenticatedSubject"),
1087                        msg.toString());
1088
1089                // Confirmation messages for the UI
1090
Output o1 = new Output("successMessage",
1091                        "Account \"" + user.getLoginName() +
1092                        "\" Validated Successfully");
1093                response.add(o1);
1094
1095                Output o2 = new Output("infoMessage",
1096                        "Your account is now activated. " +
1097                        "An email has been sent to \"" + user.getEmail() +
1098                        "\" containing your password.");
1099                response.add(o2);
1100
1101                Transition login = new Transition();
1102                login.setName("promptLogin");
1103                login.addParam(CONTROLLER_PARAM_KEY, loginController);
1104                login.addParam("dbContext", dbname);
1105                response.add(login);
1106
1107                Transition editPref = new Transition();
1108                editPref.setName("editPreferences");
1109                editPref.addParam(CONTROLLER_PARAM_KEY,
1110                        "com.jcorporate.expresso.services.controller.EditUserPreference");
1111                editPref.addParam(STATE_PARAM_KEY, "edit");
1112                response.add(editPref);
1113
1114                Transition showDBMenu = new Transition();
1115                showDBMenu.setName("showDBMenu");
1116                showDBMenu.addParam(CONTROLLER_PARAM_KEY, registrationController);
1117                showDBMenu.addParam(STATE_PARAM_KEY, "showDBMenu");
1118                response.add(showDBMenu);
1119
1120                Transition sendPW = new Transition();
1121                sendPW.setName("promptSendPassword");
1122                sendPW.addParam(CONTROLLER_PARAM_KEY, loginController);
1123                sendPW.addParam(STATE_PARAM_KEY, "promptSendPassword");
1124                response.add(sendPW);
1125
1126                Transition logout = new Transition();
1127                logout.setName("processLogout");
1128                logout.addParam(CONTROLLER_PARAM_KEY, loginController);
1129                response.add(logout);
1130            } else {
1131                response.saveErrors(errors);
1132            }
1133        } catch (DBException dbe) {
1134            throw new ControllerException("DB error", dbe);
1135        }
1136    }
1137
1138    /**
1139     * Processes the addition of a registration record.
1140     *
1141     * @param request The ControllerRequest object handed down by the framework
1142     * for this request
1143     * @param response The ControllerResponse object returned by this
1144     * controller
1145     * @throws ControllerException upon error of processing this state.
1146     * @throws NonHandleableException upon fatal error
1147     */

1148    protected void runProcessAddRecordState(ControllerRequest request,
1149                                            ControllerResponse response)
1150            throws ControllerException, NonHandleableException {
1151        String JavaDoc dbContext = StringUtil.notNull(request.getParameter("dbContext"));
1152        String JavaDoc loginControllerName = getLoginController(request);
1153
1154        if (!dbContext.equals("")) {
1155            request.setDataContext(dbContext);
1156        }
1157
1158        boolean backToMenu = false;
1159
1160        if (StringUtil.notNull(request.getParameter("backToMenu"))
1161                .equalsIgnoreCase("Y")) {
1162            backToMenu = true;
1163        }
1164
1165        User user = null;
1166
1167        try {
1168            user = new User();
1169            user.setDataContext(request.getDataContext());
1170            user.setUid(request.getUid());
1171            user.retrieve();
1172        } catch (DBException de) {
1173            throw new ControllerException(de);
1174        }
1175
1176        RegistrationDomain rd = getRegDomain(request, user);
1177        DBObject db = loadDBObject(request, request.getParameter("dbobj"));
1178
1179        try {
1180            RegistrationObjectMap rom = new RegistrationObjectMap();
1181            rom.setDataContext(request.getDataContext());
1182            rom.setField("RegDomId", rd.getField("RegDomId"));
1183            rom.setField("RegObj", request.getParameter("dbobj"));
1184
1185            if (!rom.find()) {
1186                throw new ControllerException("Cannot find registration object map entry");
1187            }
1188
1189            db.setField(rom.getField("UidField"), user.getUid());
1190            db.setDataContext(request.getDataContext());
1191
1192            //Set up registration domain parameters
1193
ErrorCollection ec = new ErrorCollection();
1194            db = (DBObject) DefaultAutoElement.getAutoControllerElement()
1195                    .parseBlock(request, db, ec);
1196
1197            // for (Iterator e = db.getFieldListIterator(); e.hasNext();) {
1198
// fieldName = (String)e.next();
1199
//
1200
// if (isShowable(rd, db, fieldName, false)) {
1201
// request.validateDBField(fieldName,db,ec);
1202
// }
1203
// }
1204
response.setFormCache();
1205
1206            if (ec.size() > 0) {
1207                response.saveErrors(ec);
1208
1209                if (log.isDebugEnabled()) {
1210                    log.debug("There were errors");
1211                }
1212
1213                transition("promptAddRecord", request, response);
1214
1215                return;
1216            }
1217
1218            if (db.getMetaData().isField("IPAddress")) {
1219                ServletControllerRequest sparams = (ServletControllerRequest) request;
1220                HttpServletRequest JavaDoc hreq = (HttpServletRequest JavaDoc) sparams.getServletRequest();
1221                db.setField("IPAddress", hreq.getRemoteAddr());
1222            }
1223
1224            db.add();
1225
1226            if (backToMenu) {
1227                request.setParameter("backToMenu", "Y");
1228                transition("showDBMenu", request, response);
1229
1230                return;
1231            }
1232
1233            /* If there are more records to be added, continue... */
1234            String JavaDoc nextToAdd = nextToAdd(request);
1235
1236            if (nextToAdd != null) {
1237                if (!nextToAdd.equals(db.getClass().getName())) {
1238                    request.setParameter("dbobj", nextToAdd);
1239                }
1240
1241                transition("promptAddRecord", request, response);
1242
1243                return;
1244            } else {
1245                processPostRegistration(request, response, user, rd,
1246                        loginControllerName);
1247            }
1248        } catch (DBException dbe) {
1249            throw new ControllerException(dbe);
1250        }
1251    }
1252
1253    /**
1254     * Processes the 'administrator wishes to process the approval state'
1255     *
1256     * @param request The ControllerRequest object handed down by the framework
1257     * for this request
1258     * @param response The ControllerResponse object returned by this
1259     * controller
1260     * @throws ControllerException upon error of processing this state.
1261     * @throws NonHandleableException upon fatal error
1262     */

1263    protected void runProcessApprovalState(ControllerRequest request,
1264                                           ControllerResponse response)
1265            throws ControllerException, NonHandleableException {
1266        ErrorCollection errors = new ErrorCollection();
1267        String JavaDoc loginName = request.getUser();
1268        String JavaDoc loginControllerName = getLoginController(request);
1269
1270        try {
1271            User myUser = new User();
1272            myUser.setDataContext(request.getDataContext());
1273            myUser.setLoginName(loginName);
1274
1275            //
1276
//NOTE: the below code is no replacement for individually securing
1277
//this controller's states.
1278
//
1279
if (loginName.equals("") || loginName.equals(User.UNKNOWN_USER) ||
1280                    !myUser.find()) {
1281                errors.addError("Must login before approving users");
1282                response.saveErrors(errors);
1283                throw new SecurityException JavaDoc("Must login before approving users");
1284            }
1285
1286            String JavaDoc dbContext = request.getParameter("db");
1287            String JavaDoc loginToApprove = request.getParameter("UserName");
1288            String JavaDoc cmd = request.getParameter("command");
1289            User u = new User();
1290
1291            if (errors.isEmpty()) {
1292                u.setDataContext(dbContext);
1293                u.setLoginName(loginToApprove);
1294
1295                if (!u.find()) {
1296                    errors.addError("User \"" + loginToApprove +
1297                            "\" not found");
1298                }
1299            }
1300
1301            RegistrationDomain rd = new RegistrationDomain();
1302
1303            if (errors.isEmpty()) {
1304                rd.setDataContext(dbContext);
1305                rd.setField("Name", u.getRegistrationDomain());
1306
1307                if (!rd.find()) {
1308                    errors.addError("Registration domain \"" +
1309                            u.getRegistrationDomain() + "\" not found");
1310                } else {
1311                    String JavaDoc approvers = rd.getField("Approvers");
1312                    StringTokenizer JavaDoc stk = new StringTokenizer JavaDoc(approvers, ",");
1313                    boolean havePermission = false;
1314
1315                    if (loginName.equals(User.ADMIN_USER)) {
1316                        havePermission = true;
1317                    }
1318
1319                    while (stk.hasMoreTokens() && !havePermission) {
1320                        if (stk.nextToken().equals(loginName)) {
1321                            havePermission = true;
1322                        }
1323                    }
1324
1325                    if (!havePermission) {
1326                        errors.addError("You (" + loginName +
1327                                ") do not have permission to approve users in this domain");
1328                    }
1329                }
1330            }
1331
1332            if (errors.isEmpty()) {
1333                StringBuffer JavaDoc msg = new StringBuffer JavaDoc();
1334                String JavaDoc subject = null;
1335                Output successMessage = new Output("successMessage",
1336                        "Approval for user \"" + loginToApprove +
1337                        "\" processed successfully");
1338                Output infoMessage = null;
1339
1340                if (cmd.equals("approve")) {
1341                    if (rd.getField("EmailValidate").equalsIgnoreCase("Y")) {
1342                        u.setAccountStatus("I");
1343                    } else {
1344                        u.setAccountStatus("A");
1345                    }
1346
1347                    // If the user is a member of the "Not Regsitered Yet" group,
1348
// move user to group specified in domain
1349
GroupMembers gm = new GroupMembers();
1350                    gm.setDataContext(request.getDataContext());
1351                    gm.setField(GroupMembers.EXPUID, u.getUid());
1352                    gm.setField(GroupMembers.GROUP_NAME, "NotReg");
1353
1354                    try {
1355                        gm.retrieve();
1356
1357                        String JavaDoc groupName = rd.getField(GroupMembers.GROUP_NAME);
1358
1359                        if ((groupName == null) || (groupName.equals(""))) {
1360                            groupName = UserGroup.ALL_USERS_GROUP;
1361                        }
1362
1363                        gm.delete();
1364                        gm.clear();
1365                        gm.setField(GroupMembers.EXPUID, u.getUid());
1366                        gm.setField(GroupMembers.GROUP_NAME, groupName);
1367                        gm.add();
1368                    } catch (DBException ex) {
1369                        if (log.isDebugEnabled()) {
1370                            log.debug("Didn't find group for uid: " +
1371                                    u.getUid());
1372                        }
1373                    }
1374
1375                    subject = response.getString("loginApprovedSubject");
1376
1377                    if (rd.getField("EmailValidate").equalsIgnoreCase("Y")) {
1378                        msg.append(response.getString("loginAuthenticatedEM1",
1379                                u.getLoginName(),
1380                                Setup.getValue(request.getDataContext(),
1381                                        "CompanyName")));
1382                    } else {
1383                        msg.append(response.getString("loginRegisteredEM1",
1384                                u.getLoginName(),
1385                                Setup.getValue(request.getDataContext(),
1386                                        "CompanyName")));
1387
1388                        if (rd.getField("UserPasswd").equalsIgnoreCase("Y")) {
1389                            msg.append(response.getString("loginAuthenticatedEM3"));
1390                        } else {
1391                            String JavaDoc password = u.randomPassword();
1392                            u.setPassword(password);
1393                            msg.append(response.getString("loginAuthenticatedEM2", password));
1394                        }
1395                    }
1396
1397                    msg.append(response.getString("loginAuthenticatedEM4",
1398                            Setup.getValue(request.getDataContext(),
1399                                    "CompanyName"),
1400                            Setup.getValue(request.getDataContext(),
1401                                    "HomePageURL")));
1402                    infoMessage = new Output("infoMessage",
1403                            "Registration was approved, user was notified by email");
1404                } else if (cmd.equals("postpone")) {
1405                    ValidationEntry ve = (ValidationEntry) request.getSession()
1406                            .getPersistentAttribute(ValidationEntry.SESSION_KEY);
1407
1408                    if (ve != null) {
1409                        ve.setStatus(ValidationEntry.WAITING);
1410                        request.getSession().removePersistentAttribute(ValidationEntry.SESSION_KEY);
1411                    }
1412
1413                    infoMessage = new Output("infoMessage",
1414                            "Registration Decision Postponed");
1415                    successMessage = new Output("successMessage", "Postponement");
1416                    response.add(infoMessage);
1417                    response.add(successMessage);
1418
1419                    return;
1420                } else if (cmd.equals("deny")) {
1421                    u.setAccountStatus("X");
1422                    subject = response.getString("loginDeniedSubject");
1423                    msg.append(response.getString("loginDeniedMsg",
1424                            Setup.getValue(request.getDataContext(),
1425                                    "CompanyName"), u.getLoginName(),
1426                            Setup.getValue(request.getDataContext(),
1427                                    "HomePageURL"), "Didn't meet our criteria"));
1428                    infoMessage = new Output("infoMessage",
1429                            "Registration was denied, user was notified by email");
1430                } else {
1431                    throw new ControllerException("Invalid Command");
1432                }
1433
1434                u.update();
1435
1436                // If email validation is required by the user's registration domain
1437
// then just send email for the email validation. Otherwise, notify
1438
// the user that approval has been granted/denied.
1439
if (rd.getField("EmailValidate").equalsIgnoreCase("Y")) {
1440                    setupEmailValidation(request, response, u, rd,
1441                            loginControllerName);
1442                } else {
1443                    u.notify(subject, msg.toString());
1444                }
1445
1446                response.add(successMessage);
1447                response.add(infoMessage);
1448            }
1449        } catch (AuthValidationException ex) {
1450            ValidationEntry ve = (ValidationEntry) request.getSession()
1451                    .getPersistentAttribute(ValidationEntry.SESSION_KEY);
1452
1453            try {
1454                if (ve != null) {
1455                    ve.setStatus(ValidationEntry.WAITING);
1456                }
1457            } catch (AuthValidationException ex1) {
1458                log.error("Error in prompting for authorization and unable to reset Validation Entry ",
1459                        ex);
1460            }
1461        } catch (DBException dbe) {
1462            ValidationEntry ve = (ValidationEntry) request.getSession()
1463                    .getPersistentAttribute(ValidationEntry.SESSION_KEY);
1464
1465            try {
1466                if (ve != null) {
1467                    ve.setStatus(ValidationEntry.WAITING);
1468                }
1469            } catch (AuthValidationException ex) {
1470                log.error("Error in prompting for authorization and unable to reset Validation Entry ",
1471                        ex);
1472            }
1473
1474            throw new ControllerException(dbe);
1475        }
1476    }
1477
1478    /**
1479     * Deletes a registration record.
1480     *
1481     * @param request The ControllerRequest object handed down by the framework
1482     * for this request
1483     * @param response The ControllerResponse object returned by this
1484     * controller
1485     * @throws ControllerException upon error of processing this state.
1486     * @throws NonHandleableException upon fatal error
1487     */

1488    protected void runProcessDeleteRecordState(ControllerRequest request,
1489                                               ControllerResponse response)
1490            throws ControllerException, NonHandleableException {
1491        User user = getRegUser(request);
1492        RegistrationDomain rd = getRegDomain(request, user);
1493        String JavaDoc dbname = getDB(request);
1494        String JavaDoc keys = request.getParameter("keys");
1495        SecuredDBObject db = loadDBObject(request, dbname);
1496
1497        try {
1498            RegistrationObjectMap rom = new RegistrationObjectMap();
1499            rom.setDataContext(request.getDataContext());
1500            rom.setField("RegDomId", rd.getField("RegDomId"));
1501            rom.setField("RegObj", dbname);
1502
1503            if (!rom.find()) {
1504                throw new ControllerException("Cannot find registration object map entry");
1505            }
1506
1507            db.setField(rom.getField("UidField"), user.getUid());
1508
1509            StringTokenizer JavaDoc stk = new StringTokenizer JavaDoc(keys, "|");
1510
1511            for (Iterator JavaDoc k = db.getKeyFieldListIterator(); k.hasNext();) {
1512                String JavaDoc fn = (String JavaDoc) k.next();
1513                db.setField(fn, stk.nextToken());
1514            }
1515
1516            if (!db.find()) {
1517                throw new ControllerException("Record with keys=" + keys +
1518                        " not found");
1519            }
1520
1521            db.delete();
1522            checkRegComplete(request, user.getUid());
1523        } catch (DBException dbe) {
1524            throw new ControllerException(dbe);
1525        }
1526
1527        transition("showDBMenu", request, response);
1528    }
1529
1530    /**
1531     * Lists the registration records.
1532     *
1533     * @param request The ControllerRequest object handed down by the framework
1534     * for this request
1535     * @param response The ControllerResponse object returned by this
1536     * controller
1537     * @throws ControllerException upon error of processing this state.
1538     */

1539    protected void runProcessListRecordsState(ControllerRequest request,
1540                                              ControllerResponse response) throws ControllerException {
1541        ErrorCollection errors = new ErrorCollection();
1542        User user = getRegUser(request);
1543        RegistrationDomain rd = getRegDomain(request, user);
1544        String JavaDoc dbname = getDB(request);
1545        SecuredDBObject db = loadDBObject(request, dbname);
1546        Block row = null;
1547        String JavaDoc loginControllerName = getLoginController(request);
1548
1549        try {
1550            RegistrationObjectMap rom = new RegistrationObjectMap();
1551            rom.setDataContext(request.getDataContext());
1552            rom.setField("RegDomId", rd.getField("RegDomId"));
1553            rom.setField("RegObj", dbname);
1554
1555            if (!rom.find()) {
1556                throw new ControllerException("Cannot find registration object map entry");
1557            }
1558
1559            db.setField(rom.getField("UidField"), user.getUid());
1560
1561            SecuredDBObject oneRec = null;
1562            int recNum = 0;
1563
1564            for (Iterator JavaDoc e = db.searchAndRetrieveList().iterator();
1565                 e.hasNext();) {
1566                recNum++;
1567                oneRec = (SecuredDBObject) e.next();
1568                oneRec.setDataContext(request.getDataContext());
1569                row = new Block("row" + recNum);
1570
1571                Output col = new Output("");
1572                String JavaDoc fieldName = null;
1573
1574                for (Iterator JavaDoc k = oneRec.getMetaData().getFieldListArray()
1575                        .iterator(); k.hasNext();) {
1576                    fieldName = (String JavaDoc) k.next();
1577
1578                    if (isShowable(rd, db, fieldName, true)) {
1579                        col = new Output(fieldName, oneRec.getField(fieldName));
1580                        row.add(col);
1581                    }
1582                }
1583
1584                FastStringBuffer s = new FastStringBuffer(24);
1585
1586                for (Iterator JavaDoc k = oneRec.getKeyFieldListIterator();
1587                     k.hasNext();) {
1588                    String JavaDoc fn = (String JavaDoc) k.next();
1589                    s.append(oneRec.getField(fn));
1590                    s.append("|");
1591                }
1592
1593                String JavaDoc registrationControllerName = (this
1594                        .getSchemaInstance()).getRegistrationController()
1595                        .getClass().getName();
1596
1597                if (rom.getField("AllowEdit").equals("Y")) {
1598                    Transition edit = new Transition("Update", "Update",
1599                            registrationControllerName);
1600                    edit.addParam(STATE_PARAM_KEY, "promptUpdateRecord");
1601                    edit.addParam("dbobj", dbname);
1602                    edit.addParam("keys", s.toString());
1603                    edit.addParam("loginController", loginControllerName);
1604                    row.add(edit);
1605                }
1606
1607                if (rom.getField("AllowDel").equals("Y")) {
1608                    Transition delete = new Transition("Delete", "Delete",
1609                            registrationControllerName);
1610                    delete.addParam(STATE_PARAM_KEY, "promptDeleteRecord");
1611                    delete.addParam("dbobj", dbname);
1612                    delete.addParam("keys", s.toString());
1613                    delete.addParam("loginController", loginControllerName);
1614                    row.add(delete);
1615                }
1616
1617                response.add(row);
1618            }
1619
1620            if (errors.getErrorCount() != 0) {
1621                response = this.newState("showDBMenu", request);
1622                response.saveErrors(errors);
1623            }
1624        } catch (Exception JavaDoc e) {
1625            throw new ControllerException("Error processing list", e);
1626        }
1627    }
1628
1629    /**
1630     * Processes the Self-Registering Users
1631     *
1632     * @param request The ControllerRequest object handed down by the framework
1633     * for this request
1634     * @param response The ControllerResponse object returned by this
1635     * controller
1636     * @throws ControllerException upon error of processing this state.
1637     * @throws NonHandleableException upon fatal error
1638     */

1639    protected void runProcessSelfRegisterState(ControllerRequest request,
1640                                               ControllerResponse response)
1641            throws ControllerException, NonHandleableException {
1642        response.setFormCache();
1643
1644        String JavaDoc dbContext = StringUtil.notNull(request.getParameter("dbContext"));
1645
1646        if (!dbContext.equals("")) {
1647            request.setDataContext(dbContext);
1648        }
1649
1650        ErrorCollection ec = request.getErrorCollection();
1651
1652        if (ec == null) {
1653            ec = new ErrorCollection();
1654        }
1655
1656        try {
1657            RegistrationDomain rd = new RegistrationDomain();
1658            User user = processLoginInformation(ec, request, response, rd);
1659
1660            if (ec.getErrorCount() > 0) {
1661                response.setFormCache();
1662                response.saveErrors(ec);
1663                transition("promptSelfRegister", request, response);
1664
1665                return;
1666            }
1667
1668            //
1669
//Ok, we have ourselves a user, let's attempt to deal with the
1670
//registration objects.
1671
//
1672
DBObject[] expectedRegistrationObjects = this.getRequiredDBObjects(request,
1673                    rd, user);
1674
1675            if (expectedRegistrationObjects.length > 0) {
1676                expectedRegistrationObjects = (DBObject[]) DefaultAutoElement.getAutoControllerElement()
1677                        .parseBlocks(request,
1678                                expectedRegistrationObjects, ec);
1679            }
1680
1681            if (ec.getErrorCount() > 0) {
1682                response.setFormCache();
1683                response.saveErrors(ec);
1684                user.delete(); //It sucks but this way we essentially rollback the
1685

1686                //transaction
1687
transition("promptSelfRegister", request, response);
1688
1689                return;
1690            }
1691
1692            for (int i = 0; i < expectedRegistrationObjects.length; i++) {
1693                try {
1694                    expectedRegistrationObjects[i].add();
1695                } catch (DBException dbe) {
1696                    FastStringBuffer fsb = new FastStringBuffer(64);
1697                    fsb.append("Error adding registration object: '");
1698                    fsb.append(expectedRegistrationObjects[i].getMetaData()
1699                            .getDescription(request.getLocale()));
1700                    fsb.append("' Message: ");
1701                    fsb.append(dbe.getMessage());
1702
1703                    String JavaDoc errorMessage = fsb.toString();
1704                    ec.addError(errorMessage);
1705                    log.error(errorMessage, dbe);
1706                }
1707            }
1708
1709            if (ec.getErrorCount() > 0) {
1710                user.delete(); //It sucks but this way we essentially rollback the
1711

1712                //transaction
1713
response.saveErrors(ec);
1714                response.setFormCache();
1715                transition("promptSelfRegister", request, response);
1716
1717                return;
1718            }
1719
1720            this.processPostRegistration(request, response, user, rd,
1721                    this.getLoginController(request));
1722        } catch (DBException de) {
1723            log.error("DBException while processing self-register state", de);
1724            throw new ControllerException(de);
1725        } catch (LogException le) {
1726            log.error("LogException while processing self-register state", le);
1727            throw new ControllerException(le);
1728        }
1729    }
1730
1731    /**
1732     * Updates the Registration Record
1733     *
1734     * @param request The ControllerRequest object handed down by the framework
1735     * for this request
1736     * @param response The ControllerResponse object returned by this
1737     * controller
1738     * @throws ControllerException upon error of processing this state.
1739     */

1740    protected void runProcessUpdateRecordState(ControllerRequest request,
1741                                               ControllerResponse response)
1742            throws ControllerException, NonHandleableException {
1743        User user = getRegUser(request);
1744        RegistrationDomain rd = getRegDomain(request, user);
1745        String JavaDoc dbname = getDB(request);
1746        DBObject db = loadDBObject(request, dbname);
1747        DataObjectMetaData metadata = db.getMetaData();
1748        String JavaDoc fieldName = null;
1749
1750        try {
1751            ErrorCollection ec = new ErrorCollection();
1752
1753            for (Iterator JavaDoc e = db.getKeyFieldListIterator(); e.hasNext();) {
1754                fieldName = (String JavaDoc) e.next();
1755                db.setField(fieldName,
1756                        request.getParameter(dbname + "." + fieldName));
1757            }
1758
1759            RegistrationObjectMap rom = new RegistrationObjectMap();
1760            rom.setDataContext(request.getDataContext());
1761            rom.setField("RegDomId", rd.getField("RegDomId"));
1762            rom.setField("RegObj", dbname);
1763
1764            if (!rom.find()) {
1765                throw new ControllerException("Cannot find registration object map entry");
1766            }
1767
1768            db.setField(rom.getField("UidField"), user.getUid());
1769
1770            if (!db.find()) {
1771                ec.addError("Key fields did not match any record in DB");
1772            }
1773
1774
1775            db = (DBObject) DefaultAutoElement.getAutoControllerElement()
1776                    .parseBlock(request, db, ec);
1777
1778            response.setFormCache();
1779
1780
1781// for (Iterator e = metadata.getFieldListArray().iterator();
1782
// e.hasNext();) {
1783
// fieldName = (String) e.next();
1784
//
1785
// if (isShowable(rd, db, fieldName, false)) {
1786
// db.setField(fieldName,
1787
// request.getParameter(dbname + "." + fieldName));
1788
// request.validateField(fieldName, dbname + "." + fieldName,
1789
// db, ec);
1790
// }
1791
// }
1792

1793            if (ec.size() > 0) {
1794                response.saveErrors(ec);
1795                transition("promptUpdateRecord", request, response);
1796
1797                return;
1798            }
1799
1800            if (metadata.isField("IPAddress")) {
1801                ServletControllerRequest sparams = (ServletControllerRequest) request;
1802                HttpServletRequest JavaDoc hreq = (HttpServletRequest JavaDoc) sparams.getServletRequest();
1803                db.setField("IPAddress", hreq.getRemoteAddr());
1804
1805                if (log.isDebugEnabled()) {
1806                    log.debug("IP address recorded as '" +
1807                            hreq.getRemoteAddr() + "'");
1808                }
1809            } else {
1810                if (log.isDebugEnabled()) {
1811                    log.debug("Object '" + db.getClass().getName() +
1812                            "' does not have an IPAddress field");
1813                }
1814            }
1815
1816            db.update();
1817            checkRegComplete(request, user.getUid());
1818        } catch (DBException dbe) {
1819            throw new ControllerException(dbe);
1820        }
1821
1822        transition("showDBMenu", request, response);
1823    }
1824
1825    /**
1826     * Displays fill-in form for registration.
1827     *
1828     * @param request The ControllerRequest object handed down by the framework
1829     * for this request
1830     * @param response The ControllerResponse object returned by this
1831     * controller
1832     * @throws ControllerException upon error of processing this state.
1833     */

1834    protected void runPromptAddRecordState(ControllerRequest request,
1835                                           ControllerResponse response) throws ControllerException {
1836        String JavaDoc dbContext = StringUtil.notNull(request.getParameter("dbContext"));
1837        String JavaDoc loginControllerName = getLoginController(request);
1838
1839        if (!dbContext.equals("")) {
1840            request.setDataContext(dbContext);
1841        }
1842
1843        User user = null;
1844
1845        try {
1846            user = new User();
1847            user.setDataContext(request.getDataContext());
1848            user.setUid(request.getUid());
1849            user.retrieve();
1850        } catch (DBException de) {
1851            throw new ControllerException(de);
1852        }
1853
1854        RegistrationDomain rd = getRegDomain(request, user);
1855        String JavaDoc dbname = getDB(request);
1856        SecuredDBObject db = loadDBObject(request, dbname);
1857        Block formBlock = buildForm(rd, db, response);
1858        Transition add = new Transition("processAddRecord", this);
1859        add.addParam("dbobj", dbname);
1860        add.addParam("dbContext", request.getDataContext());
1861        add.addParam("loginController", loginControllerName);
1862
1863        if (StringUtil.notNull(request.getParameter("backToMenu"))
1864                .equalsIgnoreCase("Y")) {
1865            add.addParam("backToMenu", "Y");
1866        }
1867
1868        formBlock.add(add);
1869        response.addBlock(formBlock);
1870    }
1871
1872    /**
1873     * Displays the 'prompt admin for approval' page. Modify this page if you
1874     * want custom displays for your administrators.
1875     *
1876     * @param request The ControllerRequest object for the system.
1877     * @param response The ControllerResponse object for the system
1878     * @throws ControllerException upon state completion error.
1879     */

1880    protected void runPromptApprovalState(ControllerRequest request,
1881                                          ControllerResponse response)
1882            throws ControllerException, NonHandleableException {
1883        ErrorCollection errors = new ErrorCollection();
1884        String JavaDoc loginName = request.getUser();
1885        String JavaDoc dbContext = request.getParameter("db");
1886        String JavaDoc loginToApprove = request.getParameter("UserName");
1887        String JavaDoc loginControllerName = getLoginController(request);
1888
1889        try {
1890            User myUser = new User();
1891            myUser.setDataContext(request.getDataContext());
1892            myUser.setLoginName(loginName);
1893
1894            if (loginName.equals("") || loginName.equals(User.UNKNOWN_USER) ||
1895                    !myUser.find()) {
1896                errors.addError("Must login before approving users");
1897                response.saveErrors(errors);
1898                throw new SecurityException JavaDoc("Must login before approving users");
1899            }
1900
1901            User u = new User();
1902
1903            if (errors.isEmpty()) {
1904                u.setDataContext(dbContext);
1905                u.setLoginName(loginToApprove);
1906
1907                if (!u.find()) {
1908                    errors.addError("User \"" + loginToApprove +
1909                            "\" not found");
1910                }
1911            }
1912
1913            RegistrationDomain rd = new RegistrationDomain();
1914
1915            if (errors.isEmpty()) {
1916                rd.setDataContext(dbContext);
1917                rd.setField("Name", u.getRegistrationDomain());
1918
1919                if (!rd.find()) {
1920                    errors.addError("Registration domain \"" +
1921                            u.getRegistrationDomain() + "\" not found");
1922                } else {
1923                    String JavaDoc approvers = rd.getField("Approvers");
1924                    StringTokenizer JavaDoc stk = new StringTokenizer JavaDoc(approvers, ",");
1925                    boolean havePermission = false;
1926
1927                    if (loginName.equals(User.ADMIN_USER)) {
1928                        havePermission = true;
1929                    }
1930
1931                    while (stk.hasMoreTokens() && !havePermission) {
1932                        if (stk.nextToken().equals(loginName)) {
1933                            havePermission = true;
1934                        }
1935                    }
1936
1937                    if (!havePermission) {
1938                        errors.addError("You (" + loginName +
1939                                ") do not have permission to approve users in this domain");
1940                    }
1941                }
1942            }
1943
1944            if (errors.isEmpty()) {
1945                Transition approve = new Transition("processApproval", this);
1946                approve.setName("approve");
1947                approve.setLabel("Approve Registration");
1948                approve.addParam("command", "approve");
1949                approve.addParam("db", dbContext);
1950                approve.addParam("UserName", loginToApprove);
1951                approve.addParam("loginController", loginControllerName);
1952                response.add(approve);
1953
1954                Transition deny = new Transition("processApproval", this);
1955                deny.setName("deny");
1956                deny.setLabel("Deny Registration");
1957                deny.addParam("command", "deny");
1958                deny.addParam("db", dbContext);
1959                deny.addParam("UserName", loginToApprove);
1960                deny.addParam("loginController", loginControllerName);
1961                response.add(deny);
1962
1963                Transition postpone = new Transition("processApproval", this);
1964                postpone.setName("postpone");
1965                postpone.setLabel("Postpone Decision Until Later");
1966                postpone.addParam("command", "postpone");
1967                postpone.addParam("db", dbContext);
1968                postpone.addParam("UserName", loginToApprove);
1969                postpone.addParam("loginController", loginControllerName);
1970                response.add(postpone);
1971                response.add(new Output("LoginName", loginToApprove));
1972                response.add(new Output("Email", u.getEmail()));
1973                response.add(new Output("RegDomain", u.getRegistrationDomain()));
1974
1975                if (rd.getField("RegRequired").equalsIgnoreCase("Y")) {
1976                    RegistrationObjectMap rom = new RegistrationObjectMap();
1977                    rom.setDataContext(dbContext);
1978                    rom.setField("RegDomId", rd.getField("RegDomId"));
1979
1980                    SecuredDBObject db = null;
1981                    RegistrationObjectMap oneRom = null;
1982                    SecuredDBObject oneDB = null;
1983
1984                    for (Iterator JavaDoc dbIter = rom.searchAndRetrieveList("RegOrder")
1985                            .iterator(); dbIter.hasNext();) {
1986                        oneRom = (RegistrationObjectMap) dbIter.next();
1987
1988                        try {
1989                            db = (SecuredDBObject) Class.forName(oneRom.getField("RegObj")).newInstance();
1990                        } catch (Exception JavaDoc ex) {
1991                            throw new ControllerException("Dynamic load failed for " +
1992                                    oneRom.getField("RegObj"), ex);
1993                        }
1994
1995                        db.setDataContext(dbContext);
1996
1997                        Block regObj = new Block("RegObj");
1998                        response.add(regObj);
1999                        regObj.add(new Output("Desc", getString(db.getMetaData().getDescription()) +
2000                                ":"));
2001                        db.setField(oneRom.getField("UidField"), u.getUid());
2002
2003                        for (Iterator JavaDoc recIter = db.searchAndRetrieveList()
2004                                .iterator();
2005                             recIter.hasNext();) {
2006                            oneDB = (SecuredDBObject) recIter.next();
2007
2008                            Block regRec = new Block("RegRec");
2009                            regObj.add(regRec);
2010
2011                            StringBuffer JavaDoc s = new StringBuffer JavaDoc("");
2012
2013                            for (Iterator JavaDoc k = oneDB.getKeyFieldListIterator();
2014                                 k.hasNext();) {
2015                                String JavaDoc fn = (String JavaDoc) k.next();
2016                                s.append(oneDB.getField(fn) + "|");
2017                            }
2018
2019                            Transition dbMaint = new Transition();
2020                            dbMaint.setName("dbMaint");
2021                            dbMaint.setLabel("View Registration Record");
2022                            dbMaint.setControllerObject(com.jcorporate.expresso.services.controller.DBMaint.class);
2023                            dbMaint.addParam(STATE_PARAM_KEY, "Update");
2024                            dbMaint.addParam("key", s.toString());
2025                            dbMaint.addParam("dbobj",
2026                                    oneDB.getClass().getName());
2027                            regRec.add(dbMaint);
2028
2029                            Block fldTbl = new Block("FldTbl");
2030                            regRec.add(fldTbl);
2031
2032                            for (Iterator JavaDoc fldIter = oneDB.getMetaData()
2033                                    .getFieldListArray()
2034                                    .iterator();
2035                                 fldIter.hasNext();) {
2036                                String JavaDoc fn = (String JavaDoc) fldIter.next();
2037                                Block fldRec = new Block("FldRec");
2038                                fldTbl.add(fldRec);
2039                                fldRec.add(new Output("FldName",
2040                                        getString(oneDB.getMetaData().getDescription(fn))));
2041
2042                                String JavaDoc value = "";
2043
2044                                if (oneDB.getMetaData().isMultiValued(fn)) {
2045                                    value = StringUtil.notNull(oneDB.getValidValueDescrip(fn));
2046                                } else {
2047                                    value = StringUtil.notNull(oneDB.getField(fn));
2048                                }
2049
2050                                if (value.equals("")) {
2051                                    value = "&nbsp;";
2052                                }
2053
2054                                fldRec.add(new Output("FldVal", value));
2055                            }
2056                        }
2057                    }
2058                }
2059            } else {
2060                response.saveErrors(errors);
2061                response.setFormCache();
2062            }
2063        } catch (DBException dbe) {
2064            ValidationEntry ve = (ValidationEntry) request.getSession()
2065                    .getPersistentAttribute(ValidationEntry.SESSION_KEY);
2066
2067            try {
2068                if (ve != null) {
2069                    ve.setStatus(ValidationEntry.WAITING);
2070                }
2071            } catch (AuthValidationException ex) {
2072                log.error("Error in prompting for authorization and unable to reset Validation Entry ",
2073                        ex);
2074            }
2075
2076            throw new ControllerException(dbe);
2077        }
2078    }
2079
2080    /**
2081     * Displays confirmation of deleting a registration record.
2082     *
2083     * @param request The ControllerRequest object handed down by the framework
2084     * for this request
2085     * @param response The ControllerResponse object returned by this
2086     * controller
2087     * @throws ControllerException upon error of processing this state.
2088     */

2089    protected void runPromptDeleteRecordState(ControllerRequest request,
2090                                              ControllerResponse response) throws ControllerException {
2091        String JavaDoc loginControllerName = getLoginController(request);
2092        String JavaDoc dbname = getDB(request);
2093        String JavaDoc keys = request.getParameter("keys");
2094        Block formBlock = new Block("DeleteForm");
2095        formBlock.setForm("true");
2096
2097        Output msg = new Output("Confirm", "Are you sure you want to delete?");
2098        formBlock.add(msg);
2099
2100        Transition cancel = new Transition("Cancel", "Cancel",
2101                this.getClass().getName());
2102        cancel.addParam(STATE_PARAM_KEY, "showDBMenu");
2103        cancel.addParam("dbobj", dbname);
2104        cancel.addParam("loginController", loginControllerName);
2105        formBlock.add(cancel);
2106
2107        Transition delete = new Transition("processDeleteRecord", this);
2108        delete.addParam("dbobj", dbname);
2109        delete.addParam("keys", keys);
2110        delete.addParam("loginController", loginControllerName);
2111        formBlock.add(delete);
2112        response.addBlock(formBlock);
2113    }
2114
2115    /**
2116     * Displays the fill-in form for self-registering users
2117     *
2118     * @param request The ControllerRequest object handed down by the framework
2119     * for this request
2120     * @param response The ControllerResponse object returned by this
2121     * controller
2122     * @throws ControllerException upon error of processing this state.
2123     */

2124    protected void runPromptSelfRegisterState(ControllerRequest request,
2125                                              ControllerResponse response) throws ControllerException {
2126        try {
2127            String JavaDoc loginControllerName = getLoginController(request);
2128
2129            //What db context to use? Try to see if it was passed as a "dbContext=xxxx" argument in the request URL.
2130
//If that fails, use "default"
2131
String JavaDoc dbContext = StringUtil.notNull(request.getParameter("dbContext"));
2132
2133            if (!dbContext.equals("")) {
2134                request.setDataContext(dbContext);
2135            }
2136
2137            if (log.isDebugEnabled()) {
2138                log.debug("New registration in db '" +
2139                        request.getDataContext() + "'");
2140            }
2141
2142            // Which registration domain to use? Try to get it from the request URL.
2143
// If it fails, see if the site default specifies a default domain
2144
// Otherwise, set it to "default"
2145
String JavaDoc regDomain = StringUtil.notNull(request.getParameter("regDomain"));
2146
2147            if (regDomain.equals("")) {
2148                if (regDomain.equals("")) {
2149                    try {
2150                        regDomain = StringUtil.notNull(Setup.getValue(request.getDataContext(), "defaultRegDomain"));
2151                    } catch (DBException dbe) {
2152                        // Ignore the exception
2153
}
2154
2155                    if (regDomain.equals("")) {
2156                        regDomain = "default";
2157                    }
2158                }
2159            }
2160
2161            RegistrationDomain rd = new RegistrationDomain(SecuredDBObject.SYSTEM_ACCOUNT);
2162            rd.setDataContext(request.getDataContext());
2163            rd.setField("Name", regDomain);
2164
2165            if (!rd.find()) {
2166                throw new ControllerException("Registration domain \"" +
2167                        regDomain + "\" not created yet");
2168            }
2169
2170            Block b = this.buildLoginBlock(rd, request, response);
2171            response.add(b);
2172
2173            //
2174
//Get all the required registration objects. Then iterate through
2175
//them and add the appaopriate blocks.
2176
//
2177
DBObject[] registrationObjects = this.getRequiredDBObjects(request,
2178                    rd, null);
2179
2180            if (log.isDebugEnabled()) {
2181                log.debug("Registration domain is '" + regDomain + "'");
2182
2183                if (registrationObjects.length == 0) {
2184                    log.debug("There are no required registration objects");
2185                } else {
2186                    log.debug("New needs " + registrationObjects.length +
2187                            " records...");
2188                }
2189            }
2190
2191            for (int i = 0; i < registrationObjects.length; i++) {
2192                Block rb = this.buildForm(rd, registrationObjects[i], response);
2193                response.add(rb);
2194            }
2195
2196            Transition register = new Transition("processSelfRegister",
2197                    this.getSchemaInstance().getRegistrationController());
2198            register.addParam("regDomain", regDomain);
2199            register.addParam("dbContext", request.getDataContext());
2200            register.addParam("loginController", loginControllerName);
2201            register.setLabel("Submit");
2202            response.add(register);
2203        } catch (DBException dbe) {
2204            log.error("Error in State: promptSelfRegister", dbe);
2205            throw new ControllerException("Error in State: promptSelfRegister",
2206                    dbe);
2207        }
2208    }
2209
2210    /**
2211     * Displays the fill-in form for updating a record
2212     *
2213     * @param request The ControllerRequest object handed down by the framework
2214     * for this request
2215     * @param response The ControllerResponse object returned by this
2216     * controller
2217     * @throws ControllerException upon error of processing this state.
2218     * @throws NonHandleableException upon fatal error
2219     */

2220    protected void runPromptUpdateRecordState(ControllerRequest request,
2221                                              ControllerResponse response)
2222            throws ControllerException, NonHandleableException {
2223        User user = getRegUser(request);
2224        RegistrationDomain rd = getRegDomain(request, user);
2225        String JavaDoc dbname = getDB(request);
2226        String JavaDoc keys = request.getParameter("keys");
2227        SecuredDBObject db = loadDBObject(request, dbname);
2228        String JavaDoc uidFieldName = null;
2229        String JavaDoc loginControllerName = getLoginController(request);
2230
2231        try {
2232            RegistrationObjectMap rom = new RegistrationObjectMap();
2233            rom.setDataContext(request.getDataContext());
2234            rom.setField("RegObj", dbname);
2235
2236            if (!rom.find()) {
2237                throw new ControllerException("Registration object for db \"" +
2238                        dbname + "\" not found");
2239            }
2240
2241            uidFieldName = rom.getField("UidField");
2242            db.setField(uidFieldName, user.getUid());
2243
2244            StringTokenizer JavaDoc stk = new StringTokenizer JavaDoc(keys, "|");
2245
2246            for (Iterator JavaDoc k = db.getKeyFieldListIterator(); k.hasNext();) {
2247                String JavaDoc fn = (String JavaDoc) k.next();
2248                db.setField(fn, stk.nextToken());
2249            }
2250
2251            if (!db.find()) {
2252                Transition addInstead = new Transition("promptAddRecord", this);
2253                addInstead.addParam("dbobj", request.getParameter("dbobj"));
2254                addInstead.addParam("loginController", loginControllerName);
2255                addInstead.transition(request, response);
2256            }
2257        } catch (DBException dbe) {
2258            throw new ControllerException("Database exception reading RegistrationObjectMap",
2259                    dbe);
2260        }
2261
2262        Block formBlock = buildForm(rd, db, response);
2263        Transition cancel = new Transition("Cancel", "Cancel",
2264                this.getClass().getName());
2265        cancel.addParam(STATE_PARAM_KEY, "showDBMenu");
2266        cancel.addParam("dbobj", dbname);
2267        cancel.addParam("loginController", loginControllerName);
2268        formBlock.add(cancel);
2269
2270        Transition update = new Transition("processUpdateRecord", this);
2271        update.addParam("keys", keys);
2272        update.addParam("dbobj", dbname);
2273        formBlock.add(update);
2274        response.addBlock(formBlock);
2275    }
2276
2277    /**
2278     * Displays a menu of registrations to fill out.
2279     *
2280     * @param request The ControllerRequest object handed down by the framework
2281     * for this request
2282     * @param response The ControllerResponse object returned by this
2283     * controller
2284     * @throws ControllerException upon error of processing this state.
2285     * @throws NonHandleableException upon fatal error
2286     */

2287    protected void runShowDBMenuState(ControllerRequest request,
2288                                      ControllerResponse response)
2289            throws ControllerException, NonHandleableException {
2290        String JavaDoc loginControllerName = getLoginController(request);
2291
2292        try {
2293            User user = new User();
2294            user.setDataContext(request.getDataContext());
2295            user.setUid(request.getUid());
2296            user.retrieve();
2297
2298            RegistrationDomain rd = new RegistrationDomain();
2299            rd.setDataContext(request.getDataContext());
2300            rd.setField("Name", user.getRegistrationDomain());
2301
2302            if (!rd.find()) {
2303                throw new ControllerException("Domain " +
2304                        user.getRegistrationDomain() + " not created yet");
2305            }
2306
2307            RegistrationObjectMap rom = new RegistrationObjectMap();
2308            rom.setDataContext(request.getDataContext());
2309            rom.setField("RegDomId", rd.getField("RegDomId"));
2310
2311            RegistrationObjectMap oneRom = null;
2312            SecuredDBObject db = null;
2313            Block block = null;
2314            Output desc = null;
2315            Output recCount = null;
2316            Output recMin = null;
2317            Output recMax = null;
2318            Output must = null;
2319            Transition add = null;
2320            Transition update = null;
2321            Transition list = null;
2322            Transition delete = null;
2323            int min = 0;
2324            int max = 0;
2325
2326            for (Iterator JavaDoc e = rom.searchAndRetrieveList("RegOrder").iterator();
2327                 e.hasNext();) {
2328                oneRom = (RegistrationObjectMap) e.next();
2329                oneRom.setDataContext(request.getDataContext());
2330
2331                try {
2332                    min = Integer.parseInt(oneRom.getField("RecMin"));
2333                } catch (NumberFormatException JavaDoc ne) {
2334                    throw new ControllerException("Value '" +
2335                            oneRom.getField("RecMin") +
2336                            "' for Field RecMin in the registration" +
2337                            " domain is not a number");
2338                }
2339
2340                try {
2341                    max = Integer.parseInt(oneRom.getField("RecMax"));
2342                } catch (NumberFormatException JavaDoc ne) {
2343                    throw new ControllerException("Value '" +
2344                            oneRom.getField("RecMax") +
2345                            "' for Field RecMax in the registration" +
2346                            " domain is not a number");
2347                }
2348
2349                try {
2350                    db = (SecuredDBObject) Class.forName(oneRom.getField("RegObj")).newInstance();
2351                } catch (Exception JavaDoc ex) {
2352                    throw new ControllerException("Dynamic load failed for " +
2353                            oneRom.getField("RegObj"), ex);
2354                }
2355
2356                db.setDataContext(request.getDataContext());
2357
2358                String JavaDoc fieldName = oneRom.getField("UidField");
2359                db.setField(fieldName, user.getUid());
2360
2361                int records = db.count();
2362                block = new Block("RegistrationDB");
2363                desc = new Output("desc", getString(db.getMetaData().getDescription()));
2364                recMin = new Output("recMin", Integer.toString(min));
2365                recMax = new Output("recMax", Integer.toString(max));
2366                recCount = new Output("recCount", Integer.toString(records));
2367
2368                if ((min > 0) && (records < min)) {
2369                    must = new Output("inputNeeded", "Need Additional Data");
2370                    block.add(must);
2371                } else {
2372                    must = new Output("inputNotNeeded",
2373                            "Additional Data Not Needed");
2374                    block.add(must);
2375                }
2376
2377                if ((max == 0) || (records < max)) {
2378                    add = new Transition("promptAddRecord", this);
2379                    add.addParam("backToMenu", "Y");
2380                    add.addParam("dbobj", oneRom.getField("RegObj"));
2381                    add.addParam("uid", user.getUidString());
2382                    add.addParam("loginController", loginControllerName);
2383                    block.add(add);
2384                }
2385
2386                if (records > 0) {
2387                    if (records == 1) {
2388                        db.find();
2389
2390                        FastStringBuffer s = new FastStringBuffer(24);
2391
2392                        for (Iterator JavaDoc k = db.getKeyFieldListIterator();
2393                             k.hasNext();) {
2394                            String JavaDoc fieldName2 = (String JavaDoc) k.next();
2395                            s.append(db.getField(fieldName2));
2396                            s.append("|");
2397                        }
2398
2399                        if (oneRom.getField("AllowEdit").equals("Y")) {
2400                            update = new Transition("promptUpdateRecord", this);
2401                            update.addParam("dbobj", oneRom.getField("RegObj"));
2402                            update.addParam("uid", user.getUidString());
2403                            update.addParam("keys", s.toString());
2404                            update.addParam("loginController",
2405                                    loginControllerName);
2406                            block.add(update);
2407                        }
2408
2409                        if (oneRom.getField("AllowDel").equals("Y")) {
2410                            delete = new Transition("promptDeleteRecord", this);
2411                            delete.addParam("dbobj", oneRom.getField("RegObj"));
2412                            delete.addParam("uid", user.getUidString());
2413                            delete.addParam("keys", s.toString());
2414                            delete.addParam("loginController",
2415                                    loginControllerName);
2416                            block.add(delete);
2417                        }
2418                    } else {
2419                        if (oneRom.getField("AllowEdit").equals("Y")) {
2420                            list = new Transition("processListRecords", this);
2421                            list.addParam("uid", user.getUidString());
2422                            list.addParam("dbobj", oneRom.getField("RegObj"));
2423                            list.addParam("loginController", loginControllerName);
2424                            block.add(list);
2425                        }
2426                    }
2427                }
2428
2429                block.add(desc);
2430                block.add(recCount);
2431                block.add(recMin);
2432                block.add(recMax);
2433                response.addBlock(block);
2434            }
2435
2436            /* This isn't relevant any more I don't think... */
2437            /* Transition complete = new Transition("processComplete", this);
2438
2439
2440
2441            response.add(complete); */

2442        } catch (DBException e) {
2443            throw new ControllerException("Cannot process registration - database error",
2444                    e);
2445        }
2446    }
2447
2448    /**
2449     * Resend the validation email.
2450     *
2451     * @param request The ControllerRequest object handed down by the framework
2452     * for this request
2453     * @param response The ControllerResponse object returned by this
2454     * controller
2455     * @throws ControllerException upon error of processing this state.
2456     * @throws NonHandleableException upon fatal error
2457     */

2458    protected void runProcessRevalidateState(ControllerRequest request,
2459                                             ControllerResponse response)
2460            throws ControllerException, NonHandleableException {
2461        ErrorCollection ec = request.getErrorCollection();
2462        if (ec == null) {
2463            ec = new ErrorCollection();
2464        }
2465
2466        try {
2467            User user = new User();
2468            user.setDBName(request.getDataContext());
2469            user.setEmail(request.getParameter("Email"));
2470            if (!user.find()) {
2471                log.error("Received request for UserName: "
2472                        + request.getParameter("UserName") +
2473                        "but user does not exist");
2474
2475                ec.addError("You entered an invalid email address");
2476            }
2477
2478            if (ec.getErrorCount() > 0) {
2479                response.setFormCache();
2480                response.saveErrors(ec);
2481                transition("promptRevalidate", Class.forName(this.getLoginController(request)), request, response);
2482                return;
2483            }
2484
2485            RegistrationDomain rd = getRegDomain(request, user);
2486            processPostRegistration(request, response, user, rd, this.getLoginController(request));
2487
2488        } catch (DBException dbe) {
2489            throw new ControllerException("Database exception reading User", dbe);
2490        } catch (ClassNotFoundException JavaDoc ce) {
2491            throw new ControllerException("Login Controller class not found", ce);
2492        }
2493    }
2494}
2495
Popular Tags