KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > base > util > UtilMisc


1 /*
2  * $Id: UtilMisc.java 7320 2006-04-18 04:50:41Z jonesde $
3  *
4  * Copyright (c) 2001-2005 The Open For Business Project - www.ofbiz.org
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  */

24 package org.ofbiz.base.util;
25
26 import java.util.ArrayList JavaDoc;
27 import java.util.Collection JavaDoc;
28 import java.util.Collections JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.LinkedList JavaDoc;
31 import java.util.List JavaDoc;
32 import java.util.Locale JavaDoc;
33 import java.util.Map JavaDoc;
34 import java.util.TreeMap JavaDoc;
35
36 import javax.mail.Address JavaDoc;
37
38 import javolution.util.FastList;
39 import javolution.util.FastMap;
40
41 import org.ofbiz.base.util.collections.MapComparator;
42
43 /**
44  * UtilMisc - Misc Utility Functions
45  *
46  * @author <a HREF="mailto:jonesde@ofbiz.org">David E. Jones</a>
47  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
48  * @version $Rev: 7320 $
49  * @since 2.0
50  */

51 public class UtilMisc {
52
53     public static final String JavaDoc module = UtilMisc.class.getName();
54
55     /**
56      * Get an iterator from a collection, returning null if collection is null
57      * @param col The collection to be turned in to an iterator
58      * @return The resulting Iterator
59      */

60     public static Iterator JavaDoc toIterator(Collection JavaDoc col) {
61         if (col == null)
62             return null;
63         else
64             return col.iterator();
65     }
66
67     /**
68      * Create a map from passed nameX, valueX parameters
69      * @return The resulting Map
70      */

71     public static Map JavaDoc toMap(String JavaDoc name1, Object JavaDoc value1) {
72         return new UtilMisc.SimpleMap(name1, value1);
73
74         /* Map fields = FastMap.newInstance();
75          fields.put(name1, value1);
76          return fields;*/

77     }
78
79     /**
80      * Create a map from passed nameX, valueX parameters
81      * @return The resulting Map
82      */

83     public static Map JavaDoc toMap(String JavaDoc name1, Object JavaDoc value1, String JavaDoc name2, Object JavaDoc value2) {
84         return new UtilMisc.SimpleMap(name1, value1, name2, value2);
85
86         /* Map fields = FastMap.newInstance();
87          fields.put(name1, value1);
88          fields.put(name2, value2);
89          return fields;*/

90     }
91
92     /**
93      * Create a map from passed nameX, valueX parameters
94      * @return The resulting Map
95      */

96     public static Map JavaDoc toMap(String JavaDoc name1, Object JavaDoc value1, String JavaDoc name2, Object JavaDoc value2, String JavaDoc name3, Object JavaDoc value3) {
97         return new UtilMisc.SimpleMap(name1, value1, name2, value2, name3, value3);
98
99         /* Map fields = FastMap.newInstance();
100          fields.put(name1, value1);
101          fields.put(name2, value2);
102          fields.put(name3, value3);
103          return fields;*/

104     }
105
106     /**
107      * Create a map from passed nameX, valueX parameters
108      * @return The resulting Map
109      */

110     public static Map JavaDoc toMap(String JavaDoc name1, Object JavaDoc value1, String JavaDoc name2, Object JavaDoc value2, String JavaDoc name3,
111         Object JavaDoc value3, String JavaDoc name4, Object JavaDoc value4) {
112         return new UtilMisc.SimpleMap(name1, value1, name2, value2, name3, value3, name4, value4);
113
114         /* Map fields = FastMap.newInstance();
115          fields.put(name1, value1);
116          fields.put(name2, value2);
117          fields.put(name3, value3);
118          fields.put(name4, value4);
119          return fields;*/

120     }
121
122     /**
123      * Create a map from passed nameX, valueX parameters
124      * @return The resulting Map
125      */

126     public static Map JavaDoc toMap(String JavaDoc name1, Object JavaDoc value1, String JavaDoc name2, Object JavaDoc value2, String JavaDoc name3, Object JavaDoc value3,
127         String JavaDoc name4, Object JavaDoc value4, String JavaDoc name5, Object JavaDoc value5) {
128         Map JavaDoc fields = FastMap.newInstance();
129
130         fields.put(name1, value1);
131         fields.put(name2, value2);
132         fields.put(name3, value3);
133         fields.put(name4, value4);
134         fields.put(name5, value5);
135         return fields;
136     }
137
138     /**
139      * Create a map from passed nameX, valueX parameters
140      * @return The resulting Map
141      */

142     public static Map JavaDoc toMap(String JavaDoc name1, Object JavaDoc value1, String JavaDoc name2, Object JavaDoc value2, String JavaDoc name3, Object JavaDoc value3,
143         String JavaDoc name4, Object JavaDoc value4, String JavaDoc name5, Object JavaDoc value5, String JavaDoc name6, Object JavaDoc value6) {
144         Map JavaDoc fields = FastMap.newInstance();
145
146         fields.put(name1, value1);
147         fields.put(name2, value2);
148         fields.put(name3, value3);
149         fields.put(name4, value4);
150         fields.put(name5, value5);
151         fields.put(name6, value6);
152         return fields;
153     }
154
155     /**
156      * Create a map from passed nameX, valueX parameters
157      * @return The resulting Map
158      */

159     public static Map JavaDoc toMap(Object JavaDoc[] data) {
160         if (data == null) {
161             return null;
162         }
163         if (data.length % 2 == 1) {
164             throw new IllegalArgumentException JavaDoc("You must pass an even sized array to the toMap method");
165         }
166         Map JavaDoc map = FastMap.newInstance();
167         for (int i = 0; i < data.length; ) {
168             map.put(data[i++], data[i++]);
169         }
170         return map;
171     }
172
173     public static String JavaDoc printMap(Map JavaDoc theMap) {
174         StringBuffer JavaDoc theBuf = new StringBuffer JavaDoc();
175         Iterator JavaDoc entryIter = theMap.entrySet().iterator();
176         while (entryIter.hasNext()) {
177             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) entryIter.next();
178             theBuf.append(entry.getKey());
179             theBuf.append(" --> ");
180             theBuf.append(entry.getValue());
181             theBuf.append("\n");
182         }
183         return theBuf.toString();
184     }
185     
186     /**
187      * Sort a List of Maps by specified consistent keys.
188      * @param listOfMaps List of Map objects to sort.
189      * @param sortKeys List of Map keys to sort by.
190      * @return a new List of sorted Maps.
191      */

192     public static List JavaDoc sortMaps(List JavaDoc listOfMaps, List JavaDoc sortKeys) {
193         if (listOfMaps == null || sortKeys == null)
194             return null;
195         List JavaDoc toSort = FastList.newInstance();
196         toSort.addAll(listOfMaps);
197         try {
198             MapComparator mc = new MapComparator(sortKeys);
199             Collections.sort(toSort, mc);
200         } catch (Exception JavaDoc e) {
201             Debug.logError(e, "Problems sorting list of maps; returning null.", module);
202             return null;
203         }
204         return toSort;
205     }
206
207     public static Object JavaDoc removeFirst(List JavaDoc lst) {
208         return lst.remove(0);
209     }
210    
211     /**
212      * Create a list from passed objX parameters
213      * @return The resulting List
214      */

215     public static List JavaDoc toList(Object JavaDoc obj1) {
216         List JavaDoc list = new ArrayList JavaDoc(1);
217
218         list.add(obj1);
219         return list;
220     }
221
222     /**
223      * Create a list from passed objX parameters
224      * @return The resulting List
225      */

226     public static List JavaDoc toList(Object JavaDoc obj1, Object JavaDoc obj2) {
227         List JavaDoc list = new ArrayList JavaDoc(2);
228
229         list.add(obj1);
230         list.add(obj2);
231         return list;
232     }
233
234     /**
235      * Create a list from passed objX parameters
236      * @return The resulting List
237      */

238     public static List JavaDoc toList(Object JavaDoc obj1, Object JavaDoc obj2, Object JavaDoc obj3) {
239         List JavaDoc list = new ArrayList JavaDoc(3);
240
241         list.add(obj1);
242         list.add(obj2);
243         list.add(obj3);
244         return list;
245     }
246
247     /**
248      * Create a list from passed objX parameters
249      * @return The resulting List
250      */

251     public static List JavaDoc toList(Object JavaDoc obj1, Object JavaDoc obj2, Object JavaDoc obj3, Object JavaDoc obj4) {
252         List JavaDoc list = new ArrayList JavaDoc(4);
253
254         list.add(obj1);
255         list.add(obj2);
256         list.add(obj3);
257         list.add(obj4);
258         return list;
259     }
260
261     /**
262      * Create a list from passed objX parameters
263      * @return The resulting List
264      */

265     public static List JavaDoc toList(Object JavaDoc obj1, Object JavaDoc obj2, Object JavaDoc obj3, Object JavaDoc obj4, Object JavaDoc obj5) {
266         List JavaDoc list = new ArrayList JavaDoc(5);
267
268         list.add(obj1);
269         list.add(obj2);
270         list.add(obj3);
271         list.add(obj4);
272         list.add(obj5);
273         return list;
274     }
275
276     /**
277      * Create a list from passed objX parameters
278      * @return The resulting List
279      */

280     public static List JavaDoc toList(Object JavaDoc obj1, Object JavaDoc obj2, Object JavaDoc obj3, Object JavaDoc obj4, Object JavaDoc obj5, Object JavaDoc obj6) {
281         List JavaDoc list = new ArrayList JavaDoc(6);
282
283         list.add(obj1);
284         list.add(obj2);
285         list.add(obj3);
286         list.add(obj4);
287         list.add(obj5);
288         list.add(obj6);
289         return list;
290     }
291
292     public static List JavaDoc toList(Collection JavaDoc collection) {
293         if (collection == null) return null;
294         if (collection instanceof List JavaDoc) {
295             return (List JavaDoc) collection;
296         } else {
297             return new ArrayList JavaDoc(collection);
298         }
299     }
300
301     public static List JavaDoc toListArray(Object JavaDoc[] data) {
302         if (data == null) {
303             return null;
304         }
305         List JavaDoc list = new ArrayList JavaDoc(data.length);
306         for (int i = 0; i < data.length; i++) {
307             list.add(data[i]);
308         }
309         return list;
310     }
311     
312     public static long toLong(Object JavaDoc value) {
313         if (value != null) {
314             if (value instanceof Long JavaDoc) {
315                 return ((Long JavaDoc) value).longValue();
316             } else if (value instanceof String JavaDoc) {
317                 return Long.parseLong((String JavaDoc) value);
318             }
319         }
320         return 0;
321     }
322
323     /**
324      * Returns a double from value, where value could either be a Double or a String
325      * @param value
326      * @return
327      */

328     public static double toDouble(Object JavaDoc value) {
329         if (value != null) {
330             if (value instanceof Double JavaDoc) {
331                 return ((Double JavaDoc) value).doubleValue();
332             } else if (value instanceof String JavaDoc) {
333                 return Double.parseDouble((String JavaDoc) value);
334             }
335         }
336         return 0.0;
337     }
338
339     /**
340      * Adds value to the key entry in theMap, or creates a new one if not already there
341      * @param theMap
342      * @param key
343      * @param value
344      */

345     public static void addToDoubleInMap(Map JavaDoc theMap, Object JavaDoc key, Double JavaDoc value) {
346         Double JavaDoc curValue = (Double JavaDoc) theMap.get(key);
347         if (curValue != null) {
348             theMap.put(key, new Double JavaDoc(curValue.doubleValue() + value.doubleValue()));
349         } else {
350             theMap.put(key, value);
351         }
352     }
353     
354     /**
355      * Parse a locale string Locale object
356      * @param localeString The locale string (en_US)
357      * @return Locale The new Locale object or null if no valid locale can be interpreted
358      */

359     public static Locale JavaDoc parseLocale(String JavaDoc localeString) {
360         if (localeString == null || localeString.length() == 0) {
361             return null;
362         }
363
364         Locale JavaDoc locale = null;
365         if (localeString.length() == 2) {
366             // two letter language code
367
locale = new Locale JavaDoc(localeString);
368         } else if (localeString.length() == 5) {
369             // positions 0-1 language, 3-4 are country
370
String JavaDoc language = localeString.substring(0, 2);
371             String JavaDoc country = localeString.substring(3, 5);
372             locale = new Locale JavaDoc(language, country);
373         } else if (localeString.length() > 6) {
374             // positions 0-1 language, 3-4 are country, 6 and on are special extensions
375
String JavaDoc language = localeString.substring(0, 2);
376             String JavaDoc country = localeString.substring(3, 5);
377             String JavaDoc extension = localeString.substring(6);
378             locale = new Locale JavaDoc(language, country, extension);
379         } else {
380             Debug.logWarning("Do not know what to do with the localeString [" + localeString + "], should be length 2, 5, or greater than 6, returning null", module);
381         }
382
383         return locale;
384     }
385
386     /** The input can be a String, Locale, or even null and a valid Locale will always be returned; if nothing else works, returns the default locale.
387      * @param localeObject An Object representing the locale
388      */

389     public static Locale JavaDoc ensureLocale(Object JavaDoc localeObject) {
390         if (localeObject != null && localeObject instanceof String JavaDoc) {
391             localeObject = UtilMisc.parseLocale((String JavaDoc) localeObject);
392         }
393         if (localeObject != null && localeObject instanceof Locale JavaDoc) {
394             return (Locale JavaDoc) localeObject;
395         }
396         return Locale.getDefault();
397     }
398
399     public static List JavaDoc availableLocaleList = null;
400     /** Returns a List of available locales sorted by display name */
401     public static List JavaDoc availableLocales() {
402         if (availableLocaleList == null) {
403             synchronized(UtilMisc.class) {
404                 if (availableLocaleList == null) {
405                     TreeMap JavaDoc localeMap = new TreeMap JavaDoc();
406                     Locale JavaDoc[] locales = Locale.getAvailableLocales();
407                     for (int i = 0; i < locales.length; i++) {
408                         localeMap.put(locales[i].getDisplayName(), locales[i]);
409                     }
410                     availableLocaleList = new LinkedList JavaDoc(localeMap.values());
411                 }
412             }
413         }
414         return availableLocaleList;
415     }
416
417     /** This is meant to be very quick to create and use for small sized maps, perfect for how we usually use UtilMisc.toMap */
418     protected static class SimpleMap implements Map JavaDoc, java.io.Serializable JavaDoc {
419         protected Map JavaDoc realMapIfNeeded = null;
420
421         String JavaDoc[] names;
422         Object JavaDoc[] values;
423
424         public SimpleMap() {
425             names = new String JavaDoc[0];
426             values = new Object JavaDoc[0];
427         }
428
429         public SimpleMap(String JavaDoc name1, Object JavaDoc value1) {
430             names = new String JavaDoc[1];
431             values = new Object JavaDoc[1];
432             this.names[0] = name1;
433             this.values[0] = value1;
434         }
435
436         public SimpleMap(String JavaDoc name1, Object JavaDoc value1, String JavaDoc name2, Object JavaDoc value2) {
437             names = new String JavaDoc[2];
438             values = new Object JavaDoc[2];
439             this.names[0] = name1;
440             this.values[0] = value1;
441             this.names[1] = name2;
442             this.values[1] = value2;
443         }
444
445         public SimpleMap(String JavaDoc name1, Object JavaDoc value1, String JavaDoc name2, Object JavaDoc value2, String JavaDoc name3, Object JavaDoc value3) {
446             names = new String JavaDoc[3];
447             values = new Object JavaDoc[3];
448             this.names[0] = name1;
449             this.values[0] = value1;
450             this.names[1] = name2;
451             this.values[1] = value2;
452             this.names[2] = name3;
453             this.values[2] = value3;
454         }
455
456         public SimpleMap(String JavaDoc name1, Object JavaDoc value1, String JavaDoc name2, Object JavaDoc value2, String JavaDoc name3, Object JavaDoc value3, String JavaDoc name4, Object JavaDoc value4) {
457             names = new String JavaDoc[4];
458             values = new Object JavaDoc[4];
459             this.names[0] = name1;
460             this.values[0] = value1;
461             this.names[1] = name2;
462             this.values[1] = value2;
463             this.names[2] = name3;
464             this.values[2] = value3;
465             this.names[3] = name4;
466             this.values[3] = value4;
467         }
468
469         protected void makeRealMap() {
470             realMapIfNeeded = FastMap.newInstance();
471             for (int i = 0; i < names.length; i++) {
472                 realMapIfNeeded.put(names[i], values[i]);
473             }
474             this.names = null;
475             this.values = null;
476         }
477
478         public void clear() {
479             if (realMapIfNeeded != null) {
480                 realMapIfNeeded.clear();
481             } else {
482                 realMapIfNeeded = FastMap.newInstance();
483                 names = null;
484                 values = null;
485             }
486         }
487
488         public boolean containsKey(Object JavaDoc obj) {
489             if (realMapIfNeeded != null) {
490                 return realMapIfNeeded.containsKey(obj);
491             } else {
492                 for (int i = 0; i < names.length; i++) {
493                     if (obj == null && names[i] == null) return true;
494                     if (names[i] != null && names[i].equals(obj)) return true;
495                 }
496                 return false;
497             }
498         }
499
500         public boolean containsValue(Object JavaDoc obj) {
501             if (realMapIfNeeded != null) {
502                 return realMapIfNeeded.containsValue(obj);
503             } else {
504                 for (int i = 0; i < names.length; i++) {
505                     if (obj == null && values[i] == null) return true;
506                     if (values[i] != null && values[i].equals(obj)) return true;
507                 }
508                 return false;
509             }
510         }
511
512         public java.util.Set JavaDoc entrySet() {
513             if (realMapIfNeeded != null) {
514                 return realMapIfNeeded.entrySet();
515             } else {
516                 this.makeRealMap();
517                 return realMapIfNeeded.entrySet();
518             }
519         }
520
521         public Object JavaDoc get(Object JavaDoc obj) {
522             if (realMapIfNeeded != null) {
523                 return realMapIfNeeded.get(obj);
524             } else {
525                 for (int i = 0; i < names.length; i++) {
526                     if (obj == null && names[i] == null) return values[i];
527                     if (names[i] != null && names[i].equals(obj)) return values[i];
528                 }
529                 return null;
530             }
531         }
532
533         public boolean isEmpty() {
534             if (realMapIfNeeded != null) {
535                 return realMapIfNeeded.isEmpty();
536             } else {
537                 if (this.names.length == 0) return true;
538                 return false;
539             }
540         }
541
542         public java.util.Set JavaDoc keySet() {
543             if (realMapIfNeeded != null) {
544                 return realMapIfNeeded.keySet();
545             } else {
546                 this.makeRealMap();
547                 return realMapIfNeeded.keySet();
548             }
549         }
550
551         public Object JavaDoc put(Object JavaDoc obj, Object JavaDoc obj1) {
552             if (realMapIfNeeded != null) {
553                 return realMapIfNeeded.put(obj, obj1);
554             } else {
555                 this.makeRealMap();
556                 return realMapIfNeeded.put(obj, obj1);
557             }
558         }
559
560         public void putAll(java.util.Map JavaDoc map) {
561             if (realMapIfNeeded != null) {
562                 realMapIfNeeded.putAll(map);
563             } else {
564                 this.makeRealMap();
565                 realMapIfNeeded.putAll(map);
566             }
567         }
568
569         public Object JavaDoc remove(Object JavaDoc obj) {
570             if (realMapIfNeeded != null) {
571                 return realMapIfNeeded.remove(obj);
572             } else {
573                 this.makeRealMap();
574                 return realMapIfNeeded.remove(obj);
575             }
576         }
577
578         public int size() {
579             if (realMapIfNeeded != null) {
580                 return realMapIfNeeded.size();
581             } else {
582                 return this.names.length;
583             }
584         }
585
586         public java.util.Collection JavaDoc values() {
587             if (realMapIfNeeded != null) {
588                 return realMapIfNeeded.values();
589             } else {
590                 this.makeRealMap();
591                 return realMapIfNeeded.values();
592             }
593         }
594
595         public String JavaDoc toString() {
596             if (realMapIfNeeded != null) {
597                 return realMapIfNeeded.toString();
598             } else {
599                 StringBuffer JavaDoc outString = new StringBuffer JavaDoc("{");
600                 for (int i = 0; i < names.length; i++) {
601                     if (i > 0) outString.append(',');
602                     outString.append('{');
603                     outString.append(names[i]);
604                     outString.append(',');
605                     outString.append(values[i]);
606                     outString.append('}');
607                 }
608                 outString.append('}');
609                 return outString.toString();
610             }
611         }
612
613         public int hashCode() {
614             if (realMapIfNeeded != null) {
615                 return realMapIfNeeded.hashCode();
616             } else {
617                 int hashCode = 0;
618                 for (int i = 0; i < names.length; i++) {
619                     //note that this calculation is done based on the calc specified in the Java java.util.Map interface
620
int tempNum = (names[i] == null ? 0 : names[i].hashCode()) ^
621                             (values[i] == null ? 0 : values[i].hashCode());
622                     hashCode += tempNum;
623                 }
624                 return hashCode;
625             }
626         }
627
628         public boolean equals(Object JavaDoc obj) {
629             if (realMapIfNeeded != null) {
630                 return realMapIfNeeded.equals(obj);
631             } else {
632                 Map JavaDoc mapObj = (Map JavaDoc) obj;
633
634                 //first check the size
635
if (mapObj.size() != names.length) return false;
636
637                 //okay, same size, now check each entry
638
for (int i = 0; i < names.length; i++) {
639                     //first check the name
640
if (!mapObj.containsKey(names[i])) return false;
641
642                     //if that passes, check the value
643
Object JavaDoc mapValue = mapObj.get(names[i]);
644                     if (mapValue == null) {
645                         if (values[i] != null) return false;
646                     } else {
647                         if (!mapValue.equals(values[i])) return false;
648                     }
649                 }
650
651                 return true;
652             }
653         }
654     }
655 }
656
Popular Tags