KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > myfaces > wap > renderkit > RendererUtils


1 /*
2  * Copyright 2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.apache.myfaces.wap.renderkit;
17
18 import java.lang.reflect.Array JavaDoc;
19 import java.net.URLEncoder JavaDoc;
20 import java.util.ArrayList JavaDoc;
21 import java.util.HashSet JavaDoc;
22 import java.util.Iterator JavaDoc;
23 import java.util.List JavaDoc;
24 import java.util.Map JavaDoc;
25 import java.util.Set JavaDoc;
26
27 import javax.faces.FacesException;
28 import javax.faces.application.ViewHandler;
29 import javax.faces.component.EditableValueHolder;
30 import javax.faces.component.UIComponent;
31 import javax.faces.component.UISelectMany;
32 import javax.faces.component.ValueHolder;
33 import javax.faces.context.FacesContext;
34 import javax.faces.context.ResponseWriter;
35 import javax.faces.convert.Converter;
36 import javax.faces.el.ValueBinding;
37
38 import org.apache.commons.logging.Log;
39 import org.apache.commons.logging.LogFactory;
40
41 /**
42  *
43  * @author <a HREF="mailto:Jiri.Zaloudek@ivancice.cz">Jiri Zaloudek</a> (latest modification by $Author: matzew $)
44  * @version $Revision: 1.1 $ $Date: 2004/12/30 09:37:27 $
45  * $Log: RendererUtils.java,v $
46  * Revision 1.1 2004/12/30 09:37:27 matzew
47  * added a new RenderKit for WML. Thanks to Jirí Žaloudek
48  *
49  */

50
51 public class RendererUtils {
52     private static Log log = LogFactory.getLog(RendererUtils.class);
53     
54     public static String JavaDoc getCurrentUrl(FacesContext context){
55         ViewHandler viewHandler = context.getApplication().getViewHandler();
56         String JavaDoc viewId = context.getViewRoot().getViewId();
57         String JavaDoc actionUrl = viewHandler.getActionURL(context, viewId);
58         String JavaDoc urlLink = context.getExternalContext().encodeActionURL(actionUrl);
59         return(urlLink);
60     }
61     
62     /** write attribute */
63     public static void writeAttribute(String JavaDoc attribute, Object JavaDoc value, ResponseWriter writer){
64         log.debug("attribute " + attribute + ": " + value);
65         
66         try {
67             if (value != null)
68                 writer.writeAttribute(attribute, value, null);
69         } catch (java.io.IOException JavaDoc ex) {
70             log.error("Error write attribute '" + attribute + " value: '" + value + "'", ex.getCause());
71         }
72     }
73     
74     /** Converts submitted value to Object (local component value) */
75     public static Object JavaDoc convertToObject(FacesContext context, UIComponent component){
76         if (!(component instanceof EditableValueHolder))
77             throw new IllegalArgumentException JavaDoc("Expected component of type EditableValueHolder. Cannot convert submitted value.");
78         
79         EditableValueHolder holder = (EditableValueHolder)component;
80         
81         if (!(holder.getSubmittedValue() instanceof String JavaDoc))
82             throw new ClassCastException JavaDoc("Submitted value must be a String value.");
83         
84         String JavaDoc submittedValue = (String JavaDoc)holder.getSubmittedValue();
85         Converter conv = holder.getConverter();
86         
87         // no conversion needed
88
if (conv == null) return(submittedValue);
89         
90         return(conv.getAsObject(context, component, submittedValue));
91     }
92     
93     /** Converts value of compoent to String */
94     public static String JavaDoc convertToString(FacesContext facesContext, UIComponent component) {
95         if (!(component instanceof ValueHolder)) {
96             throw new IllegalArgumentException JavaDoc("Component is not a ValueHolder");
97         }
98         
99         if (component instanceof EditableValueHolder) {
100             Object JavaDoc submittedValue = ((EditableValueHolder)component).getSubmittedValue();
101             if (submittedValue != null) {
102                 if (submittedValue instanceof String JavaDoc) {
103                     return (String JavaDoc)submittedValue;
104                 }
105                 else {
106                     throw new IllegalArgumentException JavaDoc("Expected submitted value of type String");
107                 }
108             }
109         }
110         
111         Object JavaDoc value = ((ValueHolder)component).getValue();
112         
113         Converter converter = ((ValueHolder)component).getConverter();
114         if (converter == null && value != null) {
115             if (value instanceof String JavaDoc) {
116                 return (String JavaDoc) value;
117             }
118             
119             try {
120                 converter = facesContext.getApplication().createConverter(value.getClass());
121             }
122             catch (FacesException e) {
123                 log.error("No converter for class " + value.getClass().getName() + " found (component id=" + component.getId() + ").");
124                 // converter stays null
125
}
126         }
127         
128         if (converter == null) {
129             if (value == null) {
130                 return "";
131             }
132             else {
133                 return value.toString();
134             }
135         }
136         else {
137             return converter.getAsString(facesContext, component, value);
138         }
139     }
140     
141     public static Object JavaDoc convertUISelectManyToObject(FacesContext context, UISelectMany component, Object JavaDoc value) {
142         if (!(value instanceof String JavaDoc[]))
143             throw new ClassCastException JavaDoc("Selected value must be a String[] type.");
144         
145         String JavaDoc[] submittedValue = (String JavaDoc[])value;
146         
147         ValueBinding vb = component.getValueBinding("value");
148         Class JavaDoc valueType = null;
149         Class JavaDoc arrayComponentType = null;
150         if (vb != null) {
151             valueType = vb.getType(context);
152             if (valueType != null && valueType.isArray()) {
153                 arrayComponentType = valueType.getComponentType();
154             }
155         }
156         
157         Converter converter = component.getConverter();
158         if (converter == null) {
159             if (valueType == null) {
160                 // No converter, and no idea of expected type
161
// --> return the submitted String array
162
return submittedValue;
163             }
164             
165             if (List JavaDoc.class.isAssignableFrom(valueType)) {
166                 // expected type is a List
167
// --> according to javadoc of UISelectMany we assume that the element type
168
// is java.lang.String, and copy the String array to a new List
169
int len = submittedValue.length;
170                 List JavaDoc lst = new ArrayList JavaDoc(len);
171                 for (int i = 0; i < len; i++) {
172                     lst.add(submittedValue[i]);
173                 }
174                 return lst;
175             }
176             
177             if (arrayComponentType == null) {
178                 throw new IllegalArgumentException JavaDoc("ValueBinding for UISelectMany must be of type List or Array");
179             }
180             
181             if (String JavaDoc.class.equals(arrayComponentType)) return submittedValue; //No conversion needed for String type
182
if (Object JavaDoc.class.equals(arrayComponentType)) return submittedValue; //No conversion for Object class
183

184             try {
185                 converter = context.getApplication().createConverter(arrayComponentType);
186             }
187             catch (FacesException e) {
188                 log.error("No Converter for type " + arrayComponentType.getName() + " found");
189                 return submittedValue;
190             }
191         }
192         
193         // Now, we have a converter...
194
if (valueType == null) {
195             // ...but have no idea of expected type
196
// --> so let's convert it to an Object array
197
int len = submittedValue.length;
198             Object JavaDoc[] convertedValues = new Object JavaDoc[len];
199             for (int i = 0; i < len; i++) {
200                 convertedValues[i] = converter.getAsObject(context, component, submittedValue[i]);
201             }
202             return convertedValues;
203         }
204         
205         if (List JavaDoc.class.isAssignableFrom(valueType)) {
206             // Curious case: According to specs we should assume, that the element type
207
// of this List is java.lang.String. But there is a Converter set for this
208
// component. Because the user must know what he is doing, we will convert the values.
209
int len = submittedValue.length;
210             List JavaDoc lst = new ArrayList JavaDoc(len);
211             for (int i = 0; i < len; i++) {
212                 lst.add(converter.getAsObject(context, component, submittedValue[i]));
213             }
214             return lst;
215         }
216         
217         if (arrayComponentType == null) {
218             throw new IllegalArgumentException JavaDoc("ValueBinding for UISelectMany must be of type List or Array");
219         }
220         
221         if (arrayComponentType.isPrimitive()) {
222             //primitive array
223
int len = submittedValue.length;
224             Object JavaDoc convertedValues = Array.newInstance(arrayComponentType, len);
225             for (int i = 0; i < len; i++) {
226                 Array.set(convertedValues, i, converter.getAsObject(context, component, submittedValue[i]));
227             }
228             return convertedValues;
229         }
230         else {
231             //Object array
232
int len = submittedValue.length;
233             Object JavaDoc[] convertedValues = new Object JavaDoc[len];
234             for (int i = 0; i < len; i++) {
235                 convertedValues[i] = converter.getAsObject(context, component, submittedValue[i]);
236             }
237             return convertedValues;
238         }
239     }
240     
241     public static void renderChildren(FacesContext context, UIComponent component) throws java.io.IOException JavaDoc {
242         if (component != null && component.isRendered()){
243             Iterator JavaDoc iter = component.getChildren().iterator();
244             while (iter.hasNext()){
245                 UIComponent child = (UIComponent)iter.next();
246                 renderChild(context, child);
247             }
248         }
249     }
250     
251     public static void renderChild(FacesContext context, UIComponent child) throws java.io.IOException JavaDoc {
252         if (child == null || !child.isRendered()) return;
253         
254         child.encodeBegin(context);
255         if (child.getRendersChildren()) {
256             child.encodeChildren(context);
257         }
258         else {
259             renderChildren(context, child);
260         }
261         child.encodeEnd(context);
262         
263         if (!child.isRendered())
264         {
265             return;
266         }
267     }
268     
269     /** Insert parameter and its value to href. Insert correct separator '?' or '&amp;' */
270     public static String JavaDoc insertGetParam(String JavaDoc href, String JavaDoc param, String JavaDoc value, String JavaDoc encoding) throws java.io.IOException JavaDoc {
271         href += (href.indexOf('?') == -1) ? "?" : "&amp;";
272         
273         href += URLEncoder.encode(param, encoding);
274         href += '=';
275         href += URLEncoder.encode(value, encoding);
276         
277         return (href);
278     }
279     
280     /** Returns all input components(input, select, option...) from the list of components(type UICommponents).
281      * @param components the list of components.
282      * @return Set of UIComponent - all input components from the list. If no input tag was found, return empty set.
283      */

284     public static Set JavaDoc getInputTags(List JavaDoc components){
285         Set JavaDoc inputTags = new HashSet JavaDoc();
286         
287         Iterator JavaDoc iter = components.iterator();
288         
289         while (iter.hasNext()){
290             UIComponent comp = (UIComponent)iter.next();
291             String JavaDoc family = comp.getFamily();
292             log.debug("processing component family:" + family);
293             
294             if (isInputComponent(family)){
295                 inputTags.add(comp);
296             }
297         }
298         return(inputTags);
299     }
300     
301     
302     private static boolean isInputComponent(String JavaDoc name){
303         String JavaDoc INPUT_COMPONENTS_FAMILY[] = {"UIInput", "UISelectItems", "UISelectBoolean", "UISelectOne", "UISelectMany"};
304         
305         for (int i = 0; i < INPUT_COMPONENTS_FAMILY.length; i++){
306             if (name != null && name.equals(INPUT_COMPONENTS_FAMILY[i]))
307                 return (true);
308         }
309         return (false);
310     }
311     
312     public static String JavaDoc getAttribute(UIComponent comp, String JavaDoc attribute){
313         Map JavaDoc attrs = comp.getAttributes();
314         
315         Iterator JavaDoc iter = attrs.keySet().iterator();
316         while (iter.hasNext())
317             log.debug("attr:" + iter.next());
318         
319         String JavaDoc value = (String JavaDoc)attrs.get(attribute);
320         if (value != null){
321             log.debug("Contains name:" + value);
322             return(value);
323         }
324         
325         return(null);
326     }
327 }
328
Popular Tags