KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > icesoft > faces > component > util > CustomComponentUtils


1 /*
2  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
3  *
4  * "The contents of this file are subject to the Mozilla Public License
5  * Version 1.1 (the "License"); you may not use this file except in
6  * compliance with the License. You may obtain a copy of the License at
7  * http://www.mozilla.org/MPL/
8  *
9  * Software distributed under the License is distributed on an "AS IS"
10  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
11  * License for the specific language governing rights and limitations under
12  * the License.
13  *
14  * The Original Code is ICEfaces 1.5 open source software code, released
15  * November 5, 2006. The Initial Developer of the Original Code is ICEsoft
16  * Technologies Canada, Corp. Portions created by ICEsoft are Copyright (C)
17  * 2004-2006 ICEsoft Technologies Canada, Corp. All Rights Reserved.
18  *
19  * Contributor(s): _____________________.
20  *
21  * Alternatively, the contents of this file may be used under the terms of
22  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"
23  * License), in which case the provisions of the LGPL License are
24  * applicable instead of those above. If you wish to allow use of your
25  * version of this file only under the terms of the LGPL License and not to
26  * allow others to use your version of this file under the MPL, indicate
27  * your decision by deleting the provisions above and replace them with
28  * the notice and other provisions required by the LGPL License. If you do
29  * not delete the provisions above, a recipient may use your version of
30  * this file under either the MPL or the LGPL License."
31  *
32  */

33 /* Original copyright
34  * Copyright 2004 The Apache Software Foundation.
35  *
36  * Licensed under the Apache License, Version 2.0 (the "License");
37  * you may not use this file except in compliance with the License.
38  * You may obtain a copy of the License at
39  *
40  * http://www.apache.org/licenses/LICENSE-2.0
41  *
42  * Unless required by applicable law or agreed to in writing, software
43  * distributed under the License is distributed on an "AS IS" BASIS,
44  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
45  * See the License for the specific language governing permissions and
46  * limitations under the License.
47  */

48 package com.icesoft.faces.component.util;
49
50 import com.icesoft.faces.renderkit.dom_html_basic.FormRenderer;
51 import org.apache.commons.logging.Log;
52 import org.apache.commons.logging.LogFactory;
53
54 import javax.faces.FacesException;
55 import javax.faces.component.EditableValueHolder;
56 import javax.faces.component.NamingContainer;
57 import javax.faces.component.UIComponent;
58 import javax.faces.component.UIForm;
59 import javax.faces.component.UIViewRoot;
60 import javax.faces.component.ValueHolder;
61 import javax.faces.component.html.HtmlInputText;
62 import javax.faces.context.FacesContext;
63 import javax.faces.convert.Converter;
64 import javax.faces.el.PropertyNotFoundException;
65 import java.io.IOException JavaDoc;
66 import java.util.Date JavaDoc;
67 import java.util.HashSet JavaDoc;
68 import java.util.Iterator JavaDoc;
69 import java.util.Map JavaDoc;
70 import java.util.Set JavaDoc;
71 import java.util.StringTokenizer JavaDoc;
72
73 public class CustomComponentUtils {
74
75     private static final String JavaDoc HIDDEN_COMMAND_INPUTS_SET_ATTR
76             = FormRenderer.class.getName() + ".HIDDEN_COMMAND_INPUTS_SET";
77     public static final String JavaDoc HIDDEN_COMMANDLINK_FIELD_NAME = "_link_hidden_";
78     public static final String JavaDoc FOOTER_CLASS_ATTR = "footerClass";
79     public static final String JavaDoc HEADER_CLASS_ATTR = "headerClass";
80     public static final String JavaDoc[] EMPTY_STRING_ARRAY = new String JavaDoc[0];
81     public static final String JavaDoc EMPTY_STRING = new String JavaDoc();
82     private static final String JavaDoc HIDDEN_TREE_NAV_FIELD_NAME = "_idtn";
83     private static final String JavaDoc HIDDEN_TREE_ACTION_FIELD_NAME = "_idta";
84     private static final Log log =
85             LogFactory.getLog(CustomComponentUtils.class);
86
87     public static void restoreAncestorState(UIComponent uiComponent) {
88         uiComponent.setId(uiComponent.getId());
89         if ((uiComponent = uiComponent.getParent()) != null) {
90             restoreAncestorState(uiComponent);
91         }
92     }
93
94     public static void restoreDescendentState(UIComponent uiComponent) {
95         uiComponent.setId(uiComponent.getId());
96         Iterator JavaDoc it = uiComponent.getFacetsAndChildren();
97         while (it.hasNext()) {
98             UIComponent next = (UIComponent) it.next();
99             restoreDescendentState(next);
100         }
101     }
102
103
104     public static String JavaDoc getStringValue(FacesContext facesContext,
105                                         UIComponent component) {
106         try {
107             if (!(component instanceof ValueHolder)) {
108                 throw new IllegalArgumentException JavaDoc("Component : " +
109                                                    getPathToComponent(
110                                                            component) +
111                                                                       "is not a ValueHolder");
112             }
113
114             if (component instanceof EditableValueHolder) {
115                 Object JavaDoc submittedValue =
116                         ((EditableValueHolder) component).getSubmittedValue();
117                 if (submittedValue != null) {
118                     if (submittedValue instanceof String JavaDoc) {
119                         return (String JavaDoc) submittedValue;
120                     } else {
121                         throw new IllegalArgumentException JavaDoc(
122                                 "Expected submitted value of type String for component : "
123                                 + getPathToComponent(component));
124                     }
125                 }
126             }
127
128             Object JavaDoc value = ((ValueHolder) component).getValue();
129
130             Converter converter = ((ValueHolder) component).getConverter();
131             if (converter == null && value != null) {
132                 if (value instanceof String JavaDoc) {
133                     return (String JavaDoc) value;
134                 }
135
136                 try {
137                     converter = facesContext.getApplication()
138                             .createConverter(value.getClass());
139                 }
140                 catch (FacesException e) {
141
142                     log.error("No converter for class " +
143                               value.getClass().getName() +
144                               " found (component id=" + component.getId() +
145                               ").", e);
146                     // converter stays null
147
}
148             }
149
150             if (converter == null) {
151                 if (value == null) {
152                     return "";
153                 } else {
154                     return value.toString();
155                 }
156             } else {
157                 return converter.getAsString(facesContext, component, value);
158             }
159         }
160         catch (PropertyNotFoundException ex) {
161             log.error("Property not found - called by component : " +
162                       getPathToComponent(component), ex);
163             throw ex;
164         }
165     }
166
167
168     public static String JavaDoc getPathToComponent(UIComponent component) {
169         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
170
171         if (component == null) {
172             buf.append("{Component-Path : ");
173             buf.append("[null]}");
174             return buf.toString();
175         }
176
177         getPathToComponent(component, buf);
178
179         buf.insert(0, "{Component-Path : ");
180         buf.append("}");
181
182         return buf.toString();
183     }
184
185     private static void getPathToComponent(UIComponent component,
186                                            StringBuffer JavaDoc buf) {
187         if (component == null) {
188             return;
189         }
190
191         StringBuffer JavaDoc intBuf = new StringBuffer JavaDoc();
192
193         intBuf.append("[Class: ");
194         intBuf.append(component.getClass().getName());
195         if (component instanceof UIViewRoot) {
196             intBuf.append(",ViewId: ");
197             intBuf.append(((UIViewRoot) component).getViewId());
198         } else {
199             intBuf.append(",Id: ");
200             intBuf.append(component.getId());
201         }
202         intBuf.append("]");
203
204         buf.insert(0, intBuf);
205
206         if (component != null) {
207             getPathToComponent(component.getParent(), buf);
208         }
209     }
210
211
212     public static void addHiddenCommandParameter(UIComponent form,
213                                                  String JavaDoc paramName) {
214         Set JavaDoc set =
215                 (Set JavaDoc) form.getAttributes().get(HIDDEN_COMMAND_INPUTS_SET_ATTR);
216         if (set == null) {
217             set = new HashSet JavaDoc();
218             form.getAttributes().put(HIDDEN_COMMAND_INPUTS_SET_ATTR, set);
219         }
220         set.add(paramName);
221     }
222
223     public static String JavaDoc getHiddenCommandLinkFieldName(String JavaDoc formName) {
224         return formName + NamingContainer.SEPARATOR_CHAR
225                + HIDDEN_COMMANDLINK_FIELD_NAME;
226     }
227
228     public static String JavaDoc getHiddenTreeExpandFieldName(String JavaDoc componentId,
229                                                       String JavaDoc formName) {
230         return formName + NamingContainer.SEPARATOR_CHAR + componentId
231                + HIDDEN_TREE_NAV_FIELD_NAME;
232     }
233
234     public static String JavaDoc getHiddenTreeActionFieldName(String JavaDoc componentId,
235                                                       String JavaDoc formName) {
236         return formName + NamingContainer.SEPARATOR_CHAR + componentId
237                + HIDDEN_TREE_ACTION_FIELD_NAME;
238     }
239
240
241     public static String JavaDoc getFormName(UIComponent component,
242                                      FacesContext context) {
243         //Find form
244
UIComponent parent = component.getParent();
245         while (parent != null && !(parent instanceof UIForm)) {
246             parent = parent.getParent();
247         }
248
249         if (parent != null) {
250             //link is nested inside a form
251
return ((UIForm) parent).getClientId(context);
252         }
253         return "this";
254     }
255
256     /**
257      * Split a string into an array of strings arround a character separator.
258      * This function will be efficient for short strings, for longer strings,
259      * another approach may be better
260      *
261      * @param str the string to be split
262      * @param separator the separator character
263      * @return array of string subparts
264      */

265     public static String JavaDoc[] splitShortString(String JavaDoc str, char separator) {
266         int len;
267         if (str == null || (len = str.length()) == 0) {
268             return EMPTY_STRING_ARRAY;
269         }
270
271         int lastTokenIndex = 0;
272
273         // Step 1: how many substrings?
274
// We exchange double scan time for less memory allocation
275
for (int pos = str.indexOf(separator);
276              pos >= 0; pos = str.indexOf(separator, pos + 1)) {
277             lastTokenIndex++;
278         }
279
280         // Step 2: allocate exact size array
281
String JavaDoc[] list = new String JavaDoc[lastTokenIndex + 1];
282
283         int oldPos = 0;
284
285         // Step 3: retrieve substrings
286
for (
287                 int pos = str.indexOf(separator), i = 0; pos >= 0;
288                 pos = str.indexOf(separator, (oldPos = (pos + 1)))) {
289             list[i++] = substring(str, oldPos, pos);
290         }
291
292         list[lastTokenIndex] = substring(str, oldPos, len);
293
294         return list;
295     }
296
297     public static String JavaDoc substring(String JavaDoc str, int begin, int end) {
298         if (begin == end) {
299             return "";
300         }
301
302         return str.substring(begin, end);
303     }
304
305     public static String JavaDoc[] trim(String JavaDoc[] strings) {
306         if (strings == null) {
307             return null;
308         }
309
310         for (int i = 0, len = strings.length; i < len; i++) {
311             strings[i] = strings[i].trim();
312         }
313
314         return strings;
315     }
316
317     public static void renderChildren(FacesContext facesContext,
318                                       UIComponent component)
319             throws IOException JavaDoc {
320         if (component.getChildCount() > 0) {
321             for (Iterator JavaDoc it = component.getChildren().iterator();
322                  it.hasNext();) {
323                 UIComponent child = (UIComponent) it.next();
324                 renderChild(facesContext, child);
325             }
326         }
327     }
328
329
330     public static void renderChild(FacesContext facesContext, UIComponent child)
331             throws IOException JavaDoc {
332         if (!child.isRendered()) {
333             return;
334         }
335
336         child.encodeBegin(facesContext);
337         if (child.getRendersChildren()) {
338             child.encodeChildren(facesContext);
339         } else {
340             renderChildren(facesContext, child);
341         }
342         child.encodeEnd(facesContext);
343     }
344
345     /**
346      * Gets the comma separated list of visibility user roles from the given
347      * component and checks if current user is in one of these roles.
348      *
349      * @param component a user role aware component
350      * @return true if no user roles are defined for this component or user is
351      * in one of these roles, false otherwise
352      */

353     public static boolean isVisibleOnUserRole(UIComponent component) {
354         String JavaDoc userRole;
355         if (component instanceof UserRoleAware) {
356             userRole = ((UserRoleAware) component).getVisibleOnUserRole();
357         } else {
358             userRole = (String JavaDoc) component.getAttributes()
359                     .get(UserRoleAware.VISIBLE_ON_USER_ROLE_ATTR);
360         }
361
362         if (userRole == null) {
363             // no restriction
364
return true;
365         }
366
367         FacesContext facesContext = FacesContext.getCurrentInstance();
368         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(userRole, ",");
369         while (st.hasMoreTokens()) {
370             if (facesContext.getExternalContext()
371                     .isUserInRole(st.nextToken().trim())) {
372                 return true;
373             }
374         }
375         return false;
376     }
377
378
379     /**
380      * Gets the comma separated list of enabling user roles from the given
381      * component and checks if current user is in one of these roles.
382      *
383      * @param component a user role aware component
384      * @return true if no user roles are defined for this component or user is
385      * in one of these roles, false otherwise
386      */

387     public static boolean isEnabledOnUserRole(UIComponent component) {
388         String JavaDoc userRole;
389         if (component instanceof UserRoleAware) {
390             userRole = ((UserRoleAware) component).getEnabledOnUserRole();
391         } else {
392             userRole = (String JavaDoc) component.getAttributes()
393                     .get(UserRoleAware.ENABLED_ON_USER_ROLE_ATTR);
394         }
395
396         if (userRole == null) {
397             // no restriction
398
return true;
399         }
400
401         FacesContext facesContext = FacesContext.getCurrentInstance();
402         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(userRole, ",");
403         while (st.hasMoreTokens()) {
404             if (facesContext.getExternalContext()
405                     .isUserInRole(st.nextToken().trim())) {
406                 return true;
407             }
408         }
409         return false;
410     }
411
412
413     public static Object JavaDoc newInstance(Class JavaDoc clazz)
414             throws FacesException {
415         try {
416             return clazz.newInstance();
417         }
418         catch (NoClassDefFoundError JavaDoc e) {
419             throw new FacesException(e);
420         }
421         catch (InstantiationException JavaDoc e) {
422             throw new FacesException(e);
423         }
424         catch (IllegalAccessException JavaDoc e) {
425             throw new FacesException(e);
426         }
427     }
428
429     /**
430      * Same as {@link #classForName(String)}, but throws a RuntimeException
431      * (FacesException) instead of a ClassNotFoundException.
432      *
433      * @return the corresponding Class
434      * @throws NullPointerException if type is null
435      * @throws FacesException if class not found
436      */

437     public static Class JavaDoc simpleClassForName(String JavaDoc type) {
438         try {
439             return classForName(type);
440         }
441         catch (ClassNotFoundException JavaDoc e) {
442             throw new FacesException(e);
443         }
444     }
445
446     public static Object JavaDoc newInstance(String JavaDoc type)
447             throws FacesException {
448         if (type == null) {
449             return null;
450         }
451         return newInstance(simpleClassForName(type));
452     }
453
454     /**
455      * Tries a Class.forName with the context class loader of the current thread
456      * first and automatically falls back to the ClassUtils class loader (i.e.
457      * the loader of the myfaces.jar lib) if necessary.
458      *
459      * @param type fully qualified name of a non-primitive non-array class
460      * @return the corresponding Class
461      * @throws NullPointerException if type is null
462      * @throws ClassNotFoundException
463      */

464     public static Class JavaDoc classForName(String JavaDoc type)
465             throws ClassNotFoundException JavaDoc {
466         if (type == null) {
467             throw new NullPointerException JavaDoc("type");
468         }
469         try {
470             // Try WebApp ClassLoader first
471
return Class.forName(type,
472                                  false, // do not initialize for faster startup
473
Thread.currentThread().getContextClassLoader());
474         }
475         catch (ClassNotFoundException JavaDoc ignore) {
476             // fallback: Try ClassLoader for ClassUtils (i.e. the myfaces.jar lib)
477
return Class.forName(type,
478                                  false, // do not initialize for faster startup
479
CustomComponentUtils.class.getClassLoader());
480         }
481     }
482
483     public static boolean isDisabledOrReadOnly(UIComponent component) {
484         return isTrue(component.getAttributes().get("disabled")) ||
485                isTrue(component.getAttributes().get("readOnly"));
486     }
487
488     private static boolean isTrue(Object JavaDoc obj) {
489         if (!(obj instanceof Boolean JavaDoc)) {
490             return false;
491         }
492
493         return ((Boolean JavaDoc) obj).booleanValue();
494     }
495
496     public static void decodeUIInput(FacesContext facesContext,
497                                      UIComponent component) {
498         if (!(component instanceof EditableValueHolder)) {
499             throw new IllegalArgumentException JavaDoc("Component "
500                                                + component
501                     .getClientId(facesContext)
502                                                +
503                                                " is not an EditableValueHolder");
504         }
505         Map JavaDoc paramMap = facesContext.getExternalContext()
506                 .getRequestParameterMap();
507         String JavaDoc clientId = component.getClientId(facesContext);
508         if (paramMap.containsKey(clientId)) {
509             //request parameter found, set submittedValue
510
((EditableValueHolder) component).setSubmittedValue(paramMap
511                     .get(clientId));
512         } else {
513             //request parameter not found, nothing to decode - set submitted value to empty
514
//if the component has not been disabled
515
if (!isDisabledOrReadOnly(component)) {
516                 ((EditableValueHolder) component)
517                         .setSubmittedValue(EMPTY_STRING);
518             }
519         }
520     }
521
522     public static Date JavaDoc getDateValue(UIComponent component) {
523         if (!(component instanceof ValueHolder)) {
524             throw new IllegalArgumentException JavaDoc("Component : " +
525                                                getPathToComponent(component) +
526                                                "is not a ValueHolder");
527         }
528
529         if (component instanceof EditableValueHolder) {
530             Object JavaDoc submittedValue =
531                     ((EditableValueHolder) component).getSubmittedValue();
532             if (submittedValue != null) {
533                 if (submittedValue instanceof Date JavaDoc) {
534                     return (Date JavaDoc) submittedValue;
535                 } else {
536                     throw new IllegalArgumentException JavaDoc(
537                             "Expected submitted value of type Date for component : " +
538                             getPathToComponent(component));
539                 }
540             }
541         }
542
543         Object JavaDoc value = ((ValueHolder) component).getValue();
544
545         if (value == null || value instanceof Date JavaDoc) {
546             return (Date JavaDoc) value;
547         } else {
548             throw new IllegalArgumentException JavaDoc(
549                     "Expected submitted value of type Date for component : "
550                     + getPathToComponent(component));
551         }
552     }
553
554     public static void copyHtmlInputTextAttributes(HtmlInputText src,
555                                                    HtmlInputText dest) {
556         dest.setId(src.getId());
557         dest.setImmediate(src.isImmediate());
558         dest.setTransient(src.isTransient());
559         dest.setAccesskey(src.getAccesskey());
560         dest.setAlt(src.getAlt());
561         dest.setConverter(src.getConverter());
562         dest.setDir(src.getDir());
563         dest.setDisabled(src.isDisabled());
564         dest.setLang(src.getLang());
565         dest.setLocalValueSet(src.isLocalValueSet());
566         dest.setMaxlength(src.getMaxlength());
567         dest.setOnblur(src.getOnblur());
568         dest.setOnchange(src.getOnchange());
569         dest.setOnclick(src.getOnclick());
570         dest.setOndblclick(src.getOndblclick());
571         dest.setOnfocus(src.getOnfocus());
572         dest.setOnkeydown(src.getOnkeydown());
573         dest.setOnkeypress(src.getOnkeypress());
574         dest.setOnkeyup(src.getOnkeyup());
575         dest.setOnmousedown(src.getOnmousedown());
576         dest.setOnmousemove(src.getOnmousemove());
577         dest.setOnmouseout(src.getOnmouseout());
578         dest.setOnmouseover(src.getOnmouseover());
579         dest.setOnmouseup(src.getOnmouseup());
580         dest.setOnselect(src.getOnselect());
581         dest.setReadonly(src.isReadonly());
582         dest.setRendered(src.isRendered());
583         dest.setRequired(src.isRequired());
584         dest.setSize(src.getSize());
585         dest.setStyle(src.getStyle());
586         dest.setStyleClass(src.getStyleClass());
587         dest.setTabindex(src.getTabindex());
588         dest.setTitle(src.getTitle());
589         dest.setValidator(src.getValidator());
590     }
591
592 }
593
Popular Tags