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