KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jcorporate > expresso > services > validation > ValidationEntry


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 package com.jcorporate.expresso.services.validation;
66
67 import com.jcorporate.expresso.core.db.DBException;
68 import com.jcorporate.expresso.core.dbobj.SecuredDBObject;
69 import com.jcorporate.expresso.core.job.Job;
70 import com.jcorporate.expresso.core.job.ServerException;
71 import com.jcorporate.expresso.core.misc.ConfigManager;
72 import com.jcorporate.expresso.core.misc.CookieBase64;
73 import com.jcorporate.expresso.core.misc.DateTime;
74 import com.jcorporate.expresso.core.misc.EMailSender;
75 import com.jcorporate.expresso.core.misc.StringUtil;
76 import com.jcorporate.expresso.core.security.CryptoManager;
77 import com.jcorporate.expresso.core.security.User;
78 import com.jcorporate.expresso.kernel.exception.ChainedException;
79 import com.jcorporate.expresso.kernel.util.ClassLocator;
80 import com.jcorporate.expresso.kernel.util.FastStringBuffer;
81 import com.jcorporate.expresso.services.dbobj.JobQueue;
82 import com.jcorporate.expresso.services.dbobj.JobQueueParam;
83 import com.jcorporate.expresso.services.dbobj.Setup;
84 import com.jcorporate.expresso.services.dbobj.ValidationQueue;
85 import com.jcorporate.expresso.services.dbobj.ValidationQueueParam;
86 import org.apache.log4j.Logger;
87
88 import java.io.Serializable JavaDoc;
89 import java.util.Calendar JavaDoc;
90 import java.util.Date JavaDoc;
91 import java.util.Enumeration JavaDoc;
92 import java.util.Hashtable JavaDoc;
93 import java.util.Iterator JavaDoc;
94 import java.util.List JavaDoc;
95 import java.util.StringTokenizer JavaDoc;
96 import java.util.Vector JavaDoc;
97
98
99 /**
100  * This class abstracts the storing of the data that goes along with any
101  * particular validation operation. This class also provides functions for a
102  * validation request to be created in the first place. In this first
103  * incarnation, this class stores all the data using DBObjects. If warranted
104  * at a later time, the ideal way to change the functionality by making this
105  * class abstract and then implementing DBValidationEntry and
106  * XMLValidationEntry or whatever. Most of the methods in this class are
107  * "protected", so that minor changes can be handled by simply extending this
108  * class and overridining the necessary methods.
109  *
110  * @author Shash Chatterjee
111  * @version $Revision: 1.25 $ $Date: 2004/11/17 20:48:22 $
112  * @since Expresso 4.0
113  */

114 public class ValidationEntry implements Serializable JavaDoc {
115     /**
116      * Parameter for validator
117      */

118     public static final String JavaDoc PRM_VALIDATOR = "$$$Validator";
119
120     /**
121      * PArameter for 'Expires After'
122      */

123     public static final String JavaDoc PRM_EXPIRES_AFTER = "$$$ExpiresAfter";
124
125     /**
126      * Parameter for 'Validation Title'
127      */

128     public static final String JavaDoc PRM_VAL_TITLE = "$$$ValTitle";
129
130     /**
131      * Parameter for 'Validation Description'
132      */

133     public static final String JavaDoc PRM_VAL_DESC = "$$$ValDesc";
134
135     /**
136      * Parameter for 'Validation Server'
137      */

138     public static final String JavaDoc PRM_VAL_SERVER = "$$$ValDServer";
139
140     /**
141      * Parameter for 'Validation Port'
142      */

143     public static final String JavaDoc PRM_VAL_PORT = "$$$ValPort";
144
145     /**
146      * Parameter for 'Validation webapp context'
147      */

148     public static final String JavaDoc PRM_VAL_CTX = "$$$ValContext";
149
150     /**
151      * Status for new
152      */

153     public static final String JavaDoc NEW = "N";
154
155     /**
156      * Status for waiting
157      */

158     public static final String JavaDoc WAITING = "W";
159
160     /**
161      * Status for available
162      */

163     public static final String JavaDoc AVAILABLE = "A";
164
165     /**
166      * Status for Validated
167      */

168     public static final String JavaDoc VALIDATED = "V";
169
170     /**
171      * Status for Expired
172      */

173     public static final String JavaDoc EXPIRED = "E";
174
175     /**
176      * Session validation key
177      */

178     public static final String JavaDoc SESSION_KEY = "expresso.services.validation.ValidationEntry";
179
180     /**
181      * The log4j logger
182      */

183     private static Logger log = Logger.getLogger(ValidationEntry.class);
184
185     /**
186      * JobQueue
187      */

188     protected JobQueue jq = null;
189
190     /**
191      * JobQueue parameter data object
192      */

193     protected JobQueueParam jqp = null;
194
195     /**
196      * default data context
197      */

198     protected String JavaDoc dataContext = "default";
199
200     /**
201      * Time it expires after
202      */

203     protected String JavaDoc expiresAfter = "120:0:0"; // five days
204

205     /**
206      * The Job class name
207      */

208     protected String JavaDoc jobClassName = com.jcorporate.expresso.services.job.ValidationJob.class.getName();
209
210     /**
211      * The Job Number
212      */

213     protected String JavaDoc jobNumber = null;
214
215     /**
216      * The validation context path
217      */

218     protected String JavaDoc valContextPath = null;
219
220     /**
221      * The default description
222      */

223     protected String JavaDoc valDesc = "Validation Job";
224
225     /**
226      * The validation port
227      */

228     protected String JavaDoc valPort = null;
229
230     /**
231      * The validation server
232      */

233     protected String JavaDoc valServer = null;
234
235     /**
236      * The validation job title
237      */

238     protected String JavaDoc valTitle = "Validation Job";
239
240     /**
241      * ?
242      */

243     protected String JavaDoc valType = "default";
244
245     /**
246      * The validator class name
247      */

248     protected String JavaDoc validationClassName = null;
249
250     /**
251      * The validation queue
252      */

253     protected ValidationQueue vq = null;
254
255     /**
256      * current parameter number
257      */

258     protected int paramNum = 0;
259
260     /**
261      * This constructor is used by classes that submit a validation request
262      * into the system. It creates a Job Queue Entry for the validation
263      * request. Application specific parameters are added using the
264      * addParam(...) method, and the request finally committed using the
265      * submit(...) method. Creation date: (9/23/2001 9:41:06 PM) Author: Shash
266      * Chatterjee
267      *
268      * @param newDbName newDbName The database context to create the validation
269      * Job/Entry in.
270      */

271     public ValidationEntry(String JavaDoc newDbName) throws AuthValidationException {
272         super();
273
274         // What DB context to use?
275
if ((newDbName == null) || (newDbName.equals(""))) {
276             newDbName = "default";
277         }
278
279         dataContext = newDbName;
280
281         try {
282             int uid = User.getAdminId(newDbName);
283
284             // Create the job queue entry
285
jq = new JobQueue();
286             jq.setDataContext(dataContext);
287             jq.setField(JobQueue.FLD_UID, uid);
288             jq.setField(JobQueue.FLD_JOBCODE, jobClassName);
289             jq.setField(JobQueue.FLD_STATUS_CODE, "N");
290             jq.add();
291
292             // Store the job queue number for later use...
293
jobNumber = jq.getField("JobNumber");
294
295             // Create a job queue parameter instance for later use in addParam()
296
jqp = new JobQueueParam();
297             jqp.setDataContext(dataContext);
298         } catch (DBException dbe) {
299             throw new AuthValidationException("Database error creating job or parameters",
300                     dbe);
301         }
302
303         if (log.isDebugEnabled()) {
304             log.debug("New entry started with job number " + jobNumber);
305         }
306     }
307
308     /**
309      * This constructor is used, after a validation request comes in, to
310      * resurrect a validation entry from the DB. Creation date: (9/23/2001
311      * 9:41:06 PM) Author: Shash Chatterjee
312      *
313      * @param dbName dbName The DB context to retrieve the validation entry
314      * from
315      * @param id id The validation request id/seq. number
316      * @throws AuthValidationException AuthValidationException
317      */

318     public ValidationEntry(String JavaDoc dbName, String JavaDoc id)
319             throws AuthValidationException {
320         super();
321
322         try {
323             // Read back the validation entry from persistent storage
324
vq = new ValidationQueue(SecuredDBObject.SYSTEM_ACCOUNT);
325             vq.setDataContext(dbName);
326             vq.setField(ValidationQueue.FLD_ID, id);
327
328             if (!vq.find()) {
329                 throw new AuthValidationException("Validation queue id \"" +
330                         id + "\" not found in db \"" + dbName + "\"");
331             }
332         } catch (DBException dbe) {
333             throw new AuthValidationException("DB error", dbe);
334         }
335     }
336
337     /**
338      * This constructor is used by the validation job to create a validation
339      * entry from the job parameters. Application classes should have no need
340      * to use this class/ Creation date: (9/23/2001 9:41:06 PM) Author: Shash
341      * Chatterjee
342      *
343      * @param context context The DB context to use for the validation entry
344      * @param paramsVector paramsVector All the params passed in to the job
345      * @param jq jq The job queue entry in its entirety
346      * @throws AuthValidationException AuthValidationException
347      */

348     public ValidationEntry(String JavaDoc context, List JavaDoc paramsVector, JobQueue jq)
349             throws AuthValidationException {
350         super();
351
352         String JavaDoc id = null;
353
354         try {
355             // The time-delta for expiry is passed in as "hours:minutes:seconds"
356
// It is parsed here and then added on to the current time
357
String JavaDoc expiresAfter = jq.getParamValue(ValidationEntry.PRM_EXPIRES_AFTER);
358             Calendar JavaDoc now = Calendar.getInstance();
359             StringTokenizer JavaDoc stk = new StringTokenizer JavaDoc(expiresAfter, ":");
360             int hr = Integer.parseInt((String JavaDoc) stk.nextElement());
361             int mn = Integer.parseInt((String JavaDoc) stk.nextElement());
362             int sc = Integer.parseInt((String JavaDoc) stk.nextElement());
363             now.add(Calendar.HOUR, hr);
364             now.add(Calendar.MINUTE, mn);
365             now.add(Calendar.SECOND, sc);
366
367             // Create the server/port/context-path variables
368
valServer = jq.getParamValue(ValidationEntry.PRM_VAL_SERVER);
369             valPort = jq.getParamValue(ValidationEntry.PRM_VAL_PORT);
370             valContextPath = jq.getParamValue(ValidationEntry.PRM_VAL_CTX);
371
372             // Create the validation entry
373
vq = new ValidationQueue();
374             vq.setDataContext(context);
375             vq.setField(ValidationQueue.FLD_STATUS_CODE, "N"); //Mark it as "new", won't be used until marked as "available"
376
vq.setField(ValidationQueue.FLD_EXPIRES_AT,
377                     DateTime.getDateTimeForDB(now.getTime(), context));
378             vq.setField(ValidationQueue.FLD_VAL_CODE, createValidationCode()); // Here's where the validation code is calculated
379
vq.setField(ValidationQueue.FLD_VAL_HANDLER,
380                     jq.getParamValue(ValidationEntry.PRM_VALIDATOR));
381             vq.setField(ValidationQueue.FLD_PROCESSED_BY, "1");
382             vq.add();
383
384             // Store the id of the validation entry for later use
385
id = vq.getField(ValidationQueue.FLD_ID);
386
387             // Loop through the job parameters and add them as validation entry parameters
388
int paramNum = 0;
389             ValidationQueueParam vqp = new ValidationQueueParam();
390             vqp.setDataContext(context);
391
392             for (Iterator JavaDoc i = paramsVector.iterator(); i.hasNext();) {
393                 JobQueueParam jqp = (JobQueueParam) i.next();
394                 String JavaDoc key = jqp.getField("ParamCode");
395                 String JavaDoc val = jqp.getField("ParamValue");
396                 vqp.clear();
397                 vqp.setField(ValidationQueueParam.FLD_QUEUE_ID, id);
398                 vqp.setField(ValidationQueueParam.FLD_PARAM_NUM, Integer.toString(++paramNum));
399                 vqp.setField(ValidationQueueParam.FLD_PARAM_CODE, key);
400                 vqp.setField(ValidationQueueParam.FLD_PARAM_VAL, val);
401                 vqp.add();
402             }
403
404             // All done....mark the entry as "available"
405
vq.setField(ValidationQueue.FLD_STATUS_CODE, "A");
406             vq.update();
407         } catch (DBException dbe) {
408             throw new AuthValidationException("Database error storing validation entry",
409                     dbe);
410         }
411     }
412
413     /**
414      * This default constructor should never be used, and is marked private and
415      * protected with an exception just for that reason. Creation date:
416      * (9/23/2001 9:41:06 PM) Author: Shash Chatterjee
417      */

418     private ValidationEntry() throws AuthValidationException {
419         throw new AuthValidationException("Please do not use the default constructor");
420     }
421
422     /**
423      * @param path
424      */

425     public void setContextPath(String JavaDoc path) {
426         valContextPath = path;
427     }
428
429     /**
430      * Sets the description for the validation job Creation date: (9/23/2001
431      * 9:41:06 PM) Author: Shash Chatterjee
432      *
433      * @param desc desc The description
434      */

435     public void setDesc(String JavaDoc desc) {
436         valDesc = desc;
437     }
438
439     /**
440      * Method to retrieve the absolute date/time when the request expires.
441      * Creation date: (9/23/2001 9:41:06 PM) Author: Shash Chatterjee
442      *
443      * @return The expiry date/time
444      */

445     public Date JavaDoc getExpiresAt() throws AuthValidationException {
446         if (vq == null) {
447             throw new AuthValidationException("Use loadQueueEntry(...) method first");
448         }
449
450         try {
451             Date JavaDoc ex = vq.getFieldDate(ValidationQueue.FLD_EXPIRES_AT);
452
453             return ex;
454         } catch (DBException dbe) {
455             throw new AuthValidationException("DB error", dbe);
456         }
457     }
458
459     /**
460      * Sets the name of the job class for validation requests. Currently the
461      * only job that should be specified is ValidationJob Creation date:
462      * (9/23/2001 9:41:06 PM) Author: Shash Chatterjee
463      *
464      * @param name name Class name of validation job
465      * @throws AuthValidationException AuthValidationException if the class
466      * isn't an Expresso Job class
467      */

468     public void setJobClassName(String JavaDoc name) throws AuthValidationException {
469         try {
470             Job.instantiate(name);
471         } catch (ServerException se) {
472             throw new AuthValidationException("Class \"" + name +
473                     "\" is not an Expresso Job", se);
474         }
475
476         jobClassName = name;
477     }
478
479     /**
480      * Method to return all the application-specific parameters associated with
481      * this validation request Creation date: (9/23/2001 9:41:06 PM) Author:
482      * Shash Chatterjee
483      *
484      * @return Hashtable of all the parameters, keyed by parameter name
485      */

486     public Hashtable JavaDoc getParams() throws AuthValidationException {
487         if (vq == null) {
488             throw new AuthValidationException("Use loadQueueEntry(...) method first");
489         }
490
491         Hashtable JavaDoc params = new Hashtable JavaDoc(8);
492
493         try {
494             String JavaDoc id = vq.getField(ValidationQueue.FLD_ID);
495             ValidationQueueParam vqp = new ValidationQueueParam();
496             vqp.setField(ValidationQueueParam.FLD_QUEUE_ID, id);
497             vqp.setDataContext(dataContext);
498
499             for (Iterator JavaDoc i = vqp.searchAndRetrieveList().iterator();
500                  i.hasNext();) {
501                 ValidationQueueParam oneParam = (ValidationQueueParam) i.next();
502                 params.put(oneParam.getField(ValidationQueueParam.FLD_PARAM_CODE),
503                         oneParam.getField(ValidationQueueParam.FLD_PARAM_VAL));
504             }
505         } catch (DBException dbe) {
506             throw new AuthValidationException("DB error", dbe);
507         }
508
509         return params;
510     }
511
512     /**
513      * @param port
514      */

515     public void setPort(String JavaDoc port) {
516         valPort = port;
517     }
518
519     /**
520      * @param server
521      */

522     public void setServer(String JavaDoc server) {
523         valServer = server;
524     }
525
526     /**
527      * Sets the current status of the validation entry Creation date:
528      * (9/23/2001 9:41:06 PM) Author: Shash Chatterjee
529      *
530      * @param newStatus newStatus = "A"=available, "N"=new, "W"=waiting,
531      * "V"=validated, "E"=expired
532      * @throws AuthValidationException AuthValidationException
533      */

534     public void setStatus(String JavaDoc newStatus) throws AuthValidationException {
535         if (vq == null) {
536             throw new AuthValidationException("Use loadQueueEntry(...) method first");
537         }
538
539         try {
540             vq.setField(ValidationQueue.FLD_STATUS_CODE, newStatus);
541             vq.update();
542         } catch (DBException dbe) {
543             throw new AuthValidationException("DB error", dbe);
544         }
545     }
546
547     /**
548      * Returns the current status of the validation request Creation date:
549      * (9/23/2001 9:41:06 PM) Author: Shash Chatterjee
550      *
551      * @return "N","A","V","E" - for "new", "available", "validated", "expired"
552      * @throws AuthValidationException AuthValidationException
553      */

554     public String JavaDoc getStatus() throws AuthValidationException {
555         if (vq == null) {
556             throw new AuthValidationException("Use loadQueueEntry(...) method first");
557         }
558
559         try {
560             String JavaDoc status = vq.getField(ValidationQueue.FLD_STATUS_CODE);
561
562             return status;
563         } catch (DBException dbe) {
564             throw new AuthValidationException("DB error", dbe);
565         }
566     }
567
568     /**
569      * Set's the title of the validation entry job Creation date: (9/23/2001
570      * 9:41:06 PM) Author: Shash Chatterjee
571      *
572      * @param title title The title
573      */

574     public void setTitle(String JavaDoc title) {
575         valTitle = title;
576     }
577
578     /**
579      * Method to set the app-specific validation handler associated with this
580      * validation request Creation date: (9/23/2001 9:41:06 PM) Author: Shash
581      * Chatterjee
582      *
583      * @param className className Class name of a class that implements
584      * ValidationHandler interface
585      * @throws AuthValidationException AuthValidationException if the handler
586      * is not of the correct class, or if the instantiation fails
587      */

588     public void setValidationHandler(String JavaDoc className)
589             throws AuthValidationException {
590         StringUtil.assertNotBlank(className,
591                 "ValidationHandler class name " + " may not be blank or null here");
592
593         try {
594             Class JavaDoc c = ClassLocator.loadClass(className);
595             c.newInstance();
596         } catch (ClassNotFoundException JavaDoc cn) {
597             throw new AuthValidationException("ValidationHandler object '" +
598                     className + "' not found", cn);
599         } catch (InstantiationException JavaDoc ie) {
600             throw new AuthValidationException("ValidationHandler object '" +
601                     className + "' cannot be instantiated", ie);
602         } catch (IllegalAccessException JavaDoc iae) {
603             throw new AuthValidationException("Illegal access loading " +
604                     "ValidationHandler object '" + className + "'", iae);
605         }
606
607         validationClassName = className;
608     }
609
610
611     /**
612      * Method to set the app-specific validation handler associated with this
613      * validation request
614      *
615      * @param clazz Class that implements
616      * ValidationHandler interface
617      * @throws AuthValidationException AuthValidationException if the handler
618      * is not of the correct class, or if the instantiation fails
619      */

620     public void setValidationHandler(Class JavaDoc clazz) throws AuthValidationException {
621         try {
622             clazz.newInstance();
623         } catch (IllegalAccessException JavaDoc ex) {
624             throw new AuthValidationException("Illegal access loading " +
625                     "ValidationHandler object '" + clazz.getName() + "'", ex);
626         } catch (InstantiationException JavaDoc ex) {
627             throw new AuthValidationException("ValidationHandler object '" +
628                     clazz.getName() + "' cannot be instantiated", ex);
629         }
630
631         validationClassName = clazz.getName();
632     }
633
634
635     /**
636      * Adds an application specific parameter into the validation entry
637      * Creation date: (9/23/2001 9:41:06 PM) Author: Shash Chatterjee
638      *
639      * @param name name Name of the parameter
640      * @param value value Value of the parameter
641      */

642     public void addParam(String JavaDoc name, String JavaDoc value)
643             throws AuthValidationException {
644         try {
645
646             jqp.clear();
647             jqp.setField("JobNumber", jobNumber);
648             paramNum++;
649             jqp.setField("ParamNumber", Integer.toString(paramNum));
650             jqp.setField("ParamCode", name);
651             jqp.setField("ParamValue", value);
652             jqp.add();
653         } catch (DBException dbe) {
654             throw new AuthValidationException("Database error adding job parameter",
655                     dbe);
656         }
657
658         if (log.isDebugEnabled()) {
659             log.debug("Job id= " + jobNumber + ": Adding param name=" + name +
660                     " value=" + value);
661         }
662     }
663
664     /**
665      * Function to match the code in the DB versus the code in the request.
666      * Creation date: (9/23/2001 9:41:06 PM) Author: Shash Chatterjee
667      *
668      * @param code code Code in the request URL
669      * @return true if code matches, false otherwise
670      * @throws AuthValidationException AuthValidationException
671      */

672     public boolean codeMatches(String JavaDoc code) throws AuthValidationException {
673         try {
674             String JavaDoc storedCode = vq.getField(ValidationQueue.FLD_VAL_CODE);
675
676             if (storedCode.equals(code)) {
677                 return true;
678             } else {
679                 return false;
680             }
681         } catch (DBException dbe) {
682             throw new AuthValidationException("DB error", dbe);
683         }
684     }
685
686     /**
687      * Deletes the validation entry and all the connected parameters
688      *
689      * @throws AuthValidationException if no record is loaded OR there's an
690      * error deleting the records.
691      */

692     public void delete() throws AuthValidationException {
693         if (vq == null) {
694             throw new AuthValidationException("Use loadQueueEntry(...) method first");
695         }
696
697         try {
698             vq.delete(true);
699             vq = null;
700         } catch (DBException dbe) {
701             throw new AuthValidationException("DB error", dbe);
702         }
703     }
704
705     /**
706      * Method to set the time delta from current time when the request will
707      * expire if unused Creation date: (9/23/2001 9:41:06 PM) Author: Shash
708      * Chatterjee
709      *
710      * @param hr hr Delta hours
711      * @param min min Delta minutes
712      * @param sec sec Delta seconds
713      */

714     public void expiresAfter(int hr, int min, int sec) {
715         FastStringBuffer fsb = FastStringBuffer.getInstance();
716
717         try {
718             fsb.append(hr);
719             fsb.append(":");
720             fsb.append(min);
721             fsb.append(":");
722             fsb.append(sec);
723
724             //Stored internally as "hours:minutes:seconds"
725
expiresAfter = fsb.toString();
726         } finally {
727             fsb.release();
728             fsb = null;
729         }
730     }
731
732     /**
733      * Utility function to instantiate the app-specific validation handler
734      * Creation date: (9/23/2001 9:41:06 PM) Author: Shash Chatterjee
735      *
736      * @return Object of class ValidationHandler
737      * @throws AuthValidationException AuthValidationException
738      */

739     public ValidationHandler instantiateHandler()
740             throws AuthValidationException {
741         ValidationHandler vh = null;
742         String JavaDoc className = null;
743
744         try {
745             className = vq.getField(ValidationQueue.FLD_VAL_HANDLER);
746         } catch (DBException dbe) {
747             throw new AuthValidationException("DB error", dbe);
748         }
749
750         StringUtil.assertNotBlank(className,
751                 "ValidationHandler class name " + " may not be blank or null here");
752
753         try {
754             Class JavaDoc c = ClassLocator.loadClass(className);
755             vh = (ValidationHandler) c.newInstance();
756         } catch (ClassNotFoundException JavaDoc cn) {
757             throw new AuthValidationException("ValidationHandler object '" +
758                     className + "' not found", cn);
759         } catch (InstantiationException JavaDoc ie) {
760             throw new AuthValidationException("ValidationHandler object '" +
761                     className + "' cannot be instantiated", ie);
762         } catch (IllegalAccessException JavaDoc iae) {
763             throw new AuthValidationException("llegal access loading " +
764                     "ValidationHandler object '" + className + "'", iae);
765         }
766
767         return vh;
768     }
769
770     /**
771      * Insert the method's description here. Creation date: (9/23/2001 9:41:06
772      * PM) Author: Shash Chatterjee
773      *
774      * @param dbName The data context to use
775      * @param from the &quot;From&quot; email field.
776      * @param addresses the email addresses to notify
777      * @param subject the subject of the email
778      * @param content The body of the email message
779      */

780     public static void notifyByEmail(String JavaDoc dbName, String JavaDoc from,
781                                      Vector JavaDoc addresses, String JavaDoc subject, String JavaDoc content)
782             throws AuthValidationException {
783         EMailSender ems = new EMailSender();
784         ems.setFromAddress(from);
785         ems.setDBName(dbName);
786
787         for (Enumeration JavaDoc e = addresses.elements(); e.hasMoreElements();) {
788             String JavaDoc oneAddr = (String JavaDoc) e.nextElement();
789
790             try {
791                 ems.send(oneAddr, subject, content);
792             } catch (Exception JavaDoc exc) {
793                 throw new AuthValidationException("Email error sending to \"" +
794                         oneAddr + "\"", exc);
795             }
796         }
797     }
798
799     /**
800      * Insert the method's description here. Creation date: (9/23/2001 9:41:06
801      * PM) Author: Shash Chatterjee
802      *
803      * @throws AuthValidationException upon error
804      */

805     public void submit() throws AuthValidationException {
806         try {
807             if ((valServer == null) || valServer.equals("")) {
808                 valServer = Setup.getValue(dataContext, "HTTPServ");
809             }
810
811             if ((valPort == null) || valPort.equals("")) {
812                 valPort = Setup.getValue(dataContext, "ServletPort");
813             }
814
815             if ((valContextPath == null) || valContextPath.equals("")) {
816                 valContextPath = Setup.getValue(dataContext, "ContextPath");
817             }
818
819             addParam(PRM_VALIDATOR, validationClassName);
820             addParam(PRM_EXPIRES_AFTER, expiresAfter);
821             addParam(PRM_VAL_TITLE, valTitle);
822             addParam(PRM_VAL_DESC, valDesc);
823             addParam(PRM_VAL_SERVER, valServer);
824             addParam(PRM_VAL_PORT, valPort);
825             addParam(PRM_VAL_CTX, valContextPath);
826             jq.setField(JobQueue.FLD_STATUS_CODE, AVAILABLE);
827             jq.update();
828         } catch (DBException dbe) {
829             throw new AuthValidationException("Database error updating job status to active",
830                     dbe);
831         }
832     }
833
834     /**
835      * Utility function to create a URL based on the webapp context, and setup
836      * values such as the http server/port etc. It tags on the db context,
837      * the validation entry id and the validation code as request parameters.
838      * Creation date: (9/23/2001 9:41:06 PM) Author: Shash Chatterjee
839      *
840      * @return The URL for use by the validator to approve the validation
841      * request
842      * @throws AuthValidationException upon error
843      */

844     public String JavaDoc validationURL() throws AuthValidationException {
845         FastStringBuffer authURL = FastStringBuffer.getInstance();
846         String JavaDoc returnValue = null;
847
848         try {
849             try {
850                 String JavaDoc db = vq.getDataContext();
851                 if (valPort.equals(ConfigManager.getConfig().getSslPort())) {
852                     authURL.append("https://");
853                 } else {
854                     authURL.append("http://");
855                 }
856                 authURL.append(valServer);
857                 authURL.append(":" + valPort);
858                 authURL.append(valContextPath);
859                 authURL.append("/Validate.do?");
860                 authURL.append("ctx=" + db);
861                 authURL.append("&id=" + vq.getField(ValidationQueue.FLD_ID));
862                 authURL.append("&code=" + vq.getField(ValidationQueue.FLD_VAL_CODE));
863             } catch (DBException dbe) {
864                 throw new AuthValidationException("DB error", dbe);
865             }
866
867             returnValue = authURL.toString();
868         } finally {
869             authURL.release();
870         }
871
872         return returnValue;
873     }
874
875     /**
876      * Create a cryptographically sound validation code for use in the
877      * validation operation [Currently generates a 256-bit random number]
878      * Creation date: (9/23/2001 9:41:06 PM) Author: Shash Chatterjee,
879      * strengthened by Mike Rimov
880      *
881      * @return The validation code
882      */

883     protected static String JavaDoc createValidationCode() {
884         final int length = 256 / 8; //256 Bit random number
885

886         byte[] possibleNumbers;
887
888         try {
889             possibleNumbers = CryptoManager.getInstance().getRandomGenerator()
890                     .getRandomBytes(length);
891         } catch (ChainedException e) {
892             possibleNumbers = new byte[length];
893
894             //If an error occurs, just fill it with Math.random() after logging the
895
//exception.
896
Logger.getLogger("com.jcorporate.expresso.core.security.").error("Create Validation Code",
897                     e);
898
899             for (int i = 0; i < length; i++) {
900                 possibleNumbers[i] = (byte) (Math.random() * 256);
901             }
902         }
903
904         return CookieBase64.encodeNoPadding(possibleNumbers);
905     }
906 }
907
Popular Tags