KickJava   Java API By Example, From Geeks To Geeks.

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


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
27 import java.util.logging.Logger JavaDoc;
28 import java.util.Hashtable JavaDoc;
29 import com.sun.logging.LogDomains;
30 import com.sun.enterprise.config.ConfigBean;
31
32 /**
33     Class which contains Meta data for all types of attributes which is present in Validation Descriptor
34  * XML File
35  *
36  * Sample
37  * <attribute name=<Name> type="address" />
38  * <attribute name=<Name> type="integer" range="low,high" />
39  * <attribute name=<Name> type="string" max-length="length" />
40     
41     @author Srinivas Krishnan
42     @version 2.0
43 */

44
45 /* Base Class for all types of attribute */
46  
47 public class AttrType {
48     String JavaDoc name;
49     String JavaDoc type;
50     boolean optional = false; // iff true then attribute can be set to
51
// a null
52
Hashtable JavaDoc _specRules;
53
54     final static protected Logger JavaDoc _logger = LogDomains.getLogger(LogDomains.APPVERIFY_LOGGER);
55     public AttrType(final String JavaDoc name, final String JavaDoc type, final boolean optional) {
56         this.name = name;
57         this.type = type;
58         this.optional = optional;
59         _specRules = new Hashtable JavaDoc();
60     }
61     
62     
63     public String JavaDoc getName() {
64         return name;
65     }
66     
67     public String JavaDoc getType() {
68         return type;
69     }
70
71     public boolean getOptional(){
72         return optional;
73     }
74     
75
76     void addRuleValue(String JavaDoc ruleName, Object JavaDoc ruleValue)
77     {
78         if(ruleValue!=null)
79             _specRules.put(ruleName, ruleValue);
80             
81     }
82     
83     Object JavaDoc getRuleValue(String JavaDoc ruleName)
84     {
85         return _specRules.get(ruleName);
86     }
87     
88     public void validate(final Object JavaDoc value, final ValidationContext valCtx)
89     {
90         //check for mandatory existance if not optional
91
if (!optional && null == value){
92             reportAttributeError(valCtx, "nullValueForMandatoryAttribute",
93                   "Attribute ''{0}'' is mandatory. A null value is not allowed",
94                   new Object JavaDoc[]{name});
95         }
96         //key change check
97
validateKeyChanges(value, valCtx);
98
99         //checkUniqueness
100
validateUniqueness(value, valCtx);
101         
102         //checkReferences
103
validateReferences(value, valCtx);
104
105     }
106
107     private void validateKeyChanges(final Object JavaDoc value, final ValidationContext valCtx)
108     {
109         String JavaDoc key = valCtx.getPrimaryKeyName();
110         if (key == null || !key.equals(name))
111             return;
112         
113         if(valCtx.isUPDATE())
114         {
115             if(name.equals(valCtx.name))
116             {
117                 //change primary key is prohibited
118
reportAttributeError(valCtx, "primarykeychangeattempt",
119                          "Cannot change a primary key",
120                          new Object JavaDoc[] {valCtx.name});
121             }
122         }
123         else if(valCtx.isSET() || valCtx.isADD() || valCtx.isVALIDATE())
124         {
125             if ( (valCtx.classObject instanceof ConfigBean) && (valCtx.value instanceof ConfigBean) )
126              {
127
128                 if(!isAttrValueUniqueAmongSiblings((ConfigBean)valCtx.classObject, (ConfigBean)valCtx.value, key, null))
129                 {
130                     reportAttributeError(valCtx, "keyDuplication",
131                          "Element with the same attribute value ({0} = {1}) already exists.",
132                          new Object JavaDoc[] {key, value});
133                 }
134             }
135             
136         }
137         else if(valCtx.isDELETE())
138             return; //FIXME: what to do with DELETE
139

140     }
141     
142     private void validateUniqueness(final Object JavaDoc value, final ValidationContext valCtx)
143     {
144         String JavaDoc[] belongsTo = (String JavaDoc[])getRuleValue("belongs-to"); // unique in name-domains (forms name-domain too)
145
if (belongsTo==null || belongsTo.length==0)
146             return;
147         NameListMgr nameListMgr = valCtx.getNameListMgr();
148         if(nameListMgr==null)
149             return;
150         String JavaDoc xpathForValue = getFutureXPathForValidatingAttribute(valCtx);
151         String JavaDoc[] valuesToTest = ((String JavaDoc)value).split(",");
152         
153         for(int i=0; i<belongsTo.length; i++)
154         {
155             if(belongsTo[i]!=null)
156             {
157                 for(int j=0; j<valuesToTest.length; j++)
158                 {
159                     if(valCtx.isDELETE())
160                     {
161                         if(nameListMgr.isValueInNameDomainReferenced(
162                              belongsTo[i], valuesToTest[j], xpathForValue))
163                         {
164                             String JavaDoc elementPrintName = GenericValidator.
165                                  getConfigElementPrintName(xpathForValue, true, true);
166                             String JavaDoc refXPath= nameListMgr.getDomainValueReferenceeXPath(
167                                  belongsTo[i], valuesToTest[j], xpathForValue);
168                             String JavaDoc refPrintName = GenericValidator.
169                                  getConfigElementPrintName(refXPath, true, true);
170                             reportAttributeError(valCtx, "isReferenced",
171                                "Element {0} can not be deleted because it is referenced from {1}",
172                                new Object JavaDoc[] {elementPrintName, refPrintName});
173                         }
174                     }
175                     else
176                     {
177                         if(!nameListMgr.isUniqueValueInNameDomain(belongsTo[i],
178                                                     valuesToTest[j],
179                                                     xpathForValue))
180                         {
181                             reportAttributeError(valCtx, "notUniqueInList",
182                                "Attribute value ({0} = {1}) is not unique in {2}.",
183                                new Object JavaDoc[] {name, valuesToTest[j],
184                                    nameListMgr.getDescriptionForNameDomain(belongsTo[i])});
185                         }
186                     }
187                 }
188             }
189         }
190     }
191     
192     private void validateReferences(final Object JavaDoc value, final ValidationContext valCtx)
193     {
194         String JavaDoc[] referencesTo = (String JavaDoc[])getRuleValue("references-to"); // referencing to name-domains
195
if (referencesTo==null || referencesTo.length==0 || value==null)
196             return;
197         NameListMgr nameListMgr = valCtx.getNameListMgr();
198         if(nameListMgr==null)
199             return;
200         if(valCtx.isDELETE())
201             return; //FIXME: what to do with DELETE
202

203         String JavaDoc xpathForValue = getFutureXPathForValidatingAttribute(valCtx);
204         String JavaDoc[] valuesToTest = ((String JavaDoc)value).split(",");
205         
206         for(int i=0; i<referencesTo.length; i++)
207         {
208             if(referencesTo[i]!=null)
209             {
210                 for(int j=0; j<valuesToTest.length; j++)
211                 {
212 //System.out.println(" referencesTo[i]="+referencesTo[i]+ "\n valuesToTest[j]="+valuesToTest[j] + "\n xpathForValue="+xpathForValue);
213
if(!nameListMgr.isValueInNameDomain(referencesTo[i],
214                                                 valuesToTest[j],
215                                                 xpathForValue))
216                     {
217 //System.out.println(">>>value=" + value);
218
reportAttributeError(valCtx, "notFoundInList",
219                              "Attribute value ({0} = {1}) is not found in {2}.",
220                               new Object JavaDoc[] {name, valuesToTest[j], nameListMgr.getDescriptionForNameDomain(referencesTo[i])});
221                     }
222                 }
223             }
224         }
225     }
226      /**
227       * get attribute values from siblings
228       */

229      private boolean isAttrValueUniqueAmongSiblings(ConfigBean parent, ConfigBean cb, String JavaDoc attrName, String JavaDoc newValue)
230      {
231          if(parent==null || cb==null)
232             return true;
233          ConfigBean[] cbs = parent.getChildBeansByName(cb.name());
234          String JavaDoc value = newValue!=null?newValue:cb.getAttributeValue(attrName);
235          if(cbs == null)
236              return true;
237          for(int i=0; i<cbs.length; i++)
238          {
239              if( ((Object JavaDoc)cbs[i] != (Object JavaDoc)cb) &&
240                  value.equals(cbs[i].getAttributeValue(attrName)))
241                 return false;
242          }
243          return true;
244      }
245
246      /**
247       * get all siblings beans (including this)
248       */

249      public ConfigBean[] getAllSiblingsForConfigBean(ConfigBean cb)
250      {
251          ConfigBean parent = (ConfigBean)cb.parent();
252          if(parent==null)
253              return new ConfigBean[]{cb};
254          else
255              return parent.getChildBeansByName(cb.name());
256      }
257
258      /**
259       * get attribute values from siblings
260       */

261      private String JavaDoc[] getAttrValuesFromSiblings(ConfigBean cb, String JavaDoc attrName, boolean bIncludingThis)
262      {
263          ConfigBean[] cbs = getAllSiblingsForConfigBean(cb);
264          if(cbs == null)
265              return new String JavaDoc[0];
266          int iStrsLen = cbs.length;
267          if(!bIncludingThis)
268              iStrsLen--;
269          if(iStrsLen<=0)
270              return new String JavaDoc[0];
271          String JavaDoc[] strs = new String JavaDoc[iStrsLen];
272          int iStr = 0;
273          for(int i=0; i<cbs.length; i++)
274          {
275              if(bIncludingThis || (Object JavaDoc)cbs[i]!=(Object JavaDoc)cb)
276                 strs[iStr++] = cbs[i].getAttributeValue(attrName);
277          }
278          return strs;
279      }
280      protected String JavaDoc getFutureXPathForValidatingAttribute(ValidationContext valCtx)
281      {
282         if(valCtx.isSET() || valCtx.isADD() || valCtx.isVALIDATE())
283         {
284             String JavaDoc[] tokens = XPathHelper.extractTokens(((ConfigBean)valCtx.value).getAbsoluteXPath(""));
285             if(valCtx.classObject==null) //root
286
{
287                 return "/" + tokens[tokens.length-1] + "/@" + name;
288             }
289             return ((ConfigBean)valCtx.classObject).getXPath() + "/" +
290                             tokens[tokens.length-1] + "/@" + name;
291         }
292         else if(valCtx.isUPDATE())
293         {
294             return ((ConfigBean)valCtx.classObject).getXPath() + "/@" + name;
295         }
296         else if(valCtx.isDELETE())
297         {
298             if(valCtx.value instanceof ConfigBean)
299                return ((ConfigBean)valCtx.value).getXPath() + "/@" + name;
300         }
301         return null;
302      }
303     protected String JavaDoc getValueForAttribute(String JavaDoc attrName, ValidationContext valCtx)
304     {
305         if(attrName==null || valCtx.getTargetBean()==null)
306             return null;
307         if(attrName.startsWith("@"))
308             attrName = attrName.substring(1);
309         return valCtx.getTargetBean().getAttributeValue(attrName);
310     }
311
312     protected void reportAttributeError(ValidationContext valCtx,
313             String JavaDoc msgNameSuffix, String JavaDoc defaultMsg, Object JavaDoc[] values)
314     {
315         ReportHelper.reportAttributeError(valCtx,
316                                 msgNameSuffix, defaultMsg, values);
317
318     }
319 }
320
321
Popular Tags