KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > j2ee > sun > validation > ValidationManager


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.j2ee.sun.validation;
21
22 import java.io.File JavaDoc;
23 import java.io.FileInputStream JavaDoc;
24 import java.io.FileNotFoundException JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.io.InputStream JavaDoc;
27 import java.lang.reflect.Constructor JavaDoc;
28 import java.lang.reflect.Method JavaDoc;
29 import java.net.URL JavaDoc;
30 import java.text.MessageFormat JavaDoc;
31 import java.util.ArrayList JavaDoc;
32 import java.util.Collection JavaDoc;
33 import java.util.HashMap JavaDoc;
34
35 import org.netbeans.modules.schema2beans.BaseBean;
36
37 import org.netbeans.modules.j2ee.sun.validation.Constants;
38 import org.netbeans.modules.j2ee.sun.validation.constraints.CardinalConstraint;
39 import org.netbeans.modules.j2ee.sun.validation.constraints.Constraint;
40 import org.netbeans.modules.j2ee.sun.validation.constraints.data.Argument;
41 import org.netbeans.modules.j2ee.sun.validation.constraints.data.Arguments;
42 import org.netbeans.modules.j2ee.sun.validation.constraints.data.CheckInfo;
43 import org.netbeans.modules.j2ee.sun.validation.constraints.data.Constraints;
44 import org.netbeans.modules.j2ee.sun.validation.data.Check;
45 import org.netbeans.modules.j2ee.sun.validation.data.Element;
46 import org.netbeans.modules.j2ee.sun.validation.data.Validation;
47 import org.netbeans.modules.j2ee.sun.validation.data.Parameter;
48 import org.netbeans.modules.j2ee.sun.validation.data.Parameters;
49 import org.netbeans.modules.j2ee.sun.validation.util.BundleReader;
50 import org.netbeans.modules.j2ee.sun.validation.util.ObjectFactory;
51 import org.netbeans.modules.j2ee.sun.validation.util.Utils;
52
53
54 /**
55  * {@link ValidationManager} is an object that provides Validation functionality,
56  * through its <code>validate( )</code> function.
57  * <code>{@link ValidationManagerFactory}</code> creates
58  * <code>{@link ValidationManager}</code> based on the Validation File.
59  * Validation File specifies Validation rules i.e.
60  * which Constraints to apply to which elements. Objects are validated by
61  * applying specified Constraints to its elements. Validation file is xml file
62  * based on <code>validation.dtd</code>. If no Validation File is specified,
63  * <code>ValidationManagerFactory</code> returns default
64  * <code>ValidationManager</code>. Default <code>ValidationManager</code> is
65  * based on default Validation File. Default Validation File defines Constraints
66  * for 8.0 Sun DTDs.
67  * <p>
68  * Validations are performed, recursively on the given Object.
69  * Two types of Validations are perfomed, Structural validations and Specified
70  * validations. Structural validations are expressed through
71  * <code>{@link CardinalConstraint}</code>. <code>CardinalConstraint</code> is
72  * an implicit Constraint. Its always applied to each of the element; you dont
73  * need to specify it explicitly. Whereas , other Constaints need to be
74  * explicitly specified for each element you wanted to apply it to.
75  * Constraints to be applied are specified through Validation File.
76  * You can also define, your own custom <code>Constraint</code>s and apply them
77  * to any elements. When you define your own <code>Constraint</code>s, you
78  * need to provide information about them to the framework. This information is
79  * provided through Constraints File. Constraints File is xml file, based on
80  * <code>constraints.dtd</code>. Constraints File to use is specified through
81  * system property <code>constraints.file</code>. You can override
82  * <code>Constraint</code>s provided by framework , by providing your own.
83  *
84  * @see Constraint
85  * @see CardinalConstraint
86  * @see Validatee
87  * @see ValidationManagerFactory
88  *
89  * @author Rajeshwar Patil
90  * @version %I%, %G%
91  */

92 public class ValidationManager {
93     /*
94     ValidationManager is an object that constructs Validator objects for all
95     the Validatees. ValidationManager maintains a map of xpaths to Validators.
96     It constructs this by reading Validation File. Validation File specifies
97     Constraints to be applied to the elements.
98     Every Validatee has a corresponding Validator object and this object
99     knows how to validate its Validatee. Validator maintains a list of
100     Constraints that needs to be applied for each of the element of its
101     Validatee. Constraint objects are built using files, Constraints File
102     and Validation File.
103     */

104
105     /**
106      * A prefix used to construct the getter method name of the bean.
107      */

108     private static String JavaDoc GET_PREFIX = "get"; //NOI18N
109

110
111     /**
112      * A prefix used to construct the setter method name of the bean.
113      */

114     private static String JavaDoc SET_PREFIX = "set"; //NOI18N
115

116
117     /**
118      * A prefix used to construct the size method name of the bean.
119      */

120     private static String JavaDoc SIZE_PREFIX = "size"; //NOI18N
121

122
123     /**
124      * A file that is used specify infromation for the constraints provided
125      * by this framework. <code>Constraint</code> objects are built using the
126      * information in this file.
127      */

128     private static final String JavaDoc defaultConstraintsFile =
129         "org/netbeans/modules/j2ee/sun/validation/constraints/" + //NOI18N
130
"constraints.xml"; //NOI18N
131

132     
133     /**
134      * A Cardinal Constraint class name.
135      */

136     private static final String JavaDoc CARDINAL_CONSTRAINT_CLASS =
137         "org.netbeans.modules.j2ee.sun.validation.constraints." + //NOI18N
138
"CardinalConstraint"; //NOI18N
139

140
141     /**
142      * A file that is used to specify <code>Constraints<code> to be
143      * applied to various elements. xpaths are used to specify elements.
144      * While constructing this object, clients of this framework can specify
145      * their own file by providing the file name to the appropriate
146      * constructor. If client do not, then the default file( specified by
147      * <code>defaultValidationFile</code> ) is used.
148      */

149     private String JavaDoc validationFile = null;
150
151     
152     /**
153      * A default Validation file that specify <code>Constraints<code> to be
154      * applied to various elements. xpaths are used to specify elements.
155      * This file is used by framework if client do not specify one.
156      * This file contains default validation rules.
157      */

158     private String JavaDoc defaultValidationFile =
159            "org/netbeans/modules/j2ee/sun/validation/validation.xml"; //NOI18N
160

161     
162     /**
163      * A map that stores for each <code>Validatee</code> object, the xpath and
164      * the corresponding <code>Validator</code> object.
165      */

166     private HashMap JavaDoc xpathToValidator = null;
167
168
169     /**
170      * A root bean representing validation.xml
171      */

172     private Validation validation = null;
173
174
175     /**
176      * A root bean representing constaints.xml
177      */

178     private Constraints constraints = null;
179
180     
181     /**
182      * An object providing utilities
183      */

184     private Utils utils = null;
185
186     
187     /** Creates a new instance of <code>ValidationManager</code> */
188     public ValidationManager() {
189         utils = new Utils();
190     }
191
192
193     /** Creates a new instance of <code>ValidationManager</code> */
194     public ValidationManager(String JavaDoc validationFile) {
195         if(null != validationFile){
196             this.validationFile = validationFile;
197         }
198         
199         utils = new Utils();
200     }
201
202     
203     /**
204      * Validates the given <code>Object</code>.
205      * Validatee Implementation for the given <code>object</code> must be
206      * provided. Validatee Implementation of an object is a
207      * <code>Validatee</code> wrapper around it. Validatee Implementation
208      * of an object is specified to framework through an Implementation File.
209      * Implementation File is a <code>.properties</code> file, with name-value
210      * pair entries in it. An entry in Implementation File specifies the object
211      * name and the corresponding Validatee Implementation.
212      * Implementation File to use, is specified to framework through system
213      * property <code>impl.file</code>
214      *
215      * @param object the object to be validated
216      *
217      * @return <code>Collection</code> the Collection of
218      * <code>ConstraintFailure</code> Objects. Collection is empty
219      * if there are no failures.
220      */

221     public Collection JavaDoc validate(Object JavaDoc object){
222         //This method get called in case of Objects that are not Validatee.
223
//This method, essentially, gets the Object's Validatee Implementation
224
//and uses it instead.
225

226         Collection JavaDoc collection = new ArrayList JavaDoc();
227
228         if(object != null){
229             boolean validateeImplFound = false;
230             String JavaDoc validateeImpl = null;
231
232             String JavaDoc implFile =
233                 System.getProperty("impl.file"); //NOI18N
234
///System.out.println(implFile);
235

236             //User specified impl file overrides the default imple file
237
//default impl file -- Constants.IMPL_FILE
238
if(implFile != null){
239                 validateeImpl = getValidateeImplementation(object, implFile);
240             }
241
242             //Using default impl file; user specified not available
243
if(validateeImpl == null){
244                 validateeImpl =
245                     getValidateeImplementation(object, Constants.IMPL_FILE);
246             }
247
248             //switch the BundleReader back to read from bundle file
249
BundleReader.setBundle(Constants.BUNDLE_FILE);
250
251             if(validateeImpl != null){
252                 Validatee validatee =
253                     (Validatee)ObjectFactory.newInstance(validateeImpl, object);
254                 if(validatee != null){
255                     collection = validate(validatee);
256                 }
257             } else {
258                 Class JavaDoc classObject = utils.getClass(object);
259                 String JavaDoc className = classObject.getName();
260
261                 String JavaDoc format = BundleReader.getValue(
262                     "MSG_given_object_is_not_validatee"); //NOI18N
263
Object JavaDoc[] arguments = new Object JavaDoc[]{className};
264                 System.out.println(MessageFormat.format(format, arguments));
265             }
266
267         }
268         return collection;
269    }
270
271
272     /**
273      * Validates the given <code>Validatee</code>.
274      *
275      * @param validatee the object to be validated
276      *
277      * @return <code>Collection</code> the Collection of
278      * <code>ConstraintFailure</code> Objects. Collection is empty
279      * if there are no failures.
280      */

281     public Collection JavaDoc validate(Validatee validatee){
282         //This method applies Cardinal constraint and Custom constraints defined
283
//for each of the elements of the validatee. It recurses for elements
284
//that are objects.
285
ArrayList JavaDoc failures = new ArrayList JavaDoc();
286         if(validatee != null){
287             String JavaDoc xpath = validatee.getXPath();
288
289             ArrayList JavaDoc elementNames = validatee.getElementNames();
290             ArrayList JavaDoc elementDtdNames = validatee.getElementDtdNames();
291             int noOfElements = elementNames.size();
292             String JavaDoc elementName = null;
293             String JavaDoc elementDtdName = null;
294             int count = 0;
295
296             for(int i=0; i<noOfElements; i++){
297                 elementName = (String JavaDoc)elementNames.get(i);
298                 elementDtdName = (String JavaDoc)elementDtdNames.get(i);
299
300                 //apply Cardinal Constraint
301
failures.addAll(validateCardinalConstraint(validatee, elementName,
302                         elementDtdName));
303
304                 //apply Other Constraints
305
boolean isBean = validatee.isBeanElement(elementName);
306                 if(isBean){
307                     //Recurse if an Object
308
failures.addAll(recurse(elementName, validatee));
309                 } else {
310                     Validator validator = getValidator(xpath);
311                     if(null != validator){
312                         failures.addAll(validator.validate(elementName,
313                                 elementDtdName, validatee));
314                     } else {
315                         ///String format = BundleReader.getValue(
316
/// "MSG_No_definition_for"); //NOI18N
317
///Object[] arguments =
318
/// new Object[]{"Validator", xpath}; //NOI18N
319
///System.out.println(
320
/// MessageFormat.format(format, arguments));
321
}
322                 }
323            }
324        }
325        return failures;
326     }
327
328
329     /**
330      * Validates the given Element.
331      *
332      * @param property the Element to be validated
333      * @param absoluteDtdName the complete dtd name of <code>property</code>
334      * @param fieldName the name of the GUI field, associated
335      * with <code>property</code>
336      *
337      * @return <code>Collection</code> the Collection of
338      * <code>ConstraintFailure</code> Objects. Collection is empty
339      * if there are no failures.
340      */

341     public Collection JavaDoc validateIndividualProperty(String JavaDoc property,
342             String JavaDoc absoluteDtdName, String JavaDoc fieldName){
343         ArrayList JavaDoc failures = new ArrayList JavaDoc();
344
345         String JavaDoc xpath = utils.getParentName(absoluteDtdName,
346                 Constants.XPATH_DELIMITER_CHAR);
347         Validator validator = getValidator(xpath);
348         if(null != validator){
349             failures.addAll(validator.validateIndividualProperty(
350                 property, absoluteDtdName, fieldName));
351         } else {
352             ///String format = BundleReader.getValue(
353
/// "MSG_No_definition_for"); //NOI18N
354
///Object[] arguments =
355
/// new Object[]{"Validator", xpath}; //NOI18N
356
///System.out.println(
357
/// MessageFormat.format(format, arguments));
358
}
359
360         return failures;
361     }
362
363
364     /**
365      * Recurses by calling the appropriate methods.
366      * This method is called when the given element to be validated is
367      * an object itself(<code>Validatee</code>).
368      *
369      * @param elementName the given element to be validated
370      * @param validatee the given <code>Validatee</code> object; the
371      * element of which needs to be validated
372      *
373      * @return <code>Collection</code> the Collection of
374      * <code>ConstraintFailure</code> Objects. Collection is empty
375      * if there are no failures.
376      */

377     private Collection JavaDoc recurse(String JavaDoc elementName, Validatee validatee){
378         ArrayList JavaDoc failures = new ArrayList JavaDoc();
379         boolean isIndexed = validatee.isIndexed(elementName);
380
381         if(isIndexed){
382             failures.addAll(validateBeans(elementName, validatee));
383         } else {
384             failures.addAll(validateBean(elementName, validatee));
385         }
386         return failures;
387     }
388
389
390     /**
391      * Validates the given element of given <code>Validatee</code>
392      * for Cardinality.This method is called for each and every
393      * element of the Validatee. You does not need to define Cardinal
394      * cosntraints in Validation File. Cardinal constraint is implicity
395      * applied to each and every element.
396      *
397      * @param elementName the given element to be validated
398      * @param elementDtdName the dtd name of the given element
399      * @param validatee the given <code>Validatee</code> object; the
400      * element which needs to be validated
401      *
402      * @return <code>Collection</code> the Collection of
403      * <code>ConstraintFailure</code> Objects. Collection is empty
404      * if there are no failures.
405      */

406     private Collection JavaDoc validateCardinalConstraint(Validatee validatee,
407             String JavaDoc elementName, String JavaDoc elementDtdName){
408         ArrayList JavaDoc failures = new ArrayList JavaDoc();
409         int cardinal = validatee.getElementCardinal(elementName);
410         CardinalConstraint constraint = getCardinalConstraint(cardinal);
411
412         switch(cardinal){
413             case Constants.MANDATORY_ARRAY :
414             case Constants.OPTIONAL_ARRAY: {
415                 Object JavaDoc[] elements =
416                     (Object JavaDoc [])validatee.getElements(elementName);
417                 String JavaDoc name = validatee.getIndexedXPath() +
418                     Constants.XPATH_DELIMITER + elementDtdName;
419                 ///String name = validatee.getXPath() +
420
///Constants.XPATH_DELIMITER + elementDtdName;
421
failures.addAll(constraint.match(elements, name));
422                 break;
423             }
424             case Constants.OPTIONAL_ELEMENT : {
425                 Object JavaDoc element = validatee.getElement(elementName);
426                 break;
427             }
428             case Constants.MANDATORY_ELEMENT :
429             default : {
430                 Object JavaDoc element = validatee.getElement(elementName);
431                 String JavaDoc name = validatee.getIndexedXPath() +
432                     Constants.XPATH_DELIMITER + elementDtdName;
433                 ///String name = validatee.getXPath() +
434
///Constants.XPATH_DELIMITER + elementDtdName;
435
failures.addAll(constraint.match(element, name));
436             }
437             break;
438         }
439         return failures;
440     }
441
442
443     /**
444      * Returns the <code>Validator</code> for the given xpath.
445      * Returns <code>null</code> if there is no <code>Validator</code>
446      * object for the given xpath.
447      * <code>ValidationManager</code> constructs the <code>Validator</code>
448      * objects for xpaths using Validation File and Constraints File.
449      *
450      * @param xpath the given xpath.
451      *
452      * @return <code>Validator</code> the Corresponding validator object,if any.
453      */

454     private Validator getValidator(String JavaDoc xpath){
455         Validator validator = null;
456         if(null == xpathToValidator){
457             constructXpathToValidator();
458         }
459         if(null != xpathToValidator) {
460             validator = (Validator)xpathToValidator.get(xpath);
461         }
462         return validator;
463     }
464
465
466     /**
467      * Constructs the xpath to <code>Validator</code> map.
468      * Uses Validation File and Constraints File to build the map.
469      */

470     private void constructXpathToValidator(){
471         //read validation file and construct xPathToValidator Map
472

473         if(null == validation){
474             constructValidation();
475         }
476
477         if(null == validation){
478             String JavaDoc format =
479                 BundleReader.getValue("Warning_Not_available"); //NOI18N
480
Object JavaDoc[] arguments = new Object JavaDoc[]{"Validation Data"}; //NOI18N
481
System.out.println(MessageFormat.format(format, arguments));
482             return;
483         }
484
485
486         xpathToValidator = new HashMap JavaDoc();
487         int noOfElements = validation.sizeElement();
488         Element element = null;
489         Validator validator = null;
490     String JavaDoc elementName = null;
491     String JavaDoc beanName = null;
492         Check check = null;
493         String JavaDoc checkName = null;
494
495         for(int i=0; i<noOfElements; i++) {
496             element = validation.getElement(i);
497             elementName = utils.getName(element.getName(),
498                 Constants.XPATH_DELIMITER_CHAR);
499             beanName = utils.getParentName(element.getName(),
500                 Constants.XPATH_DELIMITER_CHAR);
501             validator = (Validator) xpathToValidator.get(beanName);
502             ///String format =
503
/// BundleReader.getValue("Name_Value_Pair_Format"); //NOI18N
504
///Object[] arguments;
505
if(null == validator) {
506                 validator = new Validator();
507                 xpathToValidator.put(beanName, validator);
508                 ///format =
509
/// BundleReader.getValue("Name_Value_Pair_Format"); //NOI18N
510
///arguments =
511
/// new Object[]{"Bean Name", beanName}; //NOI18N
512
///System.out.println(MessageFormat.format(format, arguments));
513
///arguments = new Object[]{"Validator", validator}; //NOI18N
514
///System.out.println(MessageFormat.format(format, arguments));
515
}
516
517             int noOfChecks = element.sizeCheck();
518             Constraint constraint = null;
519             for(int j=0; j<noOfChecks; j++){
520                 check = element.getCheck(j);
521                 constraint = getConstraint(check);
522                 if(null != constraint){
523                     validator.addElementConstraint(elementName, constraint);
524                     ///arguments =
525
/// new Object[]{"Element Name", elementName}; //NOI18N
526
///System.out.println(MessageFormat.format(format, arguments));
527
///arguments = new Object[]{"Check", check.getName()}; //NOI18N
528
///System.out.println(MessageFormat.format(format, arguments));
529
///arguments = new Object[]{"Constraint", constraint}; //NOI18N
530
///System.out.println(MessageFormat.format(format, arguments));
531
///constraint.print();
532
}
533             }
534         }
535     }
536
537
538     /**
539      * Constructs <code>Validation</code> object, representing the root of
540      * xml defining <code>Constraints</code> to be applied to different
541      * elements.
542      * Clients of this framework can specify their own file.
543      * If client do not, then the default file( specified by
544      * <code>defaultValidationFile</code> ) is used.
545      */

546     private void constructValidation() {
547         //Create an InpurtStream object
548

549         URL JavaDoc url = null;
550         InputStream JavaDoc inputStream = null;
551
552         if(validationFile != null){
553             inputStream = getInputStream(validationFile);
554             if(inputStream == null){
555                 String JavaDoc format =
556                     BundleReader.getValue("MSG_using_the_default_file");//NOI18N
557
Object JavaDoc[] arguments = new Object JavaDoc[]{defaultValidationFile};
558                 System.out.println(MessageFormat.format(format, arguments));
559
560                 inputStream = getDafaultStream();
561             }
562         } else {
563             inputStream = getDafaultStream();
564         }
565         
566         if(inputStream != null){
567             //Create graph
568
try {
569                 validation = Validation.createGraph(inputStream);
570             } catch(Exception JavaDoc e) {
571                 System.out.println(e.getMessage());
572                 validation = null;
573             }
574         }
575     }
576
577
578     /**
579      * Constructs <code>Constraint</code> object, for the given
580      * <code>check</code>. <code>check</code> object represents the
581      * information of the constraint declared in Constraints File.
582      * <code>Constraints</code> to be applied to different elements are
583      * declared in Validation File. This method uses Constraints File to
584      * construct Constraint object from the given <code>check</code> object.
585      *
586      * @param check the given <code>Check</code> object
587      *
588      * @return <code>Constraint</code> the corresponding <code>Constraint</code>
589      * object. Returns <code>null</code> in case no information for this
590      * constaint is specified in Constraints File or if Constraints File is not
591      * found/defined.
592      */

593     private Constraint getConstraint(Check check){
594         Constraint constraint = null;
595         if(null == constraints) {
596             constructConstraints();
597         }
598         CheckInfo checkInfo = null;
599         if(null != constraints){
600             String JavaDoc checkName = check.getName();
601             checkInfo = getCheckInfo(checkName, constraints);
602             if(null != checkInfo){
603                 constraint = buildConstraint(check, checkInfo);
604             } else {
605                 String JavaDoc format =
606                     BundleReader.getValue("MSG_No_definition_for"); //NOI18N
607
Object JavaDoc[] arguments =
608                     new Object JavaDoc[]{"CheckInfo", checkName}; //NOI18N
609
System.out.println(MessageFormat.format(format, arguments));
610             }
611         } else {
612             String JavaDoc format =
613                 BundleReader.getValue("MSG_Not_defined"); //NOI18N
614
Object JavaDoc[] arguments = new Object JavaDoc[]{"Constraints"}; //NOI18N
615
System.out.println(MessageFormat.format(format, arguments));
616         }
617         return constraint;
618     }
619
620
621     /**
622      * Constructs <code>Constraints</code> object, representing the root of
623      * Constraints File. Constraints File provide information about the
624      * <code>Constraint</code>s i.e. Constraint class name, Constraint
625      * constructor arguments & thier types.
626      */

627     private void constructConstraints() {
628         Constraints customConstraints = null;
629         Constraints defaultConstraints = null;
630         
631         String JavaDoc constraintsFile =
632             System.getProperty("constraints.file"); //NOI18N
633
///System.out.println(consFile);
634
if(constraintsFile != null){
635             customConstraints = getConstraints(constraintsFile);
636         }
637         
638         if(defaultConstraintsFile != null){
639             defaultConstraints = getConstraints(defaultConstraintsFile);
640         }
641         
642         if(customConstraints != null){
643             if(defaultConstraints != null){
644                 int count = defaultConstraints.sizeCheckInfo();
645                 CheckInfo checkInfo = null;
646                 CheckInfo checkInfoClone = null;
647                 for(int i=0; i<count; i++){
648                     checkInfo = defaultConstraints.getCheckInfo(i);
649                     ///String str = checkInfo.dumpBeanNode();
650
checkInfoClone = (CheckInfo) checkInfo.clone();
651                     ///System.out.println(checkInfoClone.dumpBeanNode());
652
customConstraints.addCheckInfo(checkInfoClone);
653                 }
654                 constraints = customConstraints;
655             } else {
656                 constraints = customConstraints;
657             }
658         } else {
659             constraints = defaultConstraints;
660         }
661     }
662
663
664     /**
665      * Returns the <code>CheckInfo</code> object for the given
666      * <code>Check</code> object. <code>Check</code> object represents
667      * the <code>Constraint</code> object. <code>CheckInfo</code> hold
668      * information for a particular <code>Constraint</code> , for example,
669      * Constraint class name, Constraint constructor arguments & thier types.
670      *
671      * @param checkName the given <code>Check</code> name
672      *
673      * @return <code>CheckInfo</code> the <code>CheckInfo</code>
674      * object for the given <code>Check</code>
675      */

676     private CheckInfo getCheckInfo(String JavaDoc checkName,
677                 Constraints constraints){
678         CheckInfo checkInfo = null;
679         int size = constraints.sizeCheckInfo();
680         for(int i=0; i<size; i++) {
681             checkInfo = constraints.getCheckInfo(i);
682             if(checkName.equals(checkInfo.getName())) {
683                 return checkInfo;
684             }
685         }
686         return null;
687     }
688
689
690     /**
691      * Constructs <code>Cosntraint</code> object, from the given
692      * <code>Check</code> and <code>CheckInfo</code> objects.
693      * <code>Check</code> object identifies a particular
694      * <code>Constraint</code>, whereas <code>CheckInfo</code> object
695      * provides additional information about the <code>Constraint</code>,
696      * such as Constraint class name, Constraint constructor arguments &
697      * thier types.
698      * For a given element <code>Check</code> object is constructed from
699      * the information specified in Validation File whereas the
700      * corresponding <code>CheckInfo</code> object is built from the
701      * infromation provided in Constraints File.
702      *
703      * @param check the <code>Check</code> object identifying the
704      * <code>Constraint</code>
705      * @param checkInfo the given <code>CheckInfo</code> object providing more
706      * information about the <code>Constraint</code> identified by input
707      * parameter <code>check</code>
708      *
709      * @return <code>Constraint</code> the <code>Constraint</code>object
710      * constructed from the input paramerters <code>check</code> and
711      * <code>checkInfo</code>
712      */

713     private Constraint buildConstraint(Check check, CheckInfo checkInfo){
714         //Constraint objects are always created using the default constructor.
715
//Fields in Constraint object are then set using using the setter
716
//methods. In order to set the fields in the Constraint object, field
717
//values are fetched from the check object and the no of arguments,
718
//argument names and thier types are fetched from checkInfo object.
719
//Assumptions
720
// Every Constraint must have default constructor.
721
// Every Constraint that has fields must provide setter functions
722
// to set those fields.
723
// <name> field of <check> in Validation File is matched with
724
// <name> field of <check-info> in Constraints File to find out
725
// infromation of a particulatar Constraint.
726
// Number of <parameters> defined in <check> should match the
727
// number of <arguments> of corresponding <check-info>
728
//
729
Constraint constraint = null;
730         String JavaDoc classname = checkInfo.getClassname();
731         Arguments arguments = checkInfo.getArguments();
732         Class JavaDoc[] argumentTypeClass = new Class JavaDoc[1];
733         Object JavaDoc[] argumentValue = new Object JavaDoc[1];
734         
735         String JavaDoc argumentName;
736         String JavaDoc argumentType;
737
738         constraint = (Constraint)utils.createObject(classname);
739         if(null != arguments){
740             int size = arguments.sizeArgument();
741             Parameters parameters = check.getParameters();
742
743             if((null != parameters) && (size == parameters.sizeParameter())){
744                 Argument argument = null;
745                 Parameter parameter = null;
746                 for(int i=0; i<size; i++) {
747                     argument = arguments.getArgument(i);
748                     argumentName = argument.getName();
749                     argumentType = argument.getType();
750                     parameter =
751                         getParameter(parameters, argumentName);
752
753                     if(parameter == null){
754                         String JavaDoc format = BundleReader.getValue(
755                             "Warning_no_value_specified_for"); //NOI18N
756
Object JavaDoc[] substitutes =
757                             new Object JavaDoc[]{argumentName, check.getName()};
758                         System.out.println(
759                             MessageFormat.format(format, substitutes));
760                         continue;
761                     }
762
763                     if(null == argumentType){
764                         argumentType = "java.lang.String"; //NOI18N
765
}
766
767                     int noOfValues = 1;
768                     if(argumentType.equals("java.lang.String[]")){ //NOI18N
769
Integer JavaDoc sz = (Integer JavaDoc)utils.getElement("value", //NOI18N
770
parameter, SIZE_PREFIX);
771                         noOfValues = sz.intValue();
772                         argumentType = "java.lang.String"; //NOI18N
773
}
774                     for(int j=0; j<noOfValues; j++) {
775                         argumentValue[0] = utils.getElement("value", //NOI18N
776
j, parameter);
777                         argumentTypeClass[0] =
778                             utils.getClass(argumentType);
779                         String JavaDoc methodName =
780                             utils.methodNameFromDtdName(argumentName,
781                                 SET_PREFIX);
782                         Method JavaDoc method =
783                             utils.getMethod(utils.getClass(constraint),
784                                 methodName, argumentTypeClass);
785                         utils.invoke(constraint, method, argumentValue);
786                     }
787                 }
788             } else {
789                 String JavaDoc format = BundleReader.getValue(
790                     "MSG_Conflicting_Constraint_information"); //NOI18N
791
Object JavaDoc[] substitues = new Object JavaDoc[]{check.getName()}; //NOI18N
792
String JavaDoc message = MessageFormat.format(format, substitues);
793                 assert false : message;
794             }
795         }
796         return constraint;
797     }
798
799
800     /**
801      * Constructs <code>CardinalCosntraint</code> object, for the given
802      * cardinal. Cardinal Constraint is implicit i.e user do not need to
803      * define Cardinal Constraint for elements. Its applied implicitly to
804      * all the elements. Where in case of other Constraints user must
805      * specify which Constraints to apply to which elements. User specifies
806      * this through Validation File.
807      *
808      * @param cardinal the given cardinal; it could be one of the following :
809      * MANDATORY_ELEMENT, MANDATORY_ARRAY, OPTIONAL_ELEMENT or OPTIONAL_ARRAY
810      *
811      * @return <code>CardinalConstraint</code> object representing the given
812      * cardinal
813      */

814     private CardinalConstraint getCardinalConstraint(int cardinal){
815         Class JavaDoc[] argumentTypes = new Class JavaDoc[] {int.class};
816         Constructor JavaDoc constructor =
817             utils.getConstructor(CARDINAL_CONSTRAINT_CLASS, argumentTypes);
818
819         Integer JavaDoc parameter = new Integer JavaDoc(cardinal);
820         Object JavaDoc[] argumentValues = new Object JavaDoc[] {parameter};
821
822         return (CardinalConstraint) utils.createObject(constructor,
823             argumentValues);
824     }
825
826
827     /**
828      * Validates the given element of the given <code>Validatee</code>.
829      * This method is called for an element that is an array(optional array
830      * or madatory array) of objects.
831      *
832      * @param elementName the given element to be validated
833      * @param validatee the given <code>Validatee</code> object; the
834      * element of which needs to be validated
835      *
836      * @return <code>Collection</code> the Collection of
837      * <code>ConstraintFailure</code> Objects. Collection is empty
838      * if there are no failures.
839      */

840     private Collection JavaDoc validateBeans(String JavaDoc elementName,
841             Validatee validatee){
842         //This method does an recursive call for each of the objects in an
843
//array of given element.
844
int noOfElements = 0;
845         String JavaDoc sizeMethodName = utils.methodNameFromBeanName(elementName,
846             SIZE_PREFIX);
847         Method JavaDoc sizeMethod = validatee.getMethod(sizeMethodName);
848         noOfElements = ((Integer JavaDoc)validatee.invoke(sizeMethod)).intValue();
849
850         ArrayList JavaDoc failures = new ArrayList JavaDoc();
851         Object JavaDoc child = null;
852         for(int i=0; i<noOfElements; i++) {
853             child = validatee.getElement(elementName, i);
854             if(child != null) {
855                 failures.addAll(validate(child));
856             }
857         }
858         return failures;
859     }
860
861
862     /**
863      * Validates the given element of the given <code>Validatee</code>.
864      * This method is called for an element that is an object.
865      *
866      * @param elementName the given element to be validated
867      * @param validatee the given <code>Validatee</code> object; the
868      * element of which needs to be validated
869      *
870      * @return <code>Collection</code> the Collection of
871      * <code>ConstraintFailure</code> Objects. Collection is empty
872      * if there are no failures.
873      */

874     private Collection JavaDoc validateBean(String JavaDoc elementName,
875             Validatee validatee){
876         //This method does an recursive call on the object of given element.
877
ArrayList JavaDoc failures = new ArrayList JavaDoc();
878         Object JavaDoc child = null;
879         child = validatee.getElement(elementName);
880         if(child != null) {
881             failures.addAll(validate(child));
882         }
883         return failures;
884     }
885
886
887     /**
888      * Constructs <code>InputStream</code> object, for default Validation File
889      * defining <code>Constraints</code> to be applied to different
890      * elements. The default Validation File is represented by the private
891      * attribute <code>defaultValidationFile</code>
892      *
893      * @return <code>InputStream</code> an InputStream object representing
894      * default Validation File. Returns null, in case of failure.
895      */

896     private InputStream JavaDoc getDafaultStream(){
897         InputStream JavaDoc inputStream = null;
898         URL JavaDoc url = null;
899         if(defaultValidationFile != null){
900             url = utils.getUrlObject(defaultValidationFile);
901             if(url != null) {
902                 try {
903                     inputStream = url.openStream();
904                 } catch (IOException JavaDoc exception){
905                     System.out.println(exception.getMessage());
906                 }
907             } else {
908                 assert false : (BundleReader.getValue(
909                     "Error_control_should_never_reach_here")); //NOI18N
910

911                 String JavaDoc format =
912                     BundleReader.getValue("Error_can_not_access_file"); //NOI18N
913
Object JavaDoc[] arguments = new Object JavaDoc[]{defaultValidationFile};
914                 String JavaDoc message = MessageFormat.format(format, arguments);
915                 assert false : message;
916             }
917         } else {
918             assert false : (BundleReader.getValue(
919                 "Error_control_should_never_reach_here")); //NOI18N
920
}
921         return inputStream;
922     }
923
924
925     /**
926      * Gets the element from this object with the given name.
927      *
928      * @return <code>Parameter</code> an object with the given name.
929      * Returns null if the object with the given name is not found.
930      */

931     private Parameter getParameter(Parameters parameters, String JavaDoc name){
932         int size = parameters.sizeParameter();
933         Parameter returnValue = null;
934         Parameter parameter = null;
935         String JavaDoc parameterName = null;
936         for(int i=0; i<size; i++){
937             parameter = (Parameter)utils.getElement("parameter", i, //NOI18N
938
parameters);
939             parameterName = parameter.getName();
940             if(parameterName.equals(name)){
941                 returnValue = parameter;
942                 break;
943             }
944         }
945         return returnValue;
946     }
947
948
949     /**
950      * Constructs <code>InputStream</code> object, for the given file.
951      *
952      * @return <code>InputStream</code> an InputStream object representing
953      * the given file. Returns null, in case of failure.
954      */

955     private InputStream JavaDoc getInputStream(String JavaDoc inputFile){
956         //Create an InpurtStream object
957

958         InputStream JavaDoc inputStream = null;
959
960         if(inputFile.lastIndexOf(':') == -1){
961             URL JavaDoc url = null;
962
963             url = utils.getUrlObject(inputFile);
964             if(url != null) {
965                 try {
966                     inputStream = url.openStream();
967                 } catch (IOException JavaDoc exception){
968                     System.out.println(exception.getMessage());
969                 }
970             } else {
971                 String JavaDoc format = BundleReader.getValue(
972                     "Error_specified_file_can_not_be_used"); //NOI18N
973
Object JavaDoc[] arguments = new Object JavaDoc[]{inputFile};
974                 System.out.println(MessageFormat.format(format, arguments));
975             }
976         } else {
977             File JavaDoc file = new File JavaDoc(inputFile);
978             if(file.exists()){
979                 try {
980                     inputStream = new FileInputStream JavaDoc(file);
981                 } catch(FileNotFoundException JavaDoc exception){
982                     System.out.println(exception.getMessage());
983                     inputStream = null;
984                 }
985             } else {
986                 String JavaDoc format = BundleReader.getValue(
987                     "Error_specified_file_can_not_be_used"); //NOI18N
988
Object JavaDoc[] arguments = new Object JavaDoc[]{inputFile};
989                 System.out.println(MessageFormat.format(format, arguments));
990             }
991         }
992
993         return inputStream;
994     }
995
996
997     /**
998      * Gets the Validatee Implementation name for the given object from the
999      * given <code>properties</code> file.
1000     *
1001     * @return <code>String</code> name of the Validatee Implementation for the
1002     * the object. Returns null, if no Validatee Implementation is found in the
1003     * given <code>properties</code> file.
1004     */

1005    private String JavaDoc getValidateeImplementation(Object JavaDoc object,
1006        String JavaDoc propertiesFile){
1007        String JavaDoc returnVal = null;
1008        Class JavaDoc classObject = utils.getClass(object);
1009        String JavaDoc className = classObject.getName();
1010
1011        //switch the BundleReader to read from the given impl file
1012
//validatee implementations are specified through this impl file
1013
BundleReader.setBundle(propertiesFile);
1014        
1015        String JavaDoc validateeImplName = BundleReader.getValue(className);
1016        while(!(className.equals("java.lang.Object"))){ //NOI18N
1017
if(!(validateeImplName.equals(className))){
1018                returnVal = validateeImplName;
1019                break;
1020            } else {
1021                classObject = classObject.getSuperclass();
1022                className = classObject.getName();
1023                validateeImplName = BundleReader.getValue(className);
1024            }
1025        }
1026        return returnVal;
1027    }
1028
1029
1030    /**
1031     * Constructs <code>Constraints</code> object, representing the root of
1032     * given Constraints File.
1033     *
1034     * @return <code>Constraints</code> object representing the root of the
1035     * given Constraints File. Returns null, in case of failure.
1036     */

1037    private Constraints getConstraints(String JavaDoc constraintsFile){
1038        URL JavaDoc url = null;
1039        InputStream JavaDoc inputStream = null;
1040        Constraints constraints = null;
1041
1042        if(constraintsFile != null){
1043            inputStream = getInputStream(constraintsFile);
1044        }
1045
1046        //Create graph
1047
if(inputStream != null){
1048            try {
1049                constraints = Constraints.createGraph(inputStream);
1050            } catch(Exception JavaDoc e) {
1051                System.out.println(e.getMessage());
1052                constraints = null;
1053            }
1054        }
1055        return constraints;
1056    }
1057}
1058
Popular Tags