KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > tools > common > validation > ValidationManager


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 /*
25  * ValidationManager.java April 14, 2003, 5:29 PM
26  */

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

100 public class ValidationManager {
101     /*
102     ValidationManager is an object that constructs Validator objects for all
103     the Validatees. ValidationManager maintains a map of xpaths to Validators.
104     It constructs this by reading Validation File. Validation File specifies
105     Constraints to be applied to the elements.
106     Every Validatee has a corresponding Validator object and this object
107     knows how to validate its Validatee. Validator maintains a list of
108     Constraints that needs to be applied for each of the element of its
109     Validatee. Constraint objects are built using files, Constraints File
110     and Validation File.
111     */

112
113     /**
114      * A prefix used to construct the getter method name of the bean.
115      */

116     private static String JavaDoc GET_PREFIX = "get"; //NOI18N
117

118
119     /**
120      * A prefix used to construct the setter method name of the bean.
121      */

122     private static String JavaDoc SET_PREFIX = "set"; //NOI18N
123

124
125     /**
126      * A prefix used to construct the size method name of the bean.
127      */

128     private static String JavaDoc SIZE_PREFIX = "size"; //NOI18N
129

130
131     /**
132      * A file that is used specify infromation for the constraints provided
133      * by this framework. <code>Constraint</code> objects are built using the
134      * information in this file.
135      */

136     private static final String JavaDoc defaultConstraintsFile =
137         "com/sun/enterprise/tools/common/validation/constraints/" + //NOI18N
138
"constraints.xml"; //NOI18N
139

140     
141     /**
142      * A Cardinal Constraint class name.
143      */

144     private static final String JavaDoc CARDINAL_CONSTRAINT_CLASS =
145         "com.sun.enterprise.tools.common.validation.constraints." + //NOI18N
146
"CardinalConstraint"; //NOI18N
147

148
149     /**
150      * A file that is used to specify <code>Constraints<code> to be
151      * applied to various elements. xpaths are used to specify elements.
152      * While constructing this object, clients of this framework can specify
153      * their own file by providing the file name to the appropriate
154      * constructor. If client do not, then the default file( specified by
155      * <code>defaultValidationFile</code> ) is used.
156      */

157     private String JavaDoc validationFile = null;
158
159     
160     /**
161      * A default Validation file that specify <code>Constraints<code> to be
162      * applied to various elements. xpaths are used to specify elements.
163      * This file is used by framework if client do not specify one.
164      * This file contains default validation rules.
165      */

166     private String JavaDoc defaultValidationFile =
167            "com/sun/enterprise/tools/common/validation/validation.xml"; //NOI18N
168

169     
170     /**
171      * A map that stores for each <code>Validatee</code> object, the xpath and
172      * the corresponding <code>Validator</code> object.
173      */

174     private HashMap JavaDoc xpathToValidator = null;
175
176
177     /**
178      * A root bean representing validation.xml
179      */

180     private Validation validation = null;
181
182
183     /**
184      * A root bean representing constaints.xml
185      */

186     private Constraints constraints = null;
187
188     
189     /**
190      * An object providing utilities
191      */

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

229     public Collection JavaDoc validate(Object JavaDoc object){
230         //This method get called in case of Objects that are not Validatee.
231
//This method, essentially, gets the Object's Validatee Implementation
232
//and uses it instead.
233

234         Collection JavaDoc collection = new ArrayList JavaDoc();
235
236         if(object != null){
237             boolean validateeImplFound = false;
238             String JavaDoc validateeImpl = null;
239
240             String JavaDoc implFile =
241                 System.getProperty("impl.file"); //NOI18N
242
///System.out.println(implFile);
243

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

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

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

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

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

462     private Validator getValidator(String JavaDoc xpath){
463         Validator validator = null;
464         if(null == xpathToValidator){
465             constructXpathToValidator();
466         }
467         if(null != xpathToValidator) {
468             validator = (Validator)xpathToValidator.get(xpath);
469         }
470         return validator;
471     }
472
473
474     /**
475      * Constructs the xpath to <code>Validator</code> map.
476      * Uses Validation File and Constraints File to build the map.
477      */

478     private void constructXpathToValidator(){
479         //read validation file and construct xPathToValidator Map
480

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

554     private void constructValidation() {
555         //Create an InpurtStream object
556

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

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

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

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

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

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

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

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

904     private InputStream JavaDoc getDafaultStream(){
905         InputStream JavaDoc inputStream = null;
906         URL JavaDoc url = null;
907         if(defaultValidationFile != null){
908             url = utils.getUrlObject(defaultValidationFile);
909             if(url != null) {
910                 try {
911                     inputStream = url.openStream();
912                 } catch (IOException JavaDoc exception){
913                     System.out.println(exception.getMessage());
914                 }
915             } else {
916                 assert false : (BundleReader.getValue(
917                     "Error_control_should_never_reach_here")); //NOI18N
918

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

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

963     private InputStream JavaDoc getInputStream(String JavaDoc inputFile){
964         //Create an InpurtStream object
965

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

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

1045    private Constraints getConstraints(String JavaDoc constraintsFile){
1046        URL JavaDoc url = null;
1047        InputStream JavaDoc inputStream = null;
1048        Constraints constraints = null;
1049
1050        if(constraintsFile != null){
1051            inputStream = getInputStream(constraintsFile);
1052        }
1053
1054        //Create graph
1055
if(inputStream != null){
1056            try {
1057                constraints = Constraints.createGraph(inputStream);
1058            } catch(Exception JavaDoc e) {
1059                System.out.println(e.getMessage());
1060                constraints = null;
1061            }
1062        }
1063        return constraints;
1064    }
1065}
1066
Popular Tags