ShortFormatter.java
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.formatters;
17 
18 import javax.annotation.Nullable;
19 import java.text.DecimalFormat;
20 import java.text.NumberFormat;
21 
22 import static griffon.util.GriffonNameUtils.isBlank;
23 
24 /**
25  @author Andres Almiray
26  @since 2.0.0
27  */
28 public class ShortFormatter extends AbstractFormatter<Short> {
29     public static final String PATTERN_CURRENCY = "currency";
30     public static final String PATTERN_PERCENT = "percent";
31 
32     private final NumberFormat numberFormat;
33 
34     public ShortFormatter() {
35         this(null);
36     }
37 
38     public ShortFormatter(@Nullable String pattern) {
39         if (isBlank(pattern)) {
40             numberFormat = NumberFormat.getIntegerInstance();
41         else if (PATTERN_CURRENCY.equalsIgnoreCase(pattern)) {
42             numberFormat = NumberFormat.getCurrencyInstance();
43         else if (PATTERN_PERCENT.equalsIgnoreCase(pattern)) {
44             numberFormat = NumberFormat.getPercentInstance();
45         else {
46             numberFormat = new DecimalFormat(pattern);
47             numberFormat.setParseIntegerOnly(true);
48         }
49     }
50 
51     @Nullable
52     public String format(@Nullable Short number) {
53         return number == null null : numberFormat.format(number);
54     }
55 
56     @Nullable
57     @Override
58     public Short parse(@Nullable String strthrows ParseException {
59         if (isBlank(str)) return null;
60         try {
61             return numberFormat.parse(str).shortValue();
62         catch (java.text.ParseException e) {
63             throw new ParseException(e);
64         }
65     }
66 }