KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * $Id: UtilFormatOut.java 7099 2006-03-28 23:02:54Z 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.text.DateFormat JavaDoc;
27 import java.text.DecimalFormat JavaDoc;
28 import java.text.NumberFormat JavaDoc;
29 import java.text.ParseException JavaDoc;
30 import java.util.Locale JavaDoc;
31 import java.util.Currency JavaDoc;
32
33 /**
34  * General output formatting functions - mainly for helping in JSPs
35  *
36  * @author <a HREF="mailto:jonesde@ofbiz.org">David E. Jones</a>
37  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
38  * @version $Rev: 7099 $
39  * @since 2.0
40  */

41 public class UtilFormatOut {
42
43     public static final String JavaDoc module = UtilFormatOut.class.getName();
44
45     public static String JavaDoc safeToString(Object JavaDoc obj) {
46         if (obj != null) {
47             return obj.toString();
48         } else {
49             return "";
50         }
51     }
52     
53     // ------------------- price format handlers -------------------
54
static DecimalFormat JavaDoc priceDecimalFormat = new DecimalFormat JavaDoc("#,##0.00");
55     static DecimalFormat JavaDoc priceNumberFormat = new DecimalFormat JavaDoc("##0.00");
56
57     /** Formats a Double representing a price into a string
58      * @param price The price Double to be formatted
59      * @return A String with the formatted price
60      */

61     public static String JavaDoc formatPrice(Double JavaDoc price) {
62         if (price == null) return "";
63         return formatPrice(price.doubleValue());
64     }
65
66     /** Formats a double representing a price into a string
67      * @param price The price double to be formatted
68      * @return A String with the formatted price
69      */

70     public static String JavaDoc formatPrice(double price) {
71         return priceDecimalFormat.format(price);
72     }
73
74     public static Double JavaDoc formatPriceNumber(double price) {
75         try {
76             return new Double JavaDoc(priceDecimalFormat.parse(formatPrice(price)).doubleValue());
77         } catch (ParseException JavaDoc e) {
78             Debug.logError(e, module);
79             return new Double JavaDoc(price);
80         }
81     }
82
83     /** Formats a double into a properly formatted currency string based on isoCode and Locale
84      * @param price The price double to be formatted
85      * @param isoCode the currency ISO code
86      * @param locale The Locale used to format the number
87      * @return A String with the formatted price
88      */

89     public static String JavaDoc formatCurrency(double price, String JavaDoc isoCode, Locale JavaDoc locale) {
90         //Debug.logInfo("formatting currency: " + price + ", isoCode: " + isoCode + ", locale: " + locale, module);
91
com.ibm.icu.text.NumberFormat nf = com.ibm.icu.text.NumberFormat.getCurrencyInstance(locale);
92         if (isoCode != null && isoCode.length() > 1) {
93             nf.setCurrency(com.ibm.icu.util.Currency.getInstance(isoCode));
94         } else {
95             Debug.logWarning("No isoCode specified to format currency value:" + price, module);
96         }
97         return nf.format(price);
98     }
99
100     /** Formats a double into a properly formatted currency string based on isoCode and Locale
101      * @param price The price Double to be formatted
102      * @param isoCode the currency ISO code
103      * @param locale The Locale used to format the number
104      * @return A String with the formatted price
105      */

106     public static String JavaDoc formatCurrency(Double JavaDoc price, String JavaDoc isoCode, Locale JavaDoc locale) {
107         return formatCurrency(price.doubleValue(), isoCode, locale);
108     }
109
110     /** Formats a Double into a properly spelled out number string based on Locale
111      * @param amount The amount Double to be formatted
112      * @param locale The Locale used to format the number
113      * @return A String with the formatted number
114      */

115     public static String JavaDoc formatSpelledOutAmount(Double JavaDoc amount, Locale JavaDoc locale) {
116         return formatSpelledOutAmount(amount.doubleValue(), locale);
117     }
118     /** Formats a double into a properly spelled out number string based on Locale
119      * @param amount The amount double to be formatted
120      * @param locale The Locale used to format the number
121      * @return A String with the formatted number
122      */

123     public static String JavaDoc formatSpelledOutAmount(double amount, Locale JavaDoc locale) {
124         //Debug.logInfo("formatting currency: " + price + ", isoCode: " + isoCode + ", locale: " + locale, module);
125
com.ibm.icu.text.NumberFormat nf = new com.ibm.icu.text.RuleBasedNumberFormat(locale, com.ibm.icu.text.RuleBasedNumberFormat.SPELLOUT);
126         return nf.format(amount);
127     }
128
129     /** Formats a double into a properly formatted string, with two decimals, based on Locale
130      * @param amount The amount double to be formatted
131      * @param locale The Locale used to format the number
132      * @return A String with the formatted amount
133      */

134     // This method should be used in place of formatPrice because it is locale aware.
135
public static String JavaDoc formatAmount(double amount, Locale JavaDoc locale) {
136         com.ibm.icu.text.NumberFormat nf = com.ibm.icu.text.NumberFormat.getInstance(locale);
137         nf.setMinimumFractionDigits(2);
138         nf.setMaximumFractionDigits(2);
139         return nf.format(amount);
140     }
141
142     // ------------------- percentage format handlers -------------------
143
static DecimalFormat JavaDoc percentageDecimalFormat = new DecimalFormat JavaDoc("##0.##%");
144
145     /** Formats a Double representing a percentage into a string
146      * @param percentage The percentage Double to be formatted
147      * @return A String with the formatted percentage
148      */

149     public static String JavaDoc formatPercentage(Double JavaDoc percentage) {
150         if (percentage == null) return "";
151         return formatPercentage(percentage.doubleValue());
152     }
153
154     /** Formats a double representing a percentage into a string
155      * @param percentage The percentage double to be formatted
156      * @return A String with the formatted percentage
157      */

158     public static String JavaDoc formatPercentage(double percentage) {
159         return percentageDecimalFormat.format(percentage);
160     }
161
162     // ------------------- quantity format handlers -------------------
163
static DecimalFormat JavaDoc quantityDecimalFormat = new DecimalFormat JavaDoc("#,##0.###");
164
165     /** Formats an Long representing a quantity into a string
166      * @param quantity The quantity Long to be formatted
167      * @return A String with the formatted quantity
168      */

169     public static String JavaDoc formatQuantity(Long JavaDoc quantity) {
170         if (quantity == null)
171             return "";
172         else
173             return formatQuantity(quantity.doubleValue());
174     }
175
176     /** Formats an int representing a quantity into a string
177      * @param quantity The quantity long to be formatted
178      * @return A String with the formatted quantity
179      */

180     public static String JavaDoc formatQuantity(long quantity) {
181         return formatQuantity((double) quantity);
182     }
183
184     /** Formats an Integer representing a quantity into a string
185      * @param quantity The quantity Integer to be formatted
186      * @return A String with the formatted quantity
187      */

188     public static String JavaDoc formatQuantity(Integer JavaDoc quantity) {
189         if (quantity == null)
190             return "";
191         else
192             return formatQuantity(quantity.doubleValue());
193     }
194
195     /** Formats an int representing a quantity into a string
196      * @param quantity The quantity int to be formatted
197      * @return A String with the formatted quantity
198      */

199     public static String JavaDoc formatQuantity(int quantity) {
200         return formatQuantity((double) quantity);
201     }
202
203     /** Formats a Float representing a quantity into a string
204      * @param quantity The quantity Float to be formatted
205      * @return A String with the formatted quantity
206      */

207     public static String JavaDoc formatQuantity(Float JavaDoc quantity) {
208         if (quantity == null)
209             return "";
210         else
211             return formatQuantity(quantity.doubleValue());
212     }
213
214     /** Formats a float representing a quantity into a string
215      * @param quantity The quantity float to be formatted
216      * @return A String with the formatted quantity
217      */

218     public static String JavaDoc formatQuantity(float quantity) {
219         return formatQuantity((double) quantity);
220     }
221
222     /** Formats an Double representing a quantity into a string
223      * @param quantity The quantity Double to be formatted
224      * @return A String with the formatted quantity
225      */

226     public static String JavaDoc formatQuantity(Double JavaDoc quantity) {
227         if (quantity == null)
228             return "";
229         else
230             return formatQuantity(quantity.doubleValue());
231     }
232
233     /** Formats an double representing a quantity into a string
234      * @param quantity The quantity double to be formatted
235      * @return A String with the formatted quantity
236      */

237     public static String JavaDoc formatQuantity(double quantity) {
238         return quantityDecimalFormat.format(quantity);
239     }
240     
241     public static String JavaDoc formatPaddedNumber(long number, int numericPadding) {
242         StringBuffer JavaDoc outStrBfr = new StringBuffer JavaDoc(Long.toString(number));
243         while (numericPadding > outStrBfr.length()) {
244             outStrBfr.insert(0, '0');
245         }
246         return outStrBfr.toString();
247     }
248     
249     public static String JavaDoc formatPaddingRemove(String JavaDoc original) {
250         if (original == null) return null;
251         StringBuffer JavaDoc orgBuf = new StringBuffer JavaDoc(original);
252         while (orgBuf.length() > 0 && orgBuf.charAt(0) == '0') {
253             orgBuf.deleteCharAt(0);
254         }
255         return orgBuf.toString();
256     }
257     
258     
259     // ------------------- date handlers -------------------
260
/** Formats a String timestamp into a nice string
261      * @param timestamp String timestamp to be formatted
262      * @return A String with the formatted date/time
263      */

264     public static String JavaDoc formatDate(java.sql.Timestamp JavaDoc timestamp) {
265         if (timestamp == null)
266             return "";
267         DateFormat JavaDoc df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.FULL);
268         java.util.Date JavaDoc date = (java.util.Date JavaDoc) timestamp;
269         return df.format(date);
270     }
271
272     // ------------------- null string handlers -------------------
273
/** Checks to see if the passed Object is null, if it is returns an empty but non-null string, otherwise calls toString() on the object
274      * @param obj1 The passed Object
275      * @return The toString() of the passed Object if not null, otherwise an empty non-null String
276      */

277     public static String JavaDoc makeString(Object JavaDoc obj1) {
278         if (obj1 != null)
279             return obj1.toString();
280         else
281             return "";
282     }
283
284     /** Checks to see if the passed string is null, if it is returns an empty but non-null string.
285      * @param string1 The passed String
286      * @return The passed String if not null, otherwise an empty non-null String
287      */

288     public static String JavaDoc checkNull(String JavaDoc string1) {
289         if (string1 != null)
290             return string1;
291         else
292             return "";
293     }
294
295     /** Returns the first passed String if not null, otherwise the second if not null, otherwise an empty but non-null String.
296      * @param string1 The first passed String
297      * @param string2 The second passed String
298      * @return The first passed String if not null, otherwise the second if not null, otherwise an empty but non-null String
299      */

300     public static String JavaDoc checkNull(String JavaDoc string1, String JavaDoc string2) {
301         if (string1 != null)
302             return string1;
303         else if (string2 != null)
304             return string2;
305         else
306             return "";
307     }
308
309     /** Returns the first passed String if not null, otherwise the second if not null, otherwise the third if not null, otherwise an empty but non-null String.
310      * @param string1 The first passed String
311      * @param string2 The second passed String
312      * @param string3 The third passed String
313      * @return The first passed String if not null, otherwise the second if not null, otherwise the third if not null, otherwise an empty but non-null String
314      */

315     public static String JavaDoc checkNull(String JavaDoc string1, String JavaDoc string2, String JavaDoc string3) {
316         if (string1 != null)
317             return string1;
318         else if (string2 != null)
319             return string2;
320         else if (string3 != null)
321             return string3;
322         else
323             return "";
324     }
325
326     /** Returns the first passed String if not null, otherwise the second if not null, otherwise the third if not null, otherwise the fourth if not null, otherwise an empty but non-null String.
327      * @param string1 The first passed String
328      * @param string2 The second passed String
329      * @param string3 The third passed String
330      * @param string4 The fourth passed String
331      * @return The first passed String if not null, otherwise the second if not null, otherwise the third if not null, otherwise the fourth if not null, otherwise an empty but non-null String
332      */

333     public static String JavaDoc checkNull(String JavaDoc string1, String JavaDoc string2, String JavaDoc string3, String JavaDoc string4) {
334         if (string1 != null)
335             return string1;
336         else if (string2 != null)
337             return string2;
338         else if (string3 != null)
339             return string3;
340         else if (string4 != null)
341             return string4;
342         else
343             return "";
344     }
345
346     /** Returns <code>pre + base + post</code> if base String is not null or empty, otherwise an empty but non-null String.
347      * @param base The base String
348      * @param pre The pre String
349      * @param post The post String
350      * @return <code>pre + base + post</code> if base String is not null or empty, otherwise an empty but non-null String.
351      */

352     public static String JavaDoc ifNotEmpty(String JavaDoc base, String JavaDoc pre, String JavaDoc post) {
353         if (base != null && base.length() > 0)
354             return pre + base + post;
355         else
356             return "";
357     }
358
359     /** Returns the first passed String if not empty, otherwise the second if not empty, otherwise an empty but non-null String.
360      * @param string1 The first passed String
361      * @param string2 The second passed String
362      * @return The first passed String if not empty, otherwise the second if not empty, otherwise an empty but non-null String
363      */

364     public static String JavaDoc checkEmpty(String JavaDoc string1, String JavaDoc string2) {
365         if (string1 != null && string1.length() > 0)
366             return string1;
367         else if (string2 != null && string2.length() > 0)
368             return string2;
369         else
370             return "";
371     }
372
373     /** Returns the first passed String if not empty, otherwise the second if not empty, otherwise the third if not empty, otherwise an empty but non-null String.
374      * @param string1 The first passed String
375      * @param string2 The second passed String
376      * @param string3 The third passed String
377      * @return The first passed String if not empty, otherwise the second if not empty, otherwise the third if not empty, otherwise an empty but non-null String
378      */

379     public static String JavaDoc checkEmpty(String JavaDoc string1, String JavaDoc string2, String JavaDoc string3) {
380         if (string1 != null && string1.length() > 0)
381             return string1;
382         else if (string2 != null && string2.length() > 0)
383             return string2;
384         else if (string3 != null && string3.length() > 0)
385             return string3;
386         else
387             return "";
388     }
389
390     // ------------------- web encode handlers -------------------
391
/** Encodes an HTTP URL query String, replacing characters used for other things in HTTP URL query strings, but not touching the separator characters '?', '=', and '&'
392      * @param query The plain query String
393      * @return The encoded String
394      */

395     public static String JavaDoc encodeQuery(String JavaDoc query) {
396         String JavaDoc retString;
397
398         retString = replaceString(query, "%", "%25");
399         retString = replaceString(retString, " ", "%20");
400         return retString;
401     }
402
403     /** Encodes a single HTTP URL query value, replacing characters used for other things in HTTP URL query strings
404      * @param query The plain query value String
405      * @return The encoded String
406      */

407     public static String JavaDoc encodeQueryValue(String JavaDoc query) {
408         String JavaDoc retString;
409
410         retString = replaceString(query, "%", "%25");
411         retString = replaceString(retString, " ", "%20");
412         retString = replaceString(retString, "&", "%26");
413         retString = replaceString(retString, "?", "%3F");
414         retString = replaceString(retString, "=", "%3D");
415         return retString;
416     }
417
418     /** Replaces all occurances of oldString in mainString with newString
419      * @param mainString The original string
420      * @param oldString The string to replace
421      * @param newString The string to insert in place of the old
422      * @return mainString with all occurances of oldString replaced by newString
423      */

424     public static String JavaDoc replaceString(String JavaDoc mainString, String JavaDoc oldString, String JavaDoc newString) {
425         return StringUtil.replaceString(mainString, oldString, newString);
426     }
427
428     /** Decodes a single query value from an HTTP URL parameter, replacing %ASCII values with characters
429      * @param query The encoded query value String
430      * @return The plain, decoded String
431      */

432     public static String JavaDoc decodeQueryValue(String JavaDoc query) {
433         String JavaDoc retString;
434
435         retString = replaceString(query, "%25", "%");
436         retString = replaceString(retString, "%20", " ");
437         retString = replaceString(retString, "%26", "&");
438         retString = replaceString(retString, "%3F", "?");
439         retString = replaceString(retString, "%3D", "=");
440         return retString;
441     }
442
443     // ------------------- web encode handlers -------------------
444
/** Encodes an XML string replacing the characters '<', '>', '"', ''', '&'
445      * @param inString The plain value String
446      * @return The encoded String
447      */

448     public static String JavaDoc encodeXmlValue(String JavaDoc inString) {
449         String JavaDoc retString = inString;
450
451         retString = StringUtil.replaceString(retString, "&", "&amp;");
452         retString = StringUtil.replaceString(retString, "<", "&lt;");
453         retString = StringUtil.replaceString(retString, ">", "&gt;");
454         retString = StringUtil.replaceString(retString, "\"", "&quot;");
455         retString = StringUtil.replaceString(retString, "'", "&apos;");
456         return retString;
457     }
458
459     public static String JavaDoc padString(String JavaDoc str, int setLen, boolean padEnd, char padChar) {
460         if (str == null) {
461             return null;
462         }
463         if (setLen == 0) {
464             return str;
465         }
466         int stringLen = str.length();
467         int diff = setLen - stringLen;
468         if (diff < 0) {
469             return str.substring(0, setLen);
470         } else {
471             String JavaDoc newString = new String JavaDoc();
472             if (padEnd) {
473                 newString = newString + str;
474             }
475             for (int i = 0; i < diff; i++) {
476                 newString = newString + padChar;
477             }
478             if (!padEnd) {
479                 newString = newString + str;
480             }
481             return newString;
482         }
483     }
484 }
485
Popular Tags