1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements.  See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License.  You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 
18 package org.apache.commons.math3.fraction;
19 
20 import java.io.Serializable;
21 import java.text.FieldPosition;
22 import java.text.NumberFormat;
23 import java.text.ParsePosition;
24 import java.util.Locale;
25 
26 import org.apache.commons.math3.exception.NullArgumentException;
27 import org.apache.commons.math3.exception.util.LocalizedFormats;
28 
29 /**
30  * Common part shared by both {@link FractionFormat} and {@link BigFractionFormat}.
31  * @since 2.0
32  */
33 public abstract class AbstractFormat extends NumberFormat implements Serializable {
34 
35     /** Serializable version identifier. */
36     private static final long serialVersionUID = -6981118387974191891L;
37 
38     /** The format used for the denominator. */
39     private NumberFormat denominatorFormat;
40 
41     /** The format used for the numerator. */
42     private NumberFormat numeratorFormat;
43 
44     /**
45      * Create an improper formatting instance with the default number format
46      * for the numerator and denominator.
47      */
AbstractFormat()48     protected AbstractFormat() {
49         this(getDefaultNumberFormat());
50     }
51 
52     /**
53      * Create an improper formatting instance with a custom number format for
54      * both the numerator and denominator.
55      * @param format the custom format for both the numerator and denominator.
56      */
AbstractFormat(final NumberFormat format)57     protected AbstractFormat(final NumberFormat format) {
58         this(format, (NumberFormat) format.clone());
59     }
60 
61     /**
62      * Create an improper formatting instance with a custom number format for
63      * the numerator and a custom number format for the denominator.
64      * @param numeratorFormat the custom format for the numerator.
65      * @param denominatorFormat the custom format for the denominator.
66      */
AbstractFormat(final NumberFormat numeratorFormat, final NumberFormat denominatorFormat)67     protected AbstractFormat(final NumberFormat numeratorFormat,
68                              final NumberFormat denominatorFormat) {
69         this.numeratorFormat   = numeratorFormat;
70         this.denominatorFormat = denominatorFormat;
71     }
72 
73     /**
74      * Create a default number format.  The default number format is based on
75      * {@link NumberFormat#getNumberInstance(java.util.Locale)}. The only
76      * customization is the maximum number of BigFraction digits, which is set to 0.
77      * @return the default number format.
78      */
getDefaultNumberFormat()79     protected static NumberFormat getDefaultNumberFormat() {
80         return getDefaultNumberFormat(Locale.getDefault());
81     }
82 
83     /**
84      * Create a default number format.  The default number format is based on
85      * {@link NumberFormat#getNumberInstance(java.util.Locale)}. The only
86      * customization is the maximum number of BigFraction digits, which is set to 0.
87      * @param locale the specific locale used by the format.
88      * @return the default number format specific to the given locale.
89      */
getDefaultNumberFormat(final Locale locale)90     protected static NumberFormat getDefaultNumberFormat(final Locale locale) {
91         final NumberFormat nf = NumberFormat.getNumberInstance(locale);
92         nf.setMaximumFractionDigits(0);
93         nf.setParseIntegerOnly(true);
94         return nf;
95     }
96 
97     /**
98      * Access the denominator format.
99      * @return the denominator format.
100      */
getDenominatorFormat()101     public NumberFormat getDenominatorFormat() {
102         return denominatorFormat;
103     }
104 
105     /**
106      * Access the numerator format.
107      * @return the numerator format.
108      */
getNumeratorFormat()109     public NumberFormat getNumeratorFormat() {
110         return numeratorFormat;
111     }
112 
113     /**
114      * Modify the denominator format.
115      * @param format the new denominator format value.
116      * @throws NullArgumentException if {@code format} is {@code null}.
117      */
setDenominatorFormat(final NumberFormat format)118     public void setDenominatorFormat(final NumberFormat format) {
119         if (format == null) {
120             throw new NullArgumentException(LocalizedFormats.DENOMINATOR_FORMAT);
121         }
122         this.denominatorFormat = format;
123     }
124 
125     /**
126      * Modify the numerator format.
127      * @param format the new numerator format value.
128      * @throws NullArgumentException if {@code format} is {@code null}.
129      */
setNumeratorFormat(final NumberFormat format)130     public void setNumeratorFormat(final NumberFormat format) {
131         if (format == null) {
132             throw new NullArgumentException(LocalizedFormats.NUMERATOR_FORMAT);
133         }
134         this.numeratorFormat = format;
135     }
136 
137     /**
138      * Parses <code>source</code> until a non-whitespace character is found.
139      * @param source the string to parse
140      * @param pos input/output parsing parameter.  On output, <code>pos</code>
141      *        holds the index of the next non-whitespace character.
142      */
parseAndIgnoreWhitespace(final String source, final ParsePosition pos)143     protected static void parseAndIgnoreWhitespace(final String source,
144                                                    final ParsePosition pos) {
145         parseNextCharacter(source, pos);
146         pos.setIndex(pos.getIndex() - 1);
147     }
148 
149     /**
150      * Parses <code>source</code> until a non-whitespace character is found.
151      * @param source the string to parse
152      * @param pos input/output parsing parameter.
153      * @return the first non-whitespace character.
154      */
parseNextCharacter(final String source, final ParsePosition pos)155     protected static char parseNextCharacter(final String source,
156                                              final ParsePosition pos) {
157          int index = pos.getIndex();
158          final int n = source.length();
159          char ret = 0;
160 
161          if (index < n) {
162              char c;
163              do {
164                  c = source.charAt(index++);
165              } while (Character.isWhitespace(c) && index < n);
166              pos.setIndex(index);
167 
168              if (index < n) {
169                  ret = c;
170              }
171          }
172 
173          return ret;
174     }
175 
176     /**
177      * Formats a double value as a fraction and appends the result to a StringBuffer.
178      *
179      * @param value the double value to format
180      * @param buffer StringBuffer to append to
181      * @param position On input: an alignment field, if desired. On output: the
182      *            offsets of the alignment field
183      * @return a reference to the appended buffer
184      * @see #format(Object, StringBuffer, FieldPosition)
185      */
186     @Override
format(final double value, final StringBuffer buffer, final FieldPosition position)187     public StringBuffer format(final double value,
188                                final StringBuffer buffer, final FieldPosition position) {
189         return format(Double.valueOf(value), buffer, position);
190     }
191 
192 
193     /**
194      * Formats a long value as a fraction and appends the result to a StringBuffer.
195      *
196      * @param value the long value to format
197      * @param buffer StringBuffer to append to
198      * @param position On input: an alignment field, if desired. On output: the
199      *            offsets of the alignment field
200      * @return a reference to the appended buffer
201      * @see #format(Object, StringBuffer, FieldPosition)
202      */
203     @Override
format(final long value, final StringBuffer buffer, final FieldPosition position)204     public StringBuffer format(final long value,
205                                final StringBuffer buffer, final FieldPosition position) {
206         return format(Long.valueOf(value), buffer, position);
207     }
208 
209 }
210