1
2
3
4 package org.rcfaces.core.util;
5
6 import java.util.ArrayList;
7 import java.util.Arrays;
8 import java.util.Collection;
9 import java.util.Iterator;
10 import java.util.List;
11
12 import javax.faces.context.FacesContext;
13 import javax.faces.model.SelectItem;
14
15 import org.apache.commons.logging.Log;
16 import org.apache.commons.logging.LogFactory;
17 import org.rcfaces.core.internal.RcfacesContext;
18 import org.rcfaces.core.internal.adapter.IAdapterManager;
19 import org.rcfaces.core.lang.IAdaptable;
20
21
22
23
24
25
26 public class SelectItemAdapter {
27
28 private static final String REVISION = "$Revision: 1.2 $";
29
30 private static final Log LOG = LogFactory.getLog(SelectItemAdapter.class);
31
32 private static final SelectItem[] SELECT_ITEM_EMPTY_ARRAY = new SelectItem[0];
33
34 public static SelectItem[] adapt(Object value[]) {
35 return adapt(value, null, null);
36 }
37
38 public static SelectItem[] adapt(Object value[], Object parameter,
39 FacesContext facesContext) {
40 if (value == null || value.length == 0) {
41 return SELECT_ITEM_EMPTY_ARRAY;
42 }
43
44 return adapt(Arrays.asList(value), parameter, facesContext);
45 }
46
47 public static SelectItem[] adapt(Collection collection) {
48 return adapt(collection, null, null);
49 }
50
51 public static SelectItem[] adapt(Collection collection, Object parameter,
52 FacesContext facesContext) {
53 if (collection == null || collection.isEmpty()) {
54 return SELECT_ITEM_EMPTY_ARRAY;
55 }
56
57 if (facesContext == null) {
58 facesContext = FacesContext.getCurrentInstance();
59 }
60
61 IAdapterManager adapterManager = RcfacesContext.getInstance(
62 facesContext).getAdapterManager();
63
64 List ret = null;
65
66 int count = collection.size();
67 for (Iterator it = collection.iterator(); it.hasNext(); count--) {
68 Object value = it.next();
69
70 if (value == null) {
71 continue;
72 }
73
74 if (value instanceof SelectItem) {
75 if (ret == null) {
76 ret = new ArrayList(count);
77 }
78 ret.add(value);
79 continue;
80 }
81
82 if (value instanceof IAdaptable) {
83 IAdaptable adaptable = (IAdaptable) value;
84
85 SelectItem selectItem = (SelectItem) adaptable.getAdapter(
86 SelectItem.class, parameter);
87 if (selectItem != null) {
88 if (ret == null) {
89 ret = new ArrayList(count);
90 }
91 ret.add(selectItem);
92 continue;
93 }
94 }
95
96 SelectItem selectItem = (SelectItem) adapterManager.getAdapter(
97 value, SelectItem.class, parameter);
98 if (selectItem != null) {
99 if (ret == null) {
100 ret = new ArrayList(count);
101 }
102 ret.add(selectItem);
103 continue;
104 }
105
106 if (LOG.isDebugEnabled()) {
107 LOG.debug("Can not convert value '" + value
108 + "' to selectItem !");
109 }
110 }
111
112 if (ret == null) {
113 return SELECT_ITEM_EMPTY_ARRAY;
114 }
115
116 return (SelectItem[]) ret.toArray(new SelectItem[ret.size()]);
117 }
118 }