1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.kuali.rice.krad.web.bind;
17
18 import org.apache.log4j.Logger;
19 import org.kuali.rice.core.api.util.RiceKeyConstants;
20 import org.kuali.rice.core.api.util.type.KualiDecimal;
21 import org.kuali.rice.core.api.util.type.KualiInteger;
22 import org.kuali.rice.core.web.format.FormatException;
23
24 import java.beans.PropertyEditorSupport;
25 import java.text.DecimalFormat;
26 import java.text.NumberFormat;
27 import java.text.ParseException;
28
29
30
31
32
33
34
35
36 public class UifCurrencyEditor extends PropertyEditorSupport {
37
38 private static Logger LOG = Logger.getLogger(UifCurrencyEditor.class);
39
40
41
42
43
44
45 @Override
46 public String getAsText() {
47 Object obj = this.getValue();
48
49 LOG.debug("format '" + obj + "'");
50 if (obj == null)
51 return null;
52
53 NumberFormat formatter = getCurrencyInstanceUsingParseBigDecimal();
54 String string = null;
55
56 try {
57 Number number = (Number) obj;
58 if (obj instanceof KualiInteger) {
59 formatter.setMaximumFractionDigits(0);
60 }
61 string = formatter.format(number.doubleValue());
62 } catch (IllegalArgumentException e) {
63 throw new FormatException("formatting", RiceKeyConstants.ERROR_CURRENCY, obj.toString(), e);
64 } catch (ClassCastException e) {
65 throw new FormatException("formatting", RiceKeyConstants.ERROR_CURRENCY, obj.toString(), e);
66 }
67
68 return string;
69 }
70
71
72
73
74
75
76
77 private NumberFormat getCurrencyInstanceUsingParseBigDecimal() {
78 NumberFormat formatter = NumberFormat.getCurrencyInstance();
79 if (formatter instanceof DecimalFormat) {
80 ((DecimalFormat) formatter).setParseBigDecimal(true);
81 }
82 return formatter;
83 }
84
85
86
87
88
89
90
91
92 @Override
93 public void setAsText(String text) {
94 this.setValue(convertToObject(text));
95 }
96
97
98
99
100
101
102
103
104
105
106
107 protected Object convertToObject(String text) {
108 KualiDecimal value = null;
109
110 LOG.debug("convertToObject '" + text + "'");
111
112 if (text != null) {
113 text = text.trim();
114 NumberFormat formatter = getCurrencyInstanceUsingParseBigDecimal();
115
116
117 if (formatter instanceof DecimalFormat) {
118 String prefix = ((DecimalFormat) formatter).getPositivePrefix();
119 String suffix = ((DecimalFormat) formatter).getPositiveSuffix();
120 if (!prefix.equals("") && !text.startsWith(prefix)) {
121 text = prefix.concat(text);
122 }
123 if (!suffix.equals("") && !text.endsWith(suffix)) {
124 text = text.concat(suffix);
125 }
126 }
127 try {
128 Number parsedNumber = formatter.parse(text);
129 value = new KualiDecimal(parsedNumber.toString());
130 } catch (NumberFormatException e) {
131 throw new FormatException("parsing", RiceKeyConstants.ERROR_CURRENCY, text, e);
132 } catch (ParseException e) {
133 throw new FormatException("parsing", RiceKeyConstants.ERROR_CURRENCY, text, e);
134 }
135 }
136 return value;
137 }
138
139 }