KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > blandware > atleap > common > util > ConvertUtil


1 /*
2  * Copyright 2004 Blandware (http://www.blandware.com)
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 com.blandware.atleap.common.util;
17
18 import com.blandware.atleap.common.Constants;
19 import org.apache.commons.logging.Log;
20 import org.apache.commons.logging.LogFactory;
21
22 import java.io.UnsupportedEncodingException JavaDoc;
23 import java.lang.reflect.Array JavaDoc;
24 import java.util.*;
25
26
27 /**
28  * <p>Utility class to perform conversions.</p>
29  * <p><a HREF="ConvertUtil.java.htm"><i>View Source</i></a>
30  * </p>
31  *
32  * @author Matt Raible <a HREF="mailto:matt@raibledesigns.com">&lt;matt@raibledesigns.com&gt;</a>
33  * @author Sergey Zubtcovskii <a HREF="mailto:sergey.zubtcovskii@blandware.com">&lt;sergey.zubtcovskii@blandware.com&gt;</a>
34  * @version $Revision: 1.17 $ $Date: 2006/03/16 11:09:36 $
35  */

36 public final class ConvertUtil {
37     //~ Static fields/initializers =============================================
38

39     //~ Methods ================================================================
40

41     /**
42      * Converts a ResourceBundle to a Map object.
43      *
44      * @param rb a given resource bundle
45      * @return Map a populated map
46      */

47     public static Map convertBundleToMap(ResourceBundle rb) {
48         Map map = new HashMap();
49
50         for ( Enumeration keys = rb.getKeys(); keys.hasMoreElements(); ) {
51             String JavaDoc key = (String JavaDoc) keys.nextElement();
52             map.put(key, rb.getString(key));
53         }
54
55         return map;
56     }
57
58     /**
59      * Converts a ResourceBundle to a Properties object.
60      *
61      * @param rb a given resource bundle
62      * @return Properties a populated properties object
63      */

64     public static Properties convertBundleToProperties(ResourceBundle rb) {
65         Properties props = new Properties();
66
67         for ( Enumeration keys = rb.getKeys(); keys.hasMoreElements(); ) {
68             String JavaDoc key = (String JavaDoc) keys.nextElement();
69             props.put(key, rb.getString(key));
70         }
71
72         return props;
73     }
74
75     /**
76      * Converts list to string concatenating list elements with the delimiter
77      *
78      * @param list List to convert to string
79      * @param delimiter Delimiter to put between elements
80      * @return List members, delimited by specifed delimiter.
81      */

82     public static String JavaDoc convertListToString(List list, String JavaDoc delimiter) {
83         return convertListToString(list, delimiter, null);
84     }
85
86     /**
87      * Converts list to string concatenating list elements with the delimiter.
88      * Each element is additionally enclosed in <code>encloser</code> chars.
89      *
90      * @param list List to convert to string
91      * @param delimiter Delimiter to put between elements
92      * @param encloser Character to enclose each element
93      * @return List members, delimited by specifed delimiter. Each element enclosed with specified character
94      */

95     public static String JavaDoc convertListToString(List list, String JavaDoc delimiter, char encloser) {
96         return convertListToString(list, delimiter, new Character JavaDoc(encloser));
97     }
98
99     /**
100      * Converts list to string concatenating list elements with the delimiter.
101      * Each element is additionally enclosed in <code>encloser</code> chars.
102      *
103      * @param list List to convert to string
104      * @param delimiter Delimiter to put between elements
105      * @param encloser Character to enclose each element
106      * @return List members, delimited by specifed delimiter. Each element enclosed with specified character
107      */

108     private static String JavaDoc convertListToString(List list, String JavaDoc delimiter, Character JavaDoc encloser) {
109
110         if ( list == null || list.size() == 0 ) {
111             return new String JavaDoc();
112         }
113
114         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
115         for ( Iterator i = list.iterator(); i.hasNext(); ) {
116             String JavaDoc next = String.valueOf(i.next());
117             if ( encloser != null ) {
118                 next = encloser + next + encloser;
119             }
120             sb.append(next);
121             if ( i.hasNext() ) {
122                 sb.append(delimiter);
123             }
124         }
125
126         return sb.toString();
127     }
128
129     /**
130      * Converts string to list. The string is assumed to be a sequence of some
131      * elements separated with delimiter.
132      *
133      * @param string String to convert to list
134      * @param delimiter Delimiter of list elements
135      * @param trim Whether or not to trim tokens befor putting them in list
136      * @return List
137      */

138     public static List convertStringToList(String JavaDoc string, String JavaDoc delimiter, boolean trim) {
139         if ( string == null || string.length() == 0 ) {
140             return new LinkedList();
141         }
142         String JavaDoc[] members = string.split(delimiter);
143         List list = Collections.synchronizedList(new LinkedList());
144         for ( int i = 0; i < members.length; i++ ) {
145             String JavaDoc member = members[i];
146             if ( trim ) {
147                 member = member.trim();
148             }
149             list.add(member);
150         }
151         return list;
152     }
153
154     /**
155      * Creates set from array of objects
156      *
157      * @param anArray Array of objects to create set from
158      * @return Set that contains objects from array
159      */

160     public static Set convertArrayToSet(Object JavaDoc[] anArray) {
161         Set set = new HashSet();
162         for ( int i = 0; i < anArray.length; i++ ) {
163             set.add(anArray[i]);
164         }
165         return set;
166     }
167
168     /**
169      * Converts all String values in specified list to <code>java.lang.Long</code>.
170      * If there is instance of another than <code>java.lang.String</code> class is found, <code>java.lang.ClassCastException</code> will be thrown.
171      *
172      * @param values List of values to convert to <code>java.lang.Long[]</code>
173      * @return <code>java.lang.Long[]</code>
174      */

175     public static Long JavaDoc[] convertToLongArray(List values) {
176         Long JavaDoc[] result = new Long JavaDoc[values.size()];
177         for ( int i = 0; i < values.size(); i++ ) {
178             Object JavaDoc value = values.get(i);
179             if ( !(value instanceof String JavaDoc) ) {
180                 throw new ClassCastException JavaDoc("Unable to convert instance of class " + value.getClass().getName() + " to java.lang.Long");
181             }
182             result[i] = Long.valueOf((String JavaDoc) value);
183         }
184         return result;
185     }
186
187     /**
188      * Converts byte array to string using default encoding
189      *
190      * @param content Byte array to convert to string
191      * @return string resulted from converting byte array using defalt encoding
192      */

193     public static String JavaDoc convertToString(byte[] content) {
194         return convertToString(content, null);
195     }
196
197     /**
198      * Converts byte array to string according to specified encoding
199      *
200      * @param content Byte array to convert to string
201      * @param encoding Encoding string, if <code>null</code> default is used
202      * @return string resulted from converting byte array
203      */

204     public static String JavaDoc convertToString(byte[] content, String JavaDoc encoding) {
205         if ( content == null ) {
206             return null;
207         }
208         if ( encoding == null ) {
209             encoding = Constants.DEFAULT_ENCODING;
210         }
211
212         String JavaDoc value = null;
213         try {
214             value = new String JavaDoc(content, encoding);
215         } catch ( UnsupportedEncodingException JavaDoc ex ) {
216             return new String JavaDoc(content);
217         }
218         return value;
219     }
220
221
222     /**
223      * Converts string to byte array using default encoding
224      *
225      * @param content String to convert to array
226      * @return byte array resulted from converting string using default encoding
227      */

228     public static byte[] convertToByteArray(String JavaDoc content) {
229         return convertToByteArray(content, null);
230     }
231
232     /**
233      * Converts string to byte array according to specified encoding
234      *
235      * @param content String to convert to array
236      * @param encoding Encoding string, if <code>null</code> default is used
237      * @return byte array
238      */

239     public static byte[] convertToByteArray(String JavaDoc content, String JavaDoc encoding) {
240
241         Log log = LogFactory.getLog(ConvertUtil.class);
242
243         if ( content == null ) {
244             return null;
245         }
246         if ( encoding == null ) {
247             encoding = Constants.DEFAULT_ENCODING;
248         }
249
250         if ( log.isDebugEnabled() ) {
251             log.debug("Converting to byte array using: " + encoding);
252         }
253
254         byte[] value;
255         try {
256             value = content.getBytes(encoding);
257         } catch ( UnsupportedEncodingException JavaDoc ex ) {
258             if ( log.isWarnEnabled() ) {
259                 log.warn(ex);
260             }
261             return content.getBytes();
262         }
263         return value;
264     }
265
266
267     /**
268      * Converts primitive array to array of objects. Each element in returned array will have run-time class
269      * equivalent to its primitive type (e.g. <code>java.lang.Integer</code> is object equivalent to <code>int</code>,
270      * <code>java.lang.Boolean</code> is object equivalent to <code>boolean</code>, etc.)
271      *
272      * @param primitiveArray Array of primitives which needs to be converted to objects
273      * @return Array of object, each element is object equivalent to corresponding primitive value
274      * @throws IllegalArgumentException if specified argument is not a primitive array
275      */

276     public static Object JavaDoc[] convertPrimitivesToObjects(Object JavaDoc primitiveArray) {
277         if ( primitiveArray == null ) {
278             return null;
279         }
280
281         if ( !primitiveArray.getClass().isArray() ) {
282             throw new IllegalArgumentException JavaDoc("Specified object is not array");
283         }
284
285         if ( primitiveArray instanceof Object JavaDoc[] ) {
286             throw new IllegalArgumentException JavaDoc("Specified object is not primitive array");
287         }
288
289         int length = Array.getLength(primitiveArray);
290         Object JavaDoc[] result = new Object JavaDoc[length];
291         for ( int i = 0; i < length; i++ ) {
292             result[i] = Array.get(primitiveArray, i);
293         }
294
295         return result;
296     }
297
298     /**
299      * Converts collection, specified in argument to the instance of <code>java.util.List</code>. Supported types
300      * include: <ul type="disc">
301      * <li><code>java.util.Collection, java.util.Set, java.util.SortedSet, java.util.List</code> - result list will contain all elements from specified collection, set or list</li>
302      * <li><code>java.util.Enumeration</code> - result list will contain all elements from this enumeration in the same order</li>
303      * <li><code>java.util.Iterator</code> - result list will contain all elements from collection, iterated by this iterator in the same order</li>
304      * <li><code>java.util.Map, java.util.SortedMap</code> - result list will contain all entries (instances of <code>java.util.Map$Entry</code>)</li>
305      * <li><code>java.lang.String</code> - result list will contain all characters, each one wrapped in <code>java.lang.Character</code></li>
306      * <li><code>java.lang.Object[]</code> - result list will be dynamic equivalent for specified array</li>
307      * <li>any primitive array - result list will contain elements from array, each wrapped in instance of equivalent class
308      * (e.g. <code>java.lang.Integer</code> is object equivalent to <code>int</code>,
309      * <code>java.lang.Boolean</code> is object equivalent to <code>boolean</code>, etc.)</li>
310      * </ul>
311      * @param collection Collection to convert to list
312      * @return List, containing all elements from collection according to rules, specified above
313      */

314     public static List convertCollectionToList(Object JavaDoc collection) {
315
316         if ( collection == null ) {
317             return null;
318         }
319
320         List list = null;
321
322         if ( collection instanceof Collection ) {
323             list = new ArrayList((Collection) collection);
324         } else if ( collection instanceof Enumeration ) {
325             list = new ArrayList();
326             Enumeration e = (Enumeration) collection;
327             while ( e.hasMoreElements() ) {
328                 list.add(e.nextElement());
329             }
330         } else if ( collection instanceof Iterator ) {
331             list = new ArrayList();
332             Iterator i = (Iterator) collection;
333             while ( i.hasNext() ) {
334                 list.add(i.next());
335             }
336         } else if ( collection instanceof Map ) {
337             list = new ArrayList(((Map) collection).entrySet());
338         } else if ( collection instanceof String JavaDoc ) {
339             list = Arrays.asList(convertPrimitivesToObjects(((String JavaDoc) collection).toCharArray()));
340         } else if ( collection instanceof Object JavaDoc[] ) {
341             list = Arrays.asList((Object JavaDoc[]) collection);
342         } else if ( collection.getClass().isArray() ) {
343             list = Arrays.asList(convertPrimitivesToObjects(collection));
344         } else {
345             // type is not supported
346
throw new IllegalArgumentException JavaDoc("Class '" + collection.getClass().getName() + "' is not convertable to java.util.List");
347         }
348
349         return list;
350     }
351 }
352
Popular Tags