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