01 /*
02 * Copyright 2008-2014 the original author or authors.
03 *
04 * Licensed under the Apache License, Version 2.0 (the "License");
05 * you may not use this file except in compliance with the License.
06 * You may obtain a copy of the License at
07 *
08 * http://www.apache.org/licenses/LICENSE-2.0
09 *
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 griffon.core.editors;
17
18 import griffon.core.formatters.BigDecimalFormatter;
19 import griffon.core.formatters.Formatter;
20
21 import java.math.BigDecimal;
22 import java.math.BigInteger;
23
24 import static griffon.util.GriffonNameUtils.isBlank;
25
26 /**
27 * @author Andres Almiray
28 * @since 2.0.0
29 */
30 public class BigDecimalPropertyEditor extends AbstractPropertyEditor {
31 protected void setValueInternal(Object value) {
32 if (null == value) {
33 super.setValueInternal(null);
34 } else if (value instanceof CharSequence) {
35 handleAsString(String.valueOf(value));
36 } else if (value instanceof Number) {
37 handleAsNumber((Number) value);
38 } else {
39 throw illegalValue(value, BigDecimal.class);
40 }
41 }
42
43 private void handleAsString(String str) {
44 try {
45 super.setValueInternal(isBlank(str) ? null : new BigDecimal(str));
46 } catch (NumberFormatException e) {
47 throw illegalValue(str, BigDecimal.class, e);
48 }
49 }
50
51 private void handleAsNumber(Number number) {
52 if (number instanceof BigInteger) {
53 super.setValueInternal(new BigDecimal((BigInteger) number));
54 } else if (number instanceof BigDecimal) {
55 super.setValueInternal(number);
56 } else {
57 super.setValueInternal(number.longValue());
58 }
59 }
60
61 protected Formatter<BigDecimal> resolveFormatter() {
62 return isBlank(getFormat()) ? null : new BigDecimalFormatter(getFormat());
63 }
64 }
|