KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > formview > FormViewResources


1 package net.sourceforge.formview;
2
3 import java.io.IOException JavaDoc;
4 import java.io.InputStream JavaDoc;
5 import java.io.Serializable JavaDoc;
6 import java.net.URL JavaDoc;
7 import java.util.ArrayList JavaDoc;
8 import java.util.Collection JavaDoc;
9 import java.util.HashMap JavaDoc;
10 import java.util.Iterator JavaDoc;
11 import java.util.List JavaDoc;
12 import java.util.Map JavaDoc;
13 import java.util.StringTokenizer JavaDoc;
14
15 import net.sourceforge.formview.displayer.DisplayerConfig;
16 import net.sourceforge.formview.displayer.DisplayersConfigResources;
17 import net.sourceforge.formview.displayer.IHTMLDisplayer;
18 import net.sourceforge.formview.permission.IPermissionsAdapter;
19 import net.sourceforge.formview.validator.ExtendedValidatorResources;
20
21 import org.apache.commons.collections.FastHashMap;
22 import org.apache.commons.digester.Digester;
23 import org.apache.commons.digester.xmlrules.DigesterLoader;
24 import org.apache.commons.logging.Log;
25 import org.apache.commons.logging.LogFactory;
26 import org.apache.commons.validator.Field;
27 import org.apache.commons.validator.Form;
28 import org.apache.commons.validator.FormSet;
29 import org.apache.commons.validator.Validator;
30 import org.xml.sax.SAXException JavaDoc;
31
32 import au.id.jericho.lib.html.Attribute;
33 import au.id.jericho.lib.html.Attributes;
34 import au.id.jericho.lib.html.Element;
35 import au.id.jericho.lib.html.OutputDocument;
36 import au.id.jericho.lib.html.Source;
37 import au.id.jericho.lib.html.Tag;
38
39
40 /**
41  * Description : Form view Resources wich load file form-view.xml
42  * and merge field with validator (validation.xml)
43  *
44  * @author <a HREF="mailto:angelo.zerr@gmail.com">Angelo ZERR</a>
45  *
46  */

47 public class FormViewResources implements Serializable JavaDoc {
48     
49     private static final long serialVersionUID = 1L;
50
51     protected static Log log = LogFactory.getLog(FormViewResources.class);
52  
53     /**
54      * <code>FastHashMap</code> of global constant values with
55      * the name of the constant as the key.
56      */

57     protected FastHashMap hStates = new FastHashMap();
58
59     /**
60      * <code>FastHashMap</code> of role definition with
61      * the name of the constant as the key.
62      */

63     protected FastHashMap hRolesDefinition = new FastHashMap();
64     
65     private RoleDefinition defaultRoleDefinition = null;
66     
67     /**
68      * <code>FastHashMap</code> of displayers with
69      * the name of the constant as the key.
70      */

71     protected FastHashMap hDisplayers = new FastHashMap();
72     
73     protected FastHashMap hHTMLDisplayers = new FastHashMap();
74     
75     protected List JavaDoc lHTMLDisplayers = new ArrayList JavaDoc();
76     
77     /**
78      * <code>Map</code> of context values with
79      * the name of the constant as the key.
80      * In this Map user can put name with value
81      * and use this value into your DisplayerConfig (eg :
82      * put context of WEB Application with key contextPath
83      * => and after
84      * you can use value into displayers like this
85      * <img SRC="../../../../${contextPath}/img/calendar.gif" />
86      */

87     protected Map JavaDoc contextValuesMap = new HashMap JavaDoc();
88     
89     /**
90      * <code>FastHashMap</code> of <code>FormSet</code>s stored under
91      * a <code>Locale</code> key.
92      */

93     //protected FastHashMap hFormSets = new FastHashMap();
94
private FormSetView formSet = new FormSetView();
95     
96     /**
97      * Error behaviour
98      */

99     private String JavaDoc errorBehaviour;
100     
101     
102     /**
103      * Create a FormViewResources object from an InputStream.
104      * @param in InputStream to a formview-config.xml configuration file.
105      * It's the client's
106      * responsibility to close this stream.
107      * @throws IOException
108      * @throws SAXException if the formview-config. XML files are not valid or well
109      * formed.
110      */

111     public FormViewResources(InputStream JavaDoc in) throws IOException JavaDoc, SAXException JavaDoc {
112         this(new InputStream JavaDoc[]{in});
113     }
114     
115     /**
116      * Create a FormViewResources object from an InputStream.
117      *
118      * @param streams An array of InputStreams to several formview-config.xml
119      * configuration files that will be read in order and merged into this object.
120      * It's the client's responsibility to close these streams.
121      * @throws IOException
122      * @throws SAXException if the formview-config XML files are not valid or well
123      * formed.
124      */

125     public FormViewResources(InputStream JavaDoc[] streams)
126             throws IOException JavaDoc, SAXException JavaDoc {
127
128         super();
129
130         URL JavaDoc rulesUrl = this.getClass().getResource("digester-rules.xml");
131         Digester digester = DigesterLoader.createDigester(rulesUrl);
132         digester.setNamespaceAware(true);
133         //digester.setValidating(true);
134
digester.setUseContextClassLoader(true);
135
136         // register DTDs
137
/*for (int i = 0; i < registrations.length; i += 2) {
138             URL url = this.getClass().getResource(registrations[i + 1]);
139             if (url != null) {
140                 digester.register(registrations[i], url.toString());
141             }
142         }*/

143
144         for (int i = 0; i < streams.length; i++) {
145             digester.push(this);
146             digester.parse(streams[i]);
147         }
148
149         this.process();
150     }
151     
152     private void process() {
153         hStates.setFast(true);
154         hRolesDefinition.setFast(true);
155         
156         // If Role defintion doesnt exist, instanciate defaultRoleDefintion
157
if (this.defaultRoleDefinition == null)
158             this.defaultRoleDefinition = RoleDefinition.getDefaultRoleDefinition();
159         
160         
161     }
162     
163     public void mergeFormSetWithValidator(ExtendedValidatorResources validatorResources) {
164         
165         /*FormSetView viewFormSet = getFormSet(key);
166         if (viewFormSet == null) {
167             // Create FormSet and add it
168             viewFormSet = new FormSetView();
169             addFormSet(viewFormSet);
170         }*/

171         // Loop for with all form of FormSet of validator
172
FormSet validatorFormSet = validatorResources.getFormSet();
173         Collection JavaDoc forms = validatorFormSet.getForms().values();
174         for (Iterator JavaDoc iter = forms.iterator(); iter.hasNext();) {
175             Form validatorForm = (Form) iter.next();
176             String JavaDoc formName = validatorForm.getName();
177             // Test if formName exist into FormSetView
178
FormView formView = formSet.getForm(formName);
179             boolean isFormViewExist = true;
180             if (formView == null) {
181                 isFormViewExist = false;
182                 // Create view Form and add it to view FormSet
183
formView = new FormView();
184                 formView.setName(formName);
185                 formSet.addForm(formView, Validator.class);
186             }
187             
188             // Update form view with validator information
189
// Loop for field of validator form
190
List JavaDoc validatorFields = validatorForm.getFields();
191             for (Iterator JavaDoc iterator = validatorFields.iterator(); iterator
192                     .hasNext();) {
193                 Field validatorField = (Field) iterator.next();
194                 String JavaDoc property = validatorField.getProperty();
195                 // Test if field exist into FormView
196
FieldView viewField = null;
197                 if (isFormViewExist)
198                     viewField = formView.getField(property);
199                 if (viewField == null) {
200                     // Add view field to form view
201
viewField = new FieldView();
202                     viewField.setProperty(validatorField.getProperty());
203                     // Update view Field with validator field
204
formView.addField(viewField, Validator.class);
205                 }
206                 mergeFieldWithValidator(viewField, validatorField);
207             }
208         }
209     }
210     
211     
212     private void mergeFieldWithValidator(FieldView viewField, Field validatorField) {
213         // REQUIRED
214
boolean isRequired = validatorField.isDependency("required");
215         if (viewField.getRequired() == null) {
216             viewField.setRequired(String.valueOf(isRequired));
217         }
218         // MAXLENGTH
219
String JavaDoc maxlength = validatorField.getVarValue("maxlength");
220         if (viewField.getMaxlength() == null) {
221             viewField.setMaxlength(maxlength);
222         }
223         // DATE
224
boolean isDate = validatorField.isDependency("date");
225         if (viewField.getDate() == null) {
226             viewField.setDate(String.valueOf(isDate));
227         }
228     }
229 //// Add value with to Map context
230

231     public void addContextValue(String JavaDoc key, String JavaDoc value) {
232         // Add ${ and end } the key
233
if(!key.startsWith("${")) {
234             key = "${" + key;
235         }
236         if(!key.startsWith("}")) {
237             key = key + "}";
238         }
239         contextValuesMap.put(key, value);
240     }
241     
242     
243  //// GLOBAL STATE
244
public void addState(State state) {
245         addState(state.getName(), state.getBehaviour());
246     }
247     
248     /**
249      * Add a global state to the resource.
250      */

251     public void addState(String JavaDoc name, String JavaDoc behaviour) {
252         if (log.isDebugEnabled()) {
253             log.debug("Adding Global States => Name : " + name + ", Behaviour : " + behaviour);
254         }
255         this.hStates.put(name, behaviour);
256     }
257
258 //// ROLE DEFINITION
259
public void addRoleDefinition(RoleDefinition roleDefinition) {
260         addRoleDefinition(roleDefinition.getName(), roleDefinition);
261     }
262     
263     /**
264      * Add a role definition to the resource.
265      */

266     public void addRoleDefinition(String JavaDoc name, RoleDefinition roleDefinition) {
267         if (log.isDebugEnabled()) {
268             log.debug("Adding Role Definition => Name : " + name);
269         }
270         this.hRolesDefinition.put(name, roleDefinition);
271         // Test if role definition is default
272
if (this.defaultRoleDefinition == null && roleDefinition.isDefaultRoleDefintion()) {
273             this.defaultRoleDefinition = roleDefinition;
274         }
275     }
276         
277     
278 //// DISPLAYER
279
public void addDisplayer(Displayer displayer) {
280         addDisplayer(displayer.getName(), displayer.getClassName());
281     }
282     
283     /**
284      * Add a displayer to the resource.
285      */

286     public void addDisplayer(String JavaDoc name, String JavaDoc className) {
287         if (log.isDebugEnabled()) {
288             log.debug("Adding Displayer => Name : " + name + ", Class name : " + className);
289         }
290         this.hDisplayers.put(name, className);
291     }
292     
293     public void mergeDisplayersWithDisplayerConfig(DisplayersConfigResources displayersResources) {
294         // Loop for Displayer Config
295
List JavaDoc displayersConfig = displayersResources.getDisplayerConfigs();
296         for (Iterator JavaDoc iter = displayersConfig.iterator(); iter.hasNext();) {
297             DisplayerConfig displayerConfig = (DisplayerConfig) iter.next();
298             addDisplayerClass(displayerConfig);
299         }
300         
301     }
302     
303     public void addDisplayerClass(IHTMLDisplayer htmlDisplayer) {
304         this.lHTMLDisplayers.add(htmlDisplayer);
305         this.hHTMLDisplayers.put(htmlDisplayer.getName(), htmlDisplayer);
306     }
307  //// FORM SET
308

309     
310     /**
311      * Add a <code>FormSet</code> to this <code>FormViewResources</code>
312      * object.
313      */

314     public void addForm(FormView formView) {
315         formSet.addForm(formView);
316         /*String key = this.buildKey(fs);
317         List formsets = (List) hFormSets.get(key);
318
319         if (formsets == null) {
320             formsets = new ArrayList();
321             hFormSets.put(key, formsets);
322         }
323
324         if (!formsets.contains(fs)) {
325             if (log.isDebugEnabled()) {
326                 log.debug("Adding FormSet '" + fs.toString() + "'.");
327             }
328             formsets.add(fs);
329         }*/

330     }
331     
332
333     
334     public FormSetView getFormSet() {
335         return formSet;
336         /*List v = (List) hFormSets.get(key);
337         if (v == null) {
338             return null;
339         }
340         Iterator formsets = v.iterator();
341         while (formsets.hasNext()) {
342             FormSetView set = (FormSetView) formsets.next();
343             return set;
344         }
345         return null;*/

346     }
347     
348     public FormView getForm(String JavaDoc formKey, String JavaDoc state) {
349         FormSetView set = getFormSet();
350         if ((set != null)) {
351             return set.getForm(formKey, state);
352         }
353         return null;
354     }
355     
356     public String JavaDoc getDefaultBehaviour(String JavaDoc defaultState) {
357         return (String JavaDoc)hStates.get(defaultState);
358     }
359  
360     // Process
361

362     public FormView getFormView(String JavaDoc formName, String JavaDoc state) {
363         Map JavaDoc roles = null;
364         return getFormView(formName, state, roles);
365     }
366     
367     public FormView getFormView(String JavaDoc formName, String JavaDoc state, String JavaDoc[] roles) {
368         Map JavaDoc rolesMap = new HashMap JavaDoc();
369         for(int i=0; i< roles.length; i++) {
370             rolesMap.put(roles[i], roles[i]);
371         }
372         return getFormView(formName, state, roles);
373     }
374     /**
375      *
376      * @return
377      */

378     public FormView getFormView(String JavaDoc formName, String JavaDoc state, Map JavaDoc roles) {
379         // Get form with formName and state computed
380
FormView form = this.getForm(formName, state);
381         if (form != null) {
382             // Form exist
383
// Clone form and update field with role
384
FormView formCloned = (FormView)form.clone();
385             
386             // Test if roles exist
387
if (roles != null) {
388                 // @TODO : Compute form with roles
389
}
390             else {
391                 return formCloned;
392             }
393         }
394         return null;
395     }
396 ////Process HTML
397
public String JavaDoc processHtmlContent(FormView form, String JavaDoc state, IPermissionsAdapter permissionsAdapter, String JavaDoc htmlContent) {
398             String JavaDoc defaultBehaviour = this.getDefaultBehaviour(state);
399             OutputDocument outputDocument = new OutputDocument(htmlContent);
400             Source source = new Source(htmlContent);
401             
402             Map JavaDoc indexedFieldMap = new HashMap JavaDoc(); // Map wich contain fields indexed (key=name, value = last index)
403
// Loop for Displayer
404
for (Iterator JavaDoc iter = lHTMLDisplayers.iterator(); iter.hasNext();) {
405                 boolean isHTMLSelect = false;
406                 
407                 IHTMLDisplayer htmlDisplayer = (IHTMLDisplayer) iter.next();
408                 String JavaDoc elementType = htmlDisplayer.getName();
409                 String JavaDoc type1 = elementType;
410                 String JavaDoc type2 = "";
411                 int index = elementType.indexOf("_");
412                 if (index != -1) {
413                     // ex : input_text => type1=input and type2=text
414
type1= elementType.substring(0, index);
415                     type2 = elementType.substring(index + 1, elementType.length());
416                 }
417                 // Test if displayer type is select
418
isHTMLSelect = Tag.SELECT.equalsIgnoreCase(type1);
419                 // Loop for element Type 1
420
List JavaDoc elementsOfType1 = source.findAllElements(type1);
421                 for (Iterator JavaDoc iterElements = elementsOfType1.iterator(); iterElements.hasNext();) {
422 // Get current element (eg : input)
423
Element currentElement = (Element) iterElements.next();
424 // Get attributes of element (ex : type, name...)
425
Attributes currentAttributes = currentElement.getAttributes();
426                     if (type2.length() > 0) {
427                         // Test if Input is with good type (text, hidden...)
428
String JavaDoc attributeType = currentAttributes.getValue("type");
429                         if (!attributeType.equalsIgnoreCase(type2))
430                             continue;
431                     }
432                     
433                     String JavaDoc attributesName = htmlDisplayer.getAttributesName();
434                     if (attributesName == null || attributesName.length() <1)
435                         attributesName = "name";
436                     StringTokenizer JavaDoc attributesNameToken = new StringTokenizer JavaDoc(attributesName, ",");
437 // Loop for attributes name (eg : name, id)
438
while (attributesNameToken.hasMoreElements())
439                     {
440                         String JavaDoc attributeName = (String JavaDoc)attributesNameToken.nextElement();
441                         // Get name of current element
442
String JavaDoc elementName = currentAttributes.getValue(attributeName);
443                         // Find field into form with name of current element
444
FieldView field = null;
445                         if (form != null && elementName != null) {
446                             field = form.getField(elementName, state);
447                             if (field != null && field.isIndexed()) {
448                                 // get last index of this field
449
Integer JavaDoc fieldIndex = (Integer JavaDoc)indexedFieldMap.get(elementName);
450                                 if (fieldIndex == null) {
451                                     fieldIndex = new Integer JavaDoc(0);
452                                 }
453                                 // Get field with index
454
FieldView fieldWithIndex = field.getFieldWithIndex(fieldIndex);
455                                 if (fieldWithIndex != null)
456                                     field = fieldWithIndex;
457                                 indexedFieldMap.put(elementName, new Integer JavaDoc(fieldIndex.intValue() + 1));
458                                 
459                             }
460                         }
461                         // Construct Map with context values (ContextPath, value of maxlength => ex to replace ${maxlength} by value)
462
Map JavaDoc allContextValuesMap = getContextValuesMap(field);
463                         // If HTML element is select, update context values Map
464
// with option code and value of select HTML
465
if (isHTMLSelect) {
466                             updateContextValuesMapWithHTMLSelect(currentElement, allContextValuesMap);
467                         }
468                         else {
469                             // Put value of HTML element into context
470
String JavaDoc elementValue = currentAttributes.getValue("value");
471                             if (elementValue != null) {
472                                 allContextValuesMap.put("${elementValue}", elementValue);
473                             }
474                         }
475                         // Put value of attribute of html element into context
476
updateContextValuesMapWithAttributesHTMLElement(currentElement, allContextValuesMap);
477                         
478                         
479                         // Update Map with Name of element
480
allContextValuesMap.put("${elementName}", "");
481                         if (elementName != null)
482                             allContextValuesMap.put("${elementName}", elementName);
483                         
484                         // Compute Role
485
if (permissionsAdapter != null && field != null) {
486                             if (field.getRoles() != null && field.getRoles().length() > 0) {
487                                 RoleDefinition fieldRoleDefinition = null;
488                                 // Field must be compute with role
489
// Test if field is associated with Rode defintion
490
String JavaDoc roleDefinitionName = field.getRoleDefinitionName();
491                                 if (roleDefinitionName != null && roleDefinitionName.length() > 0 ) {
492                                     fieldRoleDefinition = (RoleDefinition)hRolesDefinition.get(roleDefinitionName);
493                                 }
494                                 if (fieldRoleDefinition == null) {
495                                     fieldRoleDefinition = defaultRoleDefinition;
496                                 }
497                                 String JavaDoc behaviour = permissionsAdapter.getBehaviour(field, defaultBehaviour, fieldRoleDefinition);
498                                 if (behaviour != null) {
499                                     field.setBehaviour(behaviour);
500                                 }
501                             }
502                         }
503                         
504                         // Update Element with HTML Displayer
505
htmlDisplayer.processHTML(field, defaultBehaviour, allContextValuesMap, currentElement, outputDocument);
506                     }
507                 }
508             }
509         return outputDocument.toString();
510     }
511     
512     
513     public Map JavaDoc getContextValuesMap(FieldView field) {
514         if (field == null) {
515             return contextValuesMap;
516         }
517         // field exist, merge value of field with contextValuesMap
518
Map JavaDoc allContextValuesMap = new HashMap JavaDoc(contextValuesMap);
519         allContextValuesMap.put("${maxlength}", field.getMaxlength());
520         return allContextValuesMap;
521     }
522     
523     
524     private void updateContextValuesMapWithHTMLSelect(Element selectElement, Map JavaDoc contextValuesMap) {
525         Source selectSource = new Source(selectElement);
526         // Loop for <option> element to get value and label of selected option
527
int i=0;
528         List JavaDoc optionsSelected = null;
529         Element firstOption = null;
530         // Test if Select is Multiple
531
boolean isMultiple = false;
532         Attributes selectAttributes = selectElement.getAttributes();
533         if (selectAttributes != null && selectAttributes.getValue("multiple") != null) {
534             isMultiple = true;
535         }
536         
537         List JavaDoc options = selectSource.findAllElements(Tag.OPTION);
538         if (options != null)
539         {
540             for (Iterator JavaDoc iter = options.iterator(); iter.hasNext(); i++) {
541                 Element option = (Element) iter.next();
542                 if (i ==0) {
543                     firstOption = option;
544                 }
545                 Attributes optionAttributes = option.getAttributes();
546                 if (optionAttributes != null) {
547                     boolean isOptionSelected = (optionAttributes.getValue("selected") != null);
548                     if (isOptionSelected) {
549                         String JavaDoc optionValue = optionAttributes.getValue("value");
550                         String JavaDoc optionLabel = option.getContent().toString();
551                         if (optionsSelected == null)
552                             optionsSelected = new ArrayList JavaDoc();
553                         optionsSelected.add(new LabelValue(optionLabel, optionValue));
554                     }
555                     
556                     /*if (i ==0) {
557                         String optionValue = optionAttributes.getValue("value");
558                         String optionLabel = option.getContent().toString();
559                         putOptionToMap(contextValuesMap, optionValue, optionLabel);
560                     }
561                     else {
562                         if (isOptionSelected) {
563                             String optionValue = optionAttributes.getValue("value");
564                             String optionLabel = option.getContent().toString();
565                             putOptionToMap(contextValuesMap, optionValue, optionLabel);
566                             break;
567                         }
568                     }*/

569                 }
570             }
571             if (optionsSelected == null && firstOption != null) {
572                 Attributes optionAttributes = firstOption.getAttributes();
573                 if (optionAttributes != null) {
574                     String JavaDoc optionValue = optionAttributes.getValue("value");
575                     String JavaDoc optionLabel = firstOption.getContent().toString();
576                     if (optionsSelected == null)
577                         optionsSelected = new ArrayList JavaDoc();
578                     optionsSelected.add(new LabelValue(optionLabel, optionValue));
579                 }
580             }
581             
582             if (!isMultiple && optionsSelected != null && optionsSelected.size() > 0) {
583                 LabelValue firstLabelvalue = (LabelValue)optionsSelected.get(0);
584                 putOptionToMap(contextValuesMap, firstLabelvalue.getValue(), firstLabelvalue.getLabel());
585             }
586             else {
587                 contextValuesMap.put("${optionsSelected}", optionsSelected);
588             }
589         }
590     }
591     
592
593     
594     private void putOptionToMap(Map JavaDoc contextValuesMap, String JavaDoc optionValue, String JavaDoc optionLabel) {
595         contextValuesMap.put("${optionValue}", optionValue);
596         contextValuesMap.put("${optionLabel}", optionLabel);
597     }
598     
599     private void updateContextValuesMapWithAttributesHTMLElement(Element htmlElement, Map JavaDoc contextValuesMap) {
600         Attributes attributes = htmlElement.getAttributes();
601         for (Iterator JavaDoc iter = attributes.iterator(); iter.hasNext();) {
602             Attribute attribute = (Attribute) iter.next();
603             contextValuesMap.put("${" + attribute.getName() + "}", attribute.getValue());
604         }
605     }
606     
607     public String JavaDoc getErrorBehaviour() {
608         if (errorBehaviour == null)
609             return FormViewConstants.BEHAVIOUR_ERROR;
610         return errorBehaviour;
611     }
612
613     public void setErrorBehaviour(String JavaDoc errorBehaviour) {
614         this.errorBehaviour = errorBehaviour;
615     }
616     
617     
618     
619     
620 }
621
Popular Tags