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    
018    package org.apache.commons.math3.geometry;
019    
020    import java.text.FieldPosition;
021    import java.text.NumberFormat;
022    import java.text.ParsePosition;
023    import java.util.Locale;
024    
025    import org.apache.commons.math3.util.CompositeFormat;
026    import 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     *
039     * @param <S> Type of the space.
040     * @version $Id: VectorFormat.java 1416643 2012-12-03 19:37:14Z tn $
041     * @since 3.0
042     */
043    public abstract class VectorFormat<S extends Space> {
044    
045        /** The default prefix: "{". */
046        public static final String DEFAULT_PREFIX = "{";
047    
048        /** The default suffix: "}". */
049        public static final String DEFAULT_SUFFIX = "}";
050    
051        /** The default separator: ", ". */
052        public static final String DEFAULT_SEPARATOR = "; ";
053    
054        /** Prefix. */
055        private final String prefix;
056    
057        /** Suffix. */
058        private final String suffix;
059    
060        /** Separator. */
061        private final String separator;
062    
063        /** Trimmed prefix. */
064        private final String trimmedPrefix;
065    
066        /** Trimmed suffix. */
067        private final String trimmedSuffix;
068    
069        /** Trimmed separator. */
070        private final String trimmedSeparator;
071    
072        /** The format used for components. */
073        private final NumberFormat format;
074    
075        /**
076         * Create an instance with default settings.
077         * <p>The instance uses the default prefix, suffix and separator:
078         * "{", "}", and "; " and the default number format for components.</p>
079         */
080        protected VectorFormat() {
081            this(DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_SEPARATOR,
082                 CompositeFormat.getDefaultNumberFormat());
083        }
084    
085        /**
086         * Create an instance with a custom number format for components.
087         * @param format the custom format for components.
088         */
089        protected VectorFormat(final NumberFormat format) {
090            this(DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_SEPARATOR, format);
091        }
092    
093        /**
094         * Create an instance with custom prefix, suffix and separator.
095         * @param prefix prefix to use instead of the default "{"
096         * @param suffix suffix to use instead of the default "}"
097         * @param separator separator to use instead of the default "; "
098         */
099        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) {
258                    if (!CompositeFormat.parseFixedstring(source, trimmedSeparator, pos)) {
259                        return null;
260                    }
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    }