001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.apache.commons.math3.geometry;
019
020import java.text.FieldPosition;
021import java.text.NumberFormat;
022import java.text.ParsePosition;
023import java.util.Locale;
024
025import org.apache.commons.math3.util.CompositeFormat;
026import org.apache.commons.math3.exception.MathParseException;
027
028/**
029 * Formats a vector in components list format "{x; y; ...}".
030 * <p>The prefix and suffix "{" and "}" and the separator "; " can be replaced by
031 * any user-defined strings. The number format for components can be configured.</p>
032 * <p>White space is ignored at parse time, even if it is in the prefix, suffix
033 * or separator specifications. So even if the default separator does include a space
034 * character that is used at format time, both input string "{1;1;1}" and
035 * " { 1 ; 1 ; 1 } " will be parsed without error and the same vector will be
036 * returned. In the second case, however, the parse position after parsing will be
037 * just after the closing curly brace, i.e. just before the trailing space.</p>
038 * <p><b>Note:</b> using "," as a separator may interfere with the grouping separator
039 * of the default {@link NumberFormat} for the current locale. Thus it is advised
040 * to use a {@link NumberFormat} instance with disabled grouping in such a case.</p>
041 *
042 * @param <S> Type of the space.
043 * @since 3.0
044 */
045public abstract class VectorFormat<S extends Space> {
046
047    /** The default prefix: "{". */
048    public static final String DEFAULT_PREFIX = "{";
049
050    /** The default suffix: "}". */
051    public static final String DEFAULT_SUFFIX = "}";
052
053    /** The default separator: ", ". */
054    public static final String DEFAULT_SEPARATOR = "; ";
055
056    /** Prefix. */
057    private final String prefix;
058
059    /** Suffix. */
060    private final String suffix;
061
062    /** Separator. */
063    private final String separator;
064
065    /** Trimmed prefix. */
066    private final String trimmedPrefix;
067
068    /** Trimmed suffix. */
069    private final String trimmedSuffix;
070
071    /** Trimmed separator. */
072    private final String trimmedSeparator;
073
074    /** The format used for components. */
075    private final NumberFormat format;
076
077    /**
078     * Create an instance with default settings.
079     * <p>The instance uses the default prefix, suffix and separator:
080     * "{", "}", and "; " and the default number format for components.</p>
081     */
082    protected VectorFormat() {
083        this(DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_SEPARATOR,
084             CompositeFormat.getDefaultNumberFormat());
085    }
086
087    /**
088     * Create an instance with a custom number format for components.
089     * @param format the custom format for components.
090     */
091    protected VectorFormat(final NumberFormat format) {
092        this(DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_SEPARATOR, format);
093    }
094
095    /**
096     * Create an instance with custom prefix, suffix and separator.
097     * @param prefix prefix to use instead of the default "{"
098     * @param suffix suffix to use instead of the default "}"
099     * @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}