KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > config > serverbeans > validation > GenericValidator


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 package com.sun.enterprise.config.serverbeans.validation;
25
26 import java.util.Vector JavaDoc;
27 import java.net.InetAddress JavaDoc;
28 import java.net.UnknownHostException JavaDoc;
29 import com.sun.enterprise.config.ConfigContextEvent;
30 import com.sun.enterprise.config.ConfigContext;
31 import com.sun.enterprise.config.ConfigBean;
32 import com.sun.enterprise.config.serverbeans.validation.tests.StaticTest;
33 import com.sun.enterprise.config.serverbeans.ElementProperty;
34
35 import com.sun.enterprise.admin.meta.MBeanRegistryFactory;
36
37 // Logging
38
import java.util.logging.Logger JavaDoc;
39 import java.util.logging.Level JavaDoc;
40 import com.sun.logging.LogDomains;
41 import com.sun.enterprise.util.LocalStringManagerImpl;
42
43
44
45 /**
46  * Class which validates all attributes in the validation descriptor xml file.
47  * All custom tests use this as the base class
48
49     @author Srinivas Krishnan
50     @version 2.0
51 */

52
53
54 public class GenericValidator implements DomainCheck {
55     
56     // Logging
57
final static protected Logger JavaDoc _logger = LogDomains.getLogger(LogDomains.APPVERIFY_LOGGER);
58     protected LocalStringManagerImpl smh = StringManagerHelper.getLocalStringsManager();
59     
60     ValidationDescriptor desc;
61     
62     public GenericValidator(ValidationDescriptor desc) {
63         this.desc = desc;
64 // try {
65
StringManagerHelper.setLocalStringsManager(DomainXmlVerifier.class);
66             smh = StringManagerHelper.getLocalStringsManager();
67 // }
68
// catch (ClassNotFoundException e) {
69
// _logger.log(Level.FINE, "domainxmlverifier.class_notfound_exception", e);
70
// }
71
}
72     
73     // Initialize all the member variables from the event, invoked by validate. If sub class is not calling
74
// super.validate subclass has to call initialize before starting validation
75
public ValidationContext initialize(ConfigContextEvent cce) {
76         ValidationContext valCtx = new ValidationContext(new Result(), cce.getObject(), cce.getClassObject(),
77                                         cce.getBeanName(), cce.getConfigContext(), cce.getName(), cce.getChoice(),
78                                         desc.getKey(), smh, desc);
79         String JavaDoc key = desc.getKey();
80         String JavaDoc element = desc.getElementName();
81         if(valCtx.value instanceof ConfigBean) {
82             valCtx.result.setAssertion(element);
83             try {
84                 valCtx.result.setTestName(smh.getLocalString(GenericValidator.class.getName() + ".Elementkeyvalue",
85                 "{0} = {1}", new Object JavaDoc[]{key, ((ConfigBean)valCtx.value).getAttributeValue(key) }));
86             } catch(Exception JavaDoc e) {
87                 _logger.log(Level.FINE, "domainxmlverifier.keynotfound", e);
88             }
89         }
90         valCtx.result.setStatus(0);
91         //set operation name
92
if(!valCtx.isVALIDATE())
93         {
94             String JavaDoc elementName = getTargetElementPrintName(valCtx, true, false);
95             String JavaDoc strLocalTag;
96             String JavaDoc strDefault;
97             if(valCtx.isADD() || valCtx.isSET()) {
98                 strLocalTag = "add_operation_descr";
99                 strDefault = "Creation config element for {0}";
100             } else if(valCtx.isDELETE()) {
101                 strLocalTag = "delete_operation_descr";
102                 strDefault = "Deletion of config element for {0}";
103             } else {
104                 strLocalTag = "update_operation_descr";
105                 strDefault = "Update of config element for {0}";
106             }
107             valCtx.result.setOperationPrintName(valCtx.smh.getLocalString(
108                    strLocalTag, strDefault, new Object JavaDoc[] {elementName}));
109         }
110         return valCtx;
111     }
112
113     private void validateAttribute(AttrType attr, ValidationContext valCtx)
114     {
115         if(valCtx.choice == null)
116             return;
117         String JavaDoc attrName = attr.getName();
118         Object JavaDoc value = null;
119         ConfigBean ownerBean = null;
120         if(valCtx.isADD() || valCtx.isVALIDATE() || valCtx.isSET() || valCtx.isDELETE())
121         {
122             ownerBean = (ConfigBean)valCtx.value;
123             value = ((ConfigBean)valCtx.value).getAttributeValue(attrName);
124             
125         }
126         else if(valCtx.isUPDATE())
127         {
128            if(attr.getName().equals(valCtx.name))
129            {
130                 ownerBean = (ConfigBean)valCtx.classObject;
131                 value = valCtx.value;
132 // _logger.log(Level.WARNING, "setting attribute: "+attr.getName()+" to: " +valCtx.value);
133
}
134         }
135
136        
137         if(ownerBean!=null /*&& value!=null*/)
138         {
139             //-----------set current validation state in valCtx
140
valCtx.setAttrName(attrName);
141             valCtx.attrValue = value;
142             //valCtx.ownerBean = ownerBean;
143
// and now - call attributes validation method for element
144
validateAttribute(ownerBean, attr, value, valCtx);
145         }
146     }
147     
148     // can be overriden by specific element test class
149
public void validateAttribute(ConfigBean ownerBean, AttrType attr, Object JavaDoc value, ValidationContext valCtx)
150     {
151         if (/*value!=null &&*/ !StaticTest.valueContainsTokenExpression((String JavaDoc) value))
152         {
153             //generic validation of attribute
154
attr.validate(value, valCtx);
155         }
156     }
157
158     // can be overriden by specific element test class
159
public void validateElement(ValidationContext valCtx)
160     {
161      String JavaDoc key = desc.getKey();
162      String JavaDoc element = desc.getElementName();
163      if(valCtx.isADD() || valCtx.isSET())
164      {
165         ConfigBean thisBean = (ConfigBean)valCtx.value;
166         ConfigBean parentBean = (ConfigBean)valCtx.classObject;
167         String JavaDoc[] names = desc.requiredChildren;
168         for(int i=0; names!=null && i<names.length; i++)
169         {
170             String JavaDoc childName = names[i];
171             if(names[i].endsWith("*"))
172                 childName = names[i].substring(0, names[i].length()-1);
173             childName = XPathHelper.convertName(childName);
174             ConfigBean[] beans = thisBean.getChildBeansByName(childName);
175             if (beans==null || beans.length==0)
176             {
177                 if(names[i].endsWith("*"))
178                 {
179                     String JavaDoc printParentName = getConfigElementPrintName(
180                         getFutureXPath(thisBean, parentBean), false, false);
181                     valCtx.result.failed(valCtx.smh.getLocalString(
182                         GenericValidator.class.getName() + ".multipleRequiredElemAbsent",
183                         "At least one required element {0} should be present in created {1}",
184                         new Object JavaDoc[] {names[i].substring(0, names[i].length()-1),
185                                 printParentName}));
186                 }
187                 else
188                 {
189                     String JavaDoc printParentName = getConfigElementPrintName(
190                         getFutureXPath(thisBean, parentBean), false, false);
191                     valCtx.result.failed(valCtx.smh.getLocalString(
192                         GenericValidator.class.getName() + ".requiredElemAbsent",
193                         "Required element {0} should be present in created {1}",
194                         new Object JavaDoc[] {names[i], printParentName}));
195                 }
196             }
197         }
198         names = desc.exclusiveChildren;
199         String JavaDoc alreadyFound = null;
200         for(int i=0; names!=null && i<names.length; i++)
201         {
202             String JavaDoc childName = names[i];
203             childName = XPathHelper.convertName(childName);
204             ConfigBean[] beans = thisBean.getChildBeansByName(childName);
205             if (beans==null || beans.length==0)
206                 continue;
207             if(alreadyFound==null)
208             {
209                 alreadyFound = names[i];
210             }
211             else
212             {
213                 String JavaDoc printParentName = getConfigElementPrintName(
214                     getFutureXPath(thisBean, parentBean), false, false);
215                 valCtx.result.failed(valCtx.smh.getLocalString(
216                         GenericValidator.class.getName() + ".childrenCanExistTogether",
217                         "{0} can not contain both sub-elements {1} and {2} in the same time.",
218                         new Object JavaDoc[] {printParentName, alreadyFound, names[i]}));
219             }
220         }
221      }
222     }
223
224     // can be overriden by specific element test class
225
// this is convenience method for property owner element validator
226
// to add reaction on property changes
227
// this method is called from <code>validateAsParent</code> method
228
// NOTE: ValidationContext is initialized in child's validator
229
public void validatePropertyChanges(ValidationContext valCtx)
230     {
231        return;
232     }
233     
234     // can be overriden by specific element test class
235
// NOTE: ValidationContext is initialized in child's validator
236
public void validateAsParent(ValidationContext valCtx)
237     {
238      if(valCtx.isADD() || valCtx.isSET())
239      {
240         ConfigBean newChildBean = (ConfigBean)valCtx.value;
241         String JavaDoc newChildBeanName = getBeanElementName(newChildBean);
242         ConfigBean parentBean = (ConfigBean)valCtx.classObject;
243
244         String JavaDoc[] names = desc.exclusiveChildren;
245         //first, let's be sure that newChildBean in exclusive list
246
boolean bNewChildIsInList = false;
247         if(names!=null)
248         {
249             for(int i=0; i<names.length; i++)
250             {
251                if(newChildBeanName.equals(names[i]))
252                {
253                    bNewChildIsInList = true;
254                    break;
255                }
256             }
257         }
258         //now find out if any othjers are there too
259
if(bNewChildIsInList)
260         {
261             for(int i=0; i<names.length; i++)
262             {
263                 String JavaDoc childName = names[i];
264                 if(childName.equals(newChildBeanName))
265                     continue;
266                 childName = XPathHelper.convertName(childName);
267                 ConfigBean[] beans = parentBean.getChildBeansByName(childName);
268                 if (beans!=null && beans.length>0)
269                 {
270                     String JavaDoc printParentName = getConfigElementPrintName(
271                         parentBean.getXPath(), false, false);
272                     valCtx.result.failed(valCtx.smh.getLocalString(
273                             GenericValidator.class.getName() + ".childrenCanExistTogether",
274                             "{0} can not contain both sub-elements {1} and {2} in the same time.",
275                             new Object JavaDoc[] {printParentName,
276                                     newChildBeanName, names[i]}));
277                 }
278             }
279         }
280      }
281      else if(valCtx.isDELETE())
282      {
283         //Check for existence of required sub-elements
284
ConfigBean childBean = (ConfigBean)valCtx.value;
285         ConfigBean parentBean = (ConfigBean)valCtx.classObject;
286         String JavaDoc childBeanName = XPathHelper.convertName(getBeanElementName(childBean));
287         ConfigBean[] beans = parentBean.getChildBeansByName(childBeanName);
288         if (beans!=null && beans.length==1)
289         { //LAST ELEM DELETION
290
ValidationDescriptor parentDescr = desc;
291             String JavaDoc[] names = null;
292             if(parentDescr!=null)
293                 names = parentDescr.requiredChildren;
294             String JavaDoc compareTo = getBeanElementName(childBean);
295             String JavaDoc compareTo2 = compareTo+'*';
296             for(int i=0; names!=null && i<names.length; i++)
297             {
298                 if(compareTo.equals(names[i]))
299                 {
300                     String JavaDoc printParentName = getConfigElementPrintName(
301                         parentBean.getXPath(), false, false);
302                     String JavaDoc printChildName = getConfigElementPrintName(
303                         childBean.getXPath(), false, false);
304                     valCtx.result.failed(valCtx.smh.getLocalString(
305                         GenericValidator.class.getName() + ".requiredElemDelete",
306                         "Required element {0} can not be deleted from {1}",
307                         new Object JavaDoc[] {printChildName, printParentName}));
308                     break;
309                 }
310                 else if(compareTo2.equals(names[i]))
311                 {
312                     String JavaDoc printParentName = getConfigElementPrintName(
313                         parentBean.getXPath(), false, false);
314                     String JavaDoc printChildName = getConfigElementPrintName(
315                         childBean.getXPath(), false, false);
316                     valCtx.result.failed(valCtx.smh.getLocalString(
317                         GenericValidator.class.getName() + ".lastRequiredElemDelete",
318                         "At least one required {0} should be present in {1}."+
319                         " Deletion rejected.",
320                         new Object JavaDoc[] {printChildName, printParentName}));
321                     break;
322                 }
323             }
324         }
325
326      }
327      
328      if(valCtx.getTargetBean() instanceof ElementProperty)
329         validatePropertyChanges(valCtx);
330         
331     }
332     
333     // Method for validation (ususally overriden by test classes)
334
public Result validate(ConfigContextEvent cce)
335     {
336         ValidationContext valCtx = initialize(cce);
337         _logger.log(Level.CONFIG, "GenericValidator processing choice: "+valCtx.choice);
338         validate(valCtx);
339                 
340         return valCtx.result;
341         
342     }
343
344     // Method for validation (ususally overriden by test classes)
345
public void validate(ValidationContext valCtx)
346     {
347         
348         //validate element (without attributes)
349
validateElement(valCtx);
350         
351         //ask parent to confirm change
352
ConfigBean parentBean = valCtx.getParentBean();
353         if(parentBean!=null)
354         {
355            //validate changes by Parent
356
GenericValidator parentValidator =
357                    desc.domainMgr.findConfigBeanValidator((ConfigBean)parentBean);
358            if(parentValidator!=null)
359            {
360                parentValidator.validateAsParent(valCtx);
361            }
362         }
363         
364         Vector JavaDoc attrs = desc.getAttributes();
365         //Attributes validation
366
for(int i=0; i<attrs.size(); i++)
367         {
368             try {
369                 validateAttribute((AttrType) attrs.get(i), valCtx);
370             } catch(IllegalArgumentException JavaDoc e) {
371                 valCtx.result.failed(e.getMessage());
372             } catch(Exception JavaDoc e) {
373                 _logger.log(Level.WARNING, "domainxmlverifier.errorinvokingmethod", e);
374             }
375         }
376         
377     }
378
379     static String JavaDoc getConfigElementPrintName(
380             String JavaDoc xpath, boolean bIncludingKey, boolean bReplaceRefByParentElem)
381    {
382       return MBeanRegistryFactory.getAdminMBeanRegistry().
383                getConfigElementPrintName(xpath, bIncludingKey, bReplaceRefByParentElem);
384    }
385
386     static String JavaDoc getTargetElementPrintName( ValidationContext valCtx,
387             boolean bIncludingKey, boolean bReplaceRefByParentElem)
388    {
389         ConfigBean targetBean = valCtx.getTargetBean();
390         if(targetBean==null)
391             return null;
392         ConfigBean parentBean = valCtx.getParentBean();
393         return getConfigElementPrintName(
394                 getFutureXPath(targetBean, parentBean),
395                 bIncludingKey, bReplaceRefByParentElem);
396    }
397
398     protected static String JavaDoc getFutureXPath(ConfigBean childBean, ConfigBean parentBean) {
399         String JavaDoc[] tokens = XPathHelper.extractTokens(childBean.getAbsoluteXPath(""));
400         if(parentBean==null) //root
401
{
402             return "/" + tokens[tokens.length-1];
403         }
404         return (parentBean.getXPath() + "/" + tokens[tokens.length-1]);
405     }
406     protected static String JavaDoc getBeanElementName(ConfigBean bean) {
407         String JavaDoc[] tokens = XPathHelper.extractTokens(bean.getAbsoluteXPath(""));
408         if(tokens.length<1)
409             return null;
410         String JavaDoc last = tokens[tokens.length-1];
411         int idx = last.indexOf('[');
412         if(idx>0)
413             return last.substring(0, idx);
414         else
415             return last;
416     }
417
418     /***********************************************************
419      * reports validation error
420      ************************************************************/

421     static public void reportValidationError(ValidationContext valCtx,
422             String JavaDoc msgNameSuffix, String JavaDoc defaultMsg, Object JavaDoc[] values)
423     {
424         ReportHelper.reportValidationError(valCtx,
425                         msgNameSuffix, defaultMsg, values);
426     }
427 }
428
Popular Tags