1 package org.apache.maven.util;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 import java.text.DecimalFormat;
22
23 import org.apache.commons.logging.Log;
24 import org.apache.commons.logging.LogFactory;
25
26 /**
27 * Formatting tool for use with the DVSL toolbox. This class contains
28 * static methods to assist in formatting needs that can't be done or
29 * shouldn't be done in a DVSL stylesheet.
30 *
31 * @author <a href="mailto:pete-apache-dev@kazmier.com">Pete Kazmier</a>
32 * @version $Id: DVSLFormatter.java 517014 2007-03-11 21:15:50Z ltheussl $
33 * @todo move to org.apache.maven.util or make a jelly tag
34 */
35 public class DVSLFormatter
36 {
37 /**
38 * Instance of a formatter.
39 */
40 private static DecimalFormat formatter = new DecimalFormat();
41
42 /**
43 * Log for debug output
44 */
45 private final static Log LOGGER = LogFactory.getLog( DVSLFormatter.class );
46
47 /**
48 * Formats a string as a number using the specified pattern.
49 * Patterns are specified using the same format as <code>
50 * java.text.DecimalFormat</code>.
51 * <p/>
52 * This method is thread-hostile.
53 *
54 * @see java.text.DecimalFormat
55 * @param value The number to format.
56 * @param pattern The pattern used to format.
57 * @return A string formatted using the specified pattern.
58 * @throws IllegalArgumentException If an invalid pattern is
59 * specified.
60 */
61 public static final String formatNumber( final String value, final String pattern )
62 {
63 LOGGER.debug( "value = '" + value + "', pattern = '" + pattern + "'" );
64 if ( ( pattern == null ) || ( value == null ) )
65 {
66 return "<error formatting: '" + value + "' with '" + pattern + "'>";
67 }
68
69 String ret = null;
70
71 try
72 {
73 formatter = new DecimalFormat( pattern );
74 Number valueAsNumber;
75 try
76 {
77 valueAsNumber = Double.valueOf( value.trim() );
78 }
79 catch ( NumberFormatException nfe )
80 {
81 valueAsNumber = new Double( "0.00" );
82 }
83
84 if ( ( pattern.indexOf( "." ) != -1 ) || ( pattern.indexOf( "%" ) != -1 ) )
85 {
86
87 ret = formatter.format( valueAsNumber.doubleValue() );
88 }
89 else
90 {
91
92 formatter.setParseIntegerOnly( true );
93 ret = formatter.format( valueAsNumber.longValue() );
94 }
95 LOGGER.debug( "ret='" + ret + "'" );
96
97 }
98 catch ( Exception e )
99 {
100 LOGGER.error( "<error formatting: '" + value + "' with '" + pattern + "'>", e );
101 return "<error formatting: '" + value + "' with '" + pattern + "'>";
102 }
103
104 return ret;
105 }
106 }