KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > barracuda > contrib > sam > xmlform > XmlFormMap


1 /*
2  * Copyright (C) 2003 Stefan Armbruster [stefan@armbruster-it.de]
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  *
18  * $Id: XmlFormMap.java,v 1.3 2004/02/01 05:16:27 christianc Exp $
19  */

20 package org.enhydra.barracuda.contrib.sam.xmlform;
21
22 import java.util.*;
23 import java.lang.reflect.*;
24
25 import org.enhydra.barracuda.contrib.dbroggisch.repopulation.*;
26 import org.enhydra.barracuda.core.event.*;
27 import org.enhydra.barracuda.core.comp.*;
28 import org.enhydra.barracuda.core.forms.*;
29 import org.enhydra.barracuda.core.forms.validators.*;
30
31 import org.enhydra.barracuda.contrib.sam.xmlform.dtd.*;
32 import org.enhydra.barracuda.contrib.sam.data.*;
33
34 import org.apache.log4j.*;
35
36 /** Provide a FormMap based on a XML description */
37 public class XmlFormMap extends RepopulationFormMap {
38
39     protected static Logger logger = Logger.getLogger(XmlFormMap.class.getName());
40
41     public static final String JavaDoc GROUP = "GROUP";
42     protected String JavaDoc formName;
43     protected Form form;
44
45     /** instatiate a new XML Form. First the XML Form description is loaded by calling
46      * {@link XmlFormFactory }. For each field, if required a validator is created and
47      * the pre-set values are set according the DataObject
48      * @param formName filename of the form, used to call {@link XmlFormFactory}
49      * @param dataObject {@link DataObject} associated with the form
50      * @param name internal name of the form
51      */

52     public XmlFormMap(ControlEventContext context, String JavaDoc formName, String JavaDoc name, DataObject dataObject) {
53         this.formName = formName;
54         setName(name);
55         form = XmlFormFactory.get(context, this.formName);
56         Iterator iter = form.getElementList().iterator();
57         while (iter.hasNext()) {
58             Element ele = (Element) iter.next();
59             Object JavaDoc deflt = null;
60             FormElement fe = getFormElement(ele, ele.getName());
61             if (dataObject != null) {
62                 try {
63                     deflt = dataObject.get(ele.getName());
64                     if (deflt instanceof List) {
65
66                         // if DataObject's get method returns a List (instead of String), we know that this is a multi-value field
67
List defltList = (List)deflt;
68                         SelectFormElement sfe = (SelectFormElement)fe;
69                         ListSelectionModel defaults = new DefaultListSelectionModel();
70                         defaults.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
71
72                         // the list returned from get is a list of oids. These must be converted in select box indexes
73
ListModel lm = sfe.getListModel();
74                         for (int i = 0; i< lm.getSize(); i++) {
75                             DefaultItemMap item = (DefaultItemMap)lm.getItemAt(i);
76                             if (defltList.contains(item.getKey())) defaults.addSelectionInterval(i,i);
77                         }
78                         sfe.setListSelectionModel(defaults);
79
80                     } else {
81                         fe.setOrigVal(deflt);
82                         if (logger.isDebugEnabled()) logger.debug("default value for element " + ele.getName() + " is " + deflt);
83                     }
84                 } catch (DataObjectException ex) {
85                     logger.error(ex.getMessage(), ex);
86                 }
87             }
88             if (logger.isDebugEnabled()) logger.debug("Adding " + ele.getName() + " to formmap.");
89             //fe.setOrigVal(xmlMap.get(ele.getName()));
90

91             fe.setValidator( buildValidatorObject(ele.getValidator()));
92             defineElement(fe);
93         }
94     }
95
96     private static Map primitiveClasses = new Hashtable();
97
98     static {
99         primitiveClasses.put("int", Integer.TYPE);
100         primitiveClasses.put("float", Float.TYPE);
101         primitiveClasses.put("double", Double.TYPE);
102         primitiveClasses.put("long", Long.TYPE);
103         primitiveClasses.put("short", Short.TYPE);
104         primitiveClasses.put("boolean", Boolean.TYPE);
105         primitiveClasses.put("byte", Byte.TYPE);
106         primitiveClasses.put("char", Character.TYPE);
107     }
108
109     private Class JavaDoc getClassWithPrimitive(String JavaDoc name)
110     throws ClassNotFoundException JavaDoc {
111         Class JavaDoc c = (Class JavaDoc) primitiveClasses.get(name);
112         if (c==null) c = Class.forName(name);
113         return c;
114     }
115
116     private Object JavaDoc initialize(Class JavaDoc c, String JavaDoc value)
117     throws NoSuchMethodException JavaDoc, InstantiationException JavaDoc, IllegalAccessException JavaDoc, InvocationTargetException {
118         Class JavaDoc[] types = new Class JavaDoc[1];
119         types[0] = String JavaDoc.class;
120         Object JavaDoc[] para = new Object JavaDoc[1];
121         para[0] = value;
122         Constructor con = c.getConstructor(types);
123         return con.newInstance(para);
124     }
125
126
127     /** recursivly called to construct a validator hierarchy. Internally, the reflection API is used here */
128     protected FormValidator buildValidatorObject(Validator validator) {
129         if (validator == null) return null;
130
131         List children = new Vector();
132
133         //if (validator.getValidatorList() != null) {
134
Iterator iter = validator.getValidatorList().iterator();
135         while (iter.hasNext()) {
136             Validator v = (Validator) iter.next();
137             // get sub-validtors recursively
138
children.add(buildValidatorObject(v));
139         }
140         //}
141
try {
142             // use reflection to instanciate validator
143
logger.info("Trying to create Validator " + validator.getClassname());
144             Class JavaDoc validatorClass = Class.forName(validator.getClassname());
145             if (logger.isDebugEnabled()) logger.debug("Class successfully found");
146
147             // find matching constructor, first the childvalidators and second the specific parameters are appendendA
148
List para = validator.getParaList();
149
150             int size = children.size() + para.size();
151             if (logger.isDebugEnabled()) logger.debug("constructor will have " + size + " arguments");
152             Class JavaDoc[] types = new Class JavaDoc[size];
153             Object JavaDoc[] values = new Object JavaDoc[size];
154             int counter = 0;
155             // insert constructor parameter from children formvalidators
156
iter = children.iterator();
157             while (iter.hasNext()) {
158                 Object JavaDoc o = iter.next();
159                 types[counter] = FormValidator.class;
160                 values[counter++] = o;
161             }
162             // insert construcor parameter from <para> elements
163
iter = para.iterator();
164             while (iter.hasNext()) {
165                 Para p = (Para)iter.next();
166                 types[counter] = getClassWithPrimitive(p.getClassname());
167                 values[counter] = initialize(types[counter], p.getValue());
168                 counter++;
169                 if (logger.isDebugEnabled()) logger.debug("counter is " + counter);
170             }
171
172             Constructor c = validatorClass.getConstructor(types);
173             if (logger.isDebugEnabled()) logger.debug("Constructor with " + children.size() + " arguments found");
174             // invoke the constructor
175
return (FormValidator)c.newInstance(values);
176         } catch (Exception JavaDoc ex) {
177             logger.error(ex.getMessage(), ex);
178             return null;
179         }
180     }
181
182     /** generate a FormElement for a given Element from the XML description */
183     protected FormElement getFormElement(Element ele, String JavaDoc name) {
184         FormElement fe = null;
185         if (ele.getText() != null)
186             fe = new DefaultFormElement(name, FormType.STRING, null);
187         else if ( ele.getTextarea() != null) {
188             fe = new TextAreaFormElement(name, FormType.STRING, null);
189             logger.debug("creating a textarea element"+name);
190         }
191         else if ( ele.getSelect() != null) {
192             Select sel = ele.getSelect();
193             DefaultListModel lm = new DefaultListModel();
194             // call RMI to get select box contents
195
if (sel.getXmlclass() != null) {
196                 logger.debug("class is " + sel.getXmlclass());
197                 try {
198                     Class JavaDoc c = Class.forName(sel.getXmlclass());
199                     Class JavaDoc[] params = new Class JavaDoc[0];
200                     Object JavaDoc[] args = new Object JavaDoc[0];
201                     Method method = c.getMethod(sel.getMethod(), params);
202                     Object JavaDoc result = method.invoke(null, args);
203                     logger.debug("result is " + result.getClass().getName());
204                     if (result instanceof List) {
205                         List l = (List)result;
206                         Iterator rmiIter = l.iterator();
207                         while (rmiIter.hasNext()) lm.add(rmiIter.next());
208                     }
209                 } catch (Exception JavaDoc e) {
210                     logger.error(e.getMessage(),e);
211                 }
212             }
213             Iterator subIter = ele.getSelect().getOptionList().iterator();
214             while (subIter.hasNext()) {
215                 Option opt = (Option)subIter.next();
216                 lm.add(new DefaultItemMap(opt.getValue2(), opt.getValue()));
217             }
218             //fe = new SelectFormElement(lm, name, FormType.STRING, null, new NotNullValidator("Bitte wählen Sie im Feld " + ele.getLabel() + " eine Alternative aus."), false);
219
boolean hasMulti = false;
220             String JavaDoc m = sel.getMultivalue();
221             if ( (m!=null) && (m.equals("true") || m.equals("yes"))) hasMulti = true;
222             fe = new SelectFormElement(lm, name, FormType.STRING, null, null, hasMulti);
223         } else if (ele.getHidden() != null) {
224             fe = new DefaultFormElement(name, FormType.STRING, null);
225         }
226         return fe;
227     }
228
229     public Form getForm() {
230         return form;
231     }
232
233 }
234
Popular Tags