View Javadoc
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.geometry;
19  
20  import java.text.FieldPosition;
21  import java.text.NumberFormat;
22  import java.text.ParsePosition;
23  import java.util.Locale;
24  
25  import org.apache.commons.math3.util.CompositeFormat;
26  import org.apache.commons.math3.exception.MathParseException;
27  
28  /**
29   * Formats a vector in components list format "{x; y; ...}".
30   * <p>The prefix and suffix "{" and "}" and the separator "; " can be replaced by
31   * any user-defined strings. The number format for components can be configured.</p>
32   * <p>White space is ignored at parse time, even if it is in the prefix, suffix
33   * or separator specifications. So even if the default separator does include a space
34   * character that is used at format time, both input string "{1;1;1}" and
35   * " { 1 ; 1 ; 1 } " will be parsed without error and the same vector will be
36   * returned. In the second case, however, the parse position after parsing will be
37   * just after the closing curly brace, i.e. just before the trailing space.</p>
38   * <p><b>Note:</b> using "," as a separator may interfere with the grouping separator
39   * of the default {@link NumberFormat} for the current locale. Thus it is advised
40   * to use a {@link NumberFormat} instance with disabled grouping in such a case.</p>
41   *
42   * @param <S> Type of the space.
43   * @since 3.0
44   */
45  public abstract class VectorFormat<S extends Space> {
46  
47      /** The default prefix: "{". */
48      public static final String DEFAULT_PREFIX = "{";
49  
50      /** The default suffix: "}". */
51      public static final String DEFAULT_SUFFIX = "}";
52  
53      /** The default separator: ", ". */
54      public static final String DEFAULT_SEPARATOR = "; ";
55  
56      /** Prefix. */
57      private final String prefix;
58  
59      /** Suffix. */
60      private final String suffix;
61  
62      /** Separator. */
63      private final String separator;
64  
65      /** Trimmed prefix. */
66      private final String trimmedPrefix;
67  
68      /** Trimmed suffix. */
69      private final String trimmedSuffix;
70  
71      /** Trimmed separator. */
72      private final String trimmedSeparator;
73  
74      /** The format used for components. */
75      private final NumberFormat format;
76  
77      /**
78       * Create an instance with default settings.
79       * <p>The instance uses the default prefix, suffix and separator:
80       * "{", "}", and "; " and the default number format for components.</p>
81       */
82      protected VectorFormat() {
83          this(DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_SEPARATOR,
84               CompositeFormat.getDefaultNumberFormat());
85      }
86  
87      /**
88       * Create an instance with a custom number format for components.
89       * @param format the custom format for components.
90       */
91      protected VectorFormat(final NumberFormat format) {
92          this(DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_SEPARATOR, format);
93      }
94  
95      /**
96       * Create an instance with custom prefix, suffix and separator.
97       * @param prefix prefix to use instead of the default "{"
98       * @param suffix suffix to use instead of the default "}"
99       * @param separator separator to use instead of the default "; "
100      */
101     protected VectorFormat(final String prefix, final String suffix,
102                           final String separator) {
103         this(prefix, suffix, separator, CompositeFormat.getDefaultNumberFormat());
104     }
105 
106     /**
107      * Create an instance with custom prefix, suffix, separator and format
108      * for components.
109      * @param prefix prefix to use instead of the default "{"
110      * @param suffix suffix to use instead of the default "}"
111      * @param separator separator to use instead of the default "; "
112      * @param format the custom format for components.
113      */
114     protected VectorFormat(final String prefix, final String suffix,
115                           final String separator, final NumberFormat format) {
116         this.prefix      = prefix;
117         this.suffix      = suffix;
118         this.separator   = separator;
119         trimmedPrefix    = prefix.trim();
120         trimmedSuffix    = suffix.trim();
121         trimmedSeparator = separator.trim();
122         this.format      = format;
123     }
124 
125     /**
126      * Get the set of locales for which point/vector formats are available.
127      * <p>This is the same set as the {@link NumberFormat} set.</p>
128      * @return available point/vector format locales.
129      */
130     public static Locale[] getAvailableLocales() {
131         return NumberFormat.getAvailableLocales();
132     }
133 
134     /**
135      * Get the format prefix.
136      * @return format prefix.
137      */
138     public String getPrefix() {
139         return prefix;
140     }
141 
142     /**
143      * Get the format suffix.
144      * @return format suffix.
145      */
146     public String getSuffix() {
147         return suffix;
148     }
149 
150     /**
151      * Get the format separator between components.
152      * @return format separator.
153      */
154     public String getSeparator() {
155         return separator;
156     }
157 
158     /**
159      * Get the components format.
160      * @return components format.
161      */
162     public NumberFormat getFormat() {
163         return format;
164     }
165 
166     /**
167      * Formats a {@link Vector} object to produce a string.
168      * @param vector the object to format.
169      * @return a formatted string.
170      */
171     public String format(Vector<S> vector) {
172         return format(vector, new StringBuffer(), new FieldPosition(0)).toString();
173     }
174 
175     /**
176      * Formats a {@link Vector} object to produce a string.
177      * @param vector the object to format.
178      * @param toAppendTo where the text is to be appended
179      * @param pos On input: an alignment field, if desired. On output: the
180      *            offsets of the alignment field
181      * @return the value passed in as toAppendTo.
182      */
183     public abstract StringBuffer format(Vector<S> vector,
184                                         StringBuffer toAppendTo, FieldPosition pos);
185 
186     /**
187      * Formats the coordinates of a {@link Vector} to produce a string.
188      * @param toAppendTo where the text is to be appended
189      * @param pos On input: an alignment field, if desired. On output: the
190      *            offsets of the alignment field
191      * @param coordinates coordinates of the object to format.
192      * @return the value passed in as toAppendTo.
193      */
194     protected StringBuffer format(StringBuffer toAppendTo, FieldPosition pos,
195                                   double ... coordinates) {
196 
197         pos.setBeginIndex(0);
198         pos.setEndIndex(0);
199 
200         // format prefix
201         toAppendTo.append(prefix);
202 
203         // format components
204         for (int i = 0; i < coordinates.length; ++i) {
205             if (i > 0) {
206                 toAppendTo.append(separator);
207             }
208             CompositeFormat.formatDouble(coordinates[i], format, toAppendTo, pos);
209         }
210 
211         // format suffix
212         toAppendTo.append(suffix);
213 
214         return toAppendTo;
215 
216     }
217 
218     /**
219      * Parses a string to produce a {@link Vector} object.
220      * @param source the string to parse
221      * @return the parsed {@link Vector} object.
222      * @throws MathParseException if the beginning of the specified string
223      * cannot be parsed.
224      */
225     public abstract Vector<S> parse(String source) throws MathParseException;
226 
227     /**
228      * Parses a string to produce a {@link Vector} object.
229      * @param source the string to parse
230      * @param pos input/output parsing parameter.
231      * @return the parsed {@link Vector} object.
232      */
233     public abstract Vector<S> parse(String source, ParsePosition pos);
234 
235     /**
236      * Parses a string to produce an array of coordinates.
237      * @param dimension dimension of the space
238      * @param source the string to parse
239      * @param pos input/output parsing parameter.
240      * @return coordinates array.
241      */
242     protected double[] parseCoordinates(int dimension, String source, ParsePosition pos) {
243 
244         int initialIndex = pos.getIndex();
245         double[] coordinates = new double[dimension];
246 
247         // parse prefix
248         CompositeFormat.parseAndIgnoreWhitespace(source, pos);
249         if (!CompositeFormat.parseFixedstring(source, trimmedPrefix, pos)) {
250             return null;
251         }
252 
253         for (int i = 0; i < dimension; ++i) {
254 
255             // skip whitespace
256             CompositeFormat.parseAndIgnoreWhitespace(source, pos);
257 
258             // parse separator
259             if (i > 0 && !CompositeFormat.parseFixedstring(source, trimmedSeparator, pos)) {
260                 return null;
261             }
262 
263             // skip whitespace
264             CompositeFormat.parseAndIgnoreWhitespace(source, pos);
265 
266             // parse coordinate
267             Number c = CompositeFormat.parseNumber(source, format, pos);
268             if (c == null) {
269                 // invalid coordinate
270                 // set index back to initial, error index should already be set
271                 pos.setIndex(initialIndex);
272                 return null;
273             }
274 
275             // store coordinate
276             coordinates[i] = c.doubleValue();
277 
278         }
279 
280         // parse suffix
281         CompositeFormat.parseAndIgnoreWhitespace(source, pos);
282         if (!CompositeFormat.parseFixedstring(source, trimmedSuffix, pos)) {
283             return null;
284         }
285 
286         return coordinates;
287 
288     }
289 
290 }