KickJava   Java API By Example, From Geeks To Geeks.

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


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 //jdk imports
27
import javax.xml.parsers.*;
28 import org.w3c.dom.*;
29 import java.io.File JavaDoc;
30 import java.util.StringTokenizer JavaDoc;
31 import java.util.HashMap JavaDoc;
32 import org.xml.sax.SAXException JavaDoc;
33 import org.xml.sax.InputSource JavaDoc;
34 import java.io.IOException JavaDoc;
35 import java.util.Vector JavaDoc;
36 import java.util.StringTokenizer JavaDoc;
37 import java.lang.Class JavaDoc;
38 import java.lang.reflect.Constructor JavaDoc;
39 import java.net.URL JavaDoc;
40
41 // Logging
42
import java.util.logging.Logger JavaDoc;
43 import java.util.logging.Level JavaDoc;
44 import com.sun.logging.LogDomains;
45
46 import com.sun.enterprise.util.LocalStringManagerImpl;
47 import com.sun.enterprise.config.ConfigContext;
48 import com.sun.enterprise.config.ConfigContextEvent;
49 import com.sun.enterprise.config.ConfigContextEventListener;
50 import com.sun.enterprise.admin.AdminValidationException;
51
52 // config imports
53
import com.sun.enterprise.config.ConfigFactory;
54 import com.sun.enterprise.config.ConfigException;
55 import com.sun.enterprise.config.ConfigBean;
56 import com.sun.enterprise.config.serverbeans.*;
57 import com.sun.enterprise.admin.meta.MBeanRegistryFactory;
58
59 /**
60  * Class which loads all the validator descriptor information from a xml file into a hash map.
61  * Validator uses this Hash Map and invokes the particular test case depending on xml tag
62
63     @author Srinivas Krishnan
64     @version 2.0
65 */

66
67 public class DomainMgr implements ConfigContextEventListener {
68     
69     // Logging
70
static Logger JavaDoc _logger = LogDomains.getLogger(LogDomains.APPVERIFY_LOGGER);
71     LocalStringManagerImpl smh = StringManagerHelper.getLocalStringsManager();
72     HashMap JavaDoc tests = new HashMap JavaDoc();
73     transient private long lastModified = 0;
74     public NameListMgr _nameListMgr;
75     public DomainMgr() {
76         this(MBeanRegistryFactory.getAdminContext().getAdminConfigContext(), false);
77     }
78
79     public DomainMgr(ConfigContext ctx, boolean bStaticContext) {
80         loadDescriptors();
81         _nameListMgr = new NameListMgr(ctx, bStaticContext);
82     }
83    
84     
85     // Get the path of validation descriptor xml file from System property class path
86
private String JavaDoc getTestFile() throws Exception JavaDoc {
87         URL JavaDoc propertiesFile = DomainMgr.class.getClassLoader().getResource(
88             "com/sun/enterprise/config/serverbeans/validation/config/ServerTestList.xml");
89 //TODO: for test only
90
// URL propertiesFile = (new File("/ias/admin/validator/descr.xml")).toURL();
91
return propertiesFile.toString();
92     }
93
94     // Loads all validation descriptors from XML file into the Hash Map
95
public boolean loadDescriptors() {
96         boolean allIsWell = true;
97        
98         try {
99             //tests.clear();
100
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
101             InputSource JavaDoc is = new InputSource JavaDoc(getTestFile());
102             Document doc = db.parse(is);
103             NodeList list = doc.getElementsByTagName("element");
104             for (int i=0;i<list.getLength();i++) {
105                 Element e = (Element) list.item(i);
106                 String JavaDoc elementName = e.getAttribute("name");
107                 String JavaDoc elementXPath = e.getAttribute("xpath");
108                 String JavaDoc elementCustomClass = e.getAttribute("custom-class") ;
109                 String JavaDoc testName = e.getAttribute("test-name");
110                 if(testName==null || testName.length()==0)
111                 {
112                     testName = XPathHelper.convertName(elementName);
113                 }
114                 if (null == elementCustomClass || elementCustomClass.length() == 0){
115                     elementCustomClass = testName;
116                 }
117                 String JavaDoc[] required_children = null;
118                 String JavaDoc[] exclusive_list = null;
119                 String JavaDoc elemList = e.getAttribute("required-children");
120                 if(elemList!=null && elemList.length()>0)
121                 {
122                     required_children = elemList.split(",");
123                 }
124                 elemList = e.getAttribute("exclusive-list");
125                 if(elemList!=null && elemList.length()>0)
126                 {
127                     exclusive_list = elemList.split(",");
128                 }
129                 String JavaDoc key = e.getAttribute("key");
130                 if(key!=null && key.length()==0)
131                     key = null;
132                 Vector JavaDoc attributes = new Vector JavaDoc();
133                 NodeList nl = e.getChildNodes();
134                 for (int index=0,j=0;j<nl.getLength();j++) {
135                     String JavaDoc temp;
136                     String JavaDoc nodeName = nl.item(j).getNodeName().trim();
137                     String JavaDoc nameValue=null;
138                     String JavaDoc typeValue=null;
139                     NamedNodeMap nodeMap=null;
140                     AttrType attr=null;
141                    
142                     Node n = nl.item(j);
143                     
144                     if("attribute".equals(nodeName) || "optional-attribute".equals(nodeName)) {
145                         nodeMap = n.getAttributes();
146
147                         nameValue = getAttr(nodeMap, "name");
148                         typeValue = getAttr(nodeMap, "type");
149                         if("string".equals(typeValue))
150                         {
151                             attr = new AttrString(nameValue, typeValue, "optional-attribute".equals(nodeName) );
152                             if((temp=getAttr(nodeMap, "max-length"))!=null)
153                                ((AttrString)attr).setMaxLength(Integer.parseInt(temp));
154                             if((temp=getAttr(nodeMap, "enumeration"))!=null)
155                             {
156                                 Vector JavaDoc ee = new Vector JavaDoc();
157                                 String JavaDoc[] strs = temp.split(",");
158                                 for(int k=0; k<strs.length; k++)
159                                     ee.add(strs[k]);
160                                 ((AttrString)attr).setEnumstring(ee);
161                             }
162                             ((AttrString)attr).setRegExpression(getAttr(nodeMap, "regex"));
163                         }
164                         else if("file".equals(typeValue))
165                         {
166                             attr = new AttrFile(nameValue, typeValue, "optional-attribute".equals(nodeName));
167                             if("true".equals(getAttr(nodeMap, "exists")))
168                                 ((AttrFile)attr).setCheckExists(true);
169                         }
170                         else if("integer".equals(typeValue))
171                         {
172                             attr = new AttrInt(nameValue,typeValue, "optional-attribute".equals(nodeName));
173                             if((temp = getAttr(nodeMap, "range")) != null)
174                             {
175                                 String JavaDoc[] strs = temp.split(",");
176                                 if(!strs[0].equals("NA"))
177                                     ((AttrInt)attr).setLowRange(Integer.parseInt(strs[0]));
178                                 if(!strs[1].equals("NA"))
179                                     ((AttrInt)attr).setHighRange(Integer.parseInt(strs[1]));
180                             }
181                         }
182                         else if("classname".equals(typeValue))
183                             attr = new AttrClassName(nameValue, typeValue, "optional-attribute".equals(nodeName));
184                         else if("address".equals(typeValue))
185                             attr = new AttrAddress(nameValue,typeValue, "optional-attribute".equals(nodeName));
186                         else if("jndi-unique".equals(typeValue))
187                             attr = new AttrUniqueJNDI(nameValue,typeValue, "optional-attribute".equals(nodeName));
188
189                         if(attr != null)
190                         {
191                             attr.addRuleValue("belongs-to", getAttrAsList(nodeMap, "belongs-to"));
192                             attr.addRuleValue("references-to", getAttrAsList(nodeMap, "references-to"));
193                             attr.addRuleValue("le-than", getAttr(nodeMap, "le-than"));
194                             attr.addRuleValue("ls-than", getAttr(nodeMap, "ls-than"));
195                             attr.addRuleValue("ge-than", getAttr(nodeMap, "ge-than"));
196                             attr.addRuleValue("gt-than", getAttr(nodeMap, "gt-than"));
197
198                             attributes.add(index++,attr);
199                         }
200                     }
201                 }
202                 final ValidationDescriptor desc =
203                        new ValidationDescriptor(this, elementName,
204                             elementXPath, elementCustomClass,
205                             key, attributes, required_children, exclusive_list);
206                 final GenericValidator validator= getGenericValidator(desc);
207                 if(validator != null)
208                     tests.put(testName, validator);
209             }
210         } catch (ParserConfigurationException e) {
211             _logger.log(Level.WARNING, "parser_error", e);
212             allIsWell = false;
213         } catch (SAXException JavaDoc e) {
214             _logger.log(Level.WARNING, "sax_error", e);
215             allIsWell = false;
216         } catch (IOException JavaDoc e) {
217             _logger.log(Level.WARNING, "error_loading_xmlfile", e);
218             allIsWell = false;
219         } catch(Exception JavaDoc e) {
220             _logger.log(Level.WARNING, "error", e);
221             allIsWell = false;
222         }
223         return allIsWell;
224     }
225     
226     private String JavaDoc getAttr(NamedNodeMap nodeMap, String JavaDoc attrName)
227     {
228         Node node = nodeMap.getNamedItem(attrName);
229         if(node != null)
230             return node.getNodeValue();
231         return null;
232     }
233     
234     private String JavaDoc[] getAttrAsList(NamedNodeMap nodeMap, String JavaDoc attrName)
235     {
236         String JavaDoc attrValue = getAttr(nodeMap, attrName);
237         if(attrValue==null)
238             return null;
239         return attrValue.split(",");
240     }
241         /**
242          * Get the generic validator to be used for the given
243          * validation descriptor
244          * @param v the validation descriptor
245          * @return a GenericValidator instance that is to be used to
246          * validate elements which match the ValidationDescription
247          */

248     GenericValidator getGenericValidator(final ValidationDescriptor v) throws InstantiationException JavaDoc, IllegalAccessException JavaDoc, java.lang.reflect.InvocationTargetException JavaDoc{
249         final Class JavaDoc c = getValidatorClass(v.getCustomValidatorClass());
250         try {
251             final Constructor JavaDoc con = c.getConstructor(new Class JavaDoc[]{ValidationDescriptor.class});
252             return (GenericValidator) con.newInstance(new Object JavaDoc[]{v});
253         }
254         catch (NoSuchMethodException JavaDoc e){
255             return null;
256         }
257         
258     }
259     
260         /**
261          * Find a class that will perform validation for the given
262          * class name. The class returned is the first that can be
263          * loaded from the following ordered list:
264          * <ol>
265          * <li>The class as specified by the className param</li>
266          * <li>The class as specified by the className param,
267          * prepended with the TEST_PACKAGE package name. </li>
268          * <li>The GenericValidator class</li>
269          * Setting the log level to CONFIG will provide logging
270          * information as to which class was actually found and loaded.
271          * @param className the name of the class for which a
272          * validator class is to be found
273          * @return the class which is to be used for validation
274          **/

275     Class JavaDoc getValidatorClass(final String JavaDoc className){
276         Class JavaDoc c;
277         final String JavaDoc cn = TEST_PACKAGE+className+"Test";
278             try {
279             c= Class.forName(cn);
280         }
281         catch (ClassNotFoundException JavaDoc cnfe2){
282             c = GenericValidator.class;
283         }
284         _logger.log(Level.CONFIG, "validator using class \""+c.getName()+"\" to validate \""+cn+"\"");
285         return c;
286     }
287     
288     // Method invokes the validation function of the test case
289
public Result check(ConfigContextEvent cce) {
290         String JavaDoc name = cce.getName();
291         String JavaDoc beanName = cce.getBeanName();
292         Result result = null;
293
294
295         if(name == null && beanName == null)
296                 return result;
297         
298         DomainCheck validator = (DomainCheck) tests.get(name);
299         if(validator == null && beanName != null)
300             validator = (DomainCheck) tests.get(beanName);
301         try {
302             if(validator != null)
303                 result = validator.validate(cce);
304         } catch(Exception JavaDoc e) {
305 //System.out.println("+++++name="+name + " xpath=" + ((ConfigBean)cce.getObject()).getXPath());
306
_logger.log(Level.WARNING, "domainxmlverifier.error_on_validation", e);
307         }
308         return result;
309     }
310     
311     public void postAccessNotification(ConfigContextEvent ccce) {
312     }
313     
314     public void postChangeNotification(ConfigContextEvent ccce) {
315     }
316     
317     public void preAccessNotification(ConfigContextEvent ccce) {
318     }
319     
320     // Function invoked by the Config Bean for validation before writing into domain.xml
321
// Registered as listeners with ConfigContext while creation
322
public void preChangeNotification(ConfigContextEvent cce) {
323         Result result = null;
324         try{
325            result = check(cce);
326         } catch(Throwable JavaDoc t)
327         {
328             _logger.log(Level.WARNING, "Exception during validation ", t);
329         }
330         
331         if(result != null && result.getStatus() == Result.FAILED)
332         {
333             _logger.log(Level.WARNING, "Validation error: " + result.getErrorDetails().toString());
334             throw new AdminValidationException(result.getErrorDetailsAsString());
335         }
336     }
337     ValidationDescriptor findValidationDescriptor(String JavaDoc beanName)
338     {
339         if(beanName!=null)
340         {
341             GenericValidator genVal = (GenericValidator)tests.get(beanName);
342             if(genVal!=null)
343                 return genVal.desc;
344         }
345         return null;
346     }
347
348     GenericValidator findConfigBeanValidator(ConfigBean configBean)
349     {
350         
351         if(configBean!=null)
352         {
353             String JavaDoc className = configBean.getClass().getName();
354             int iLastDot = className.lastIndexOf('.');
355             if(iLastDot>0)
356                return (GenericValidator)tests.get(className.substring(iLastDot+1));
357         }
358         return null;
359     }
360     
361     public static final String JavaDoc TEST_PACKAGE="com.sun.enterprise.config.serverbeans.validation.tests.";
362 }
363
Popular Tags