VectorFormat.java

  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.  *      https://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.  * This is not the original file distributed by the Apache Software Foundation
  19.  * It has been modified by the Hipparchus project
  20.  */

  21. package org.hipparchus.geometry;

  22. import java.text.FieldPosition;
  23. import java.text.NumberFormat;
  24. import java.text.ParsePosition;
  25. import java.util.Locale;

  26. import org.hipparchus.exception.MathIllegalStateException;
  27. import org.hipparchus.util.CompositeFormat;

  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.  * @param <V> Type of vector implementing Vector interface.
  44.  */
  45. public abstract class VectorFormat<S extends Space, V extends Vector<S,V>> {

  46.     /** The default prefix: "{". */
  47.     public static final String DEFAULT_PREFIX = "{";

  48.     /** The default suffix: "}". */
  49.     public static final String DEFAULT_SUFFIX = "}";

  50.     /** The default separator: ", ". */
  51.     public static final String DEFAULT_SEPARATOR = "; ";

  52.     /** Prefix. */
  53.     private final String prefix;

  54.     /** Suffix. */
  55.     private final String suffix;

  56.     /** Separator. */
  57.     private final String separator;

  58.     /** Trimmed prefix. */
  59.     private final String trimmedPrefix;

  60.     /** Trimmed suffix. */
  61.     private final String trimmedSuffix;

  62.     /** Trimmed separator. */
  63.     private final String trimmedSeparator;

  64.     /** The format used for components. */
  65.     private final NumberFormat format;

  66.     /**
  67.      * Create an instance with default settings.
  68.      * <p>The instance uses the default prefix, suffix and separator:
  69.      * "{", "}", and "; " and the default number format for components.</p>
  70.      */
  71.     protected VectorFormat() {
  72.         this(DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_SEPARATOR,
  73.              CompositeFormat.getDefaultNumberFormat());
  74.     }

  75.     /**
  76.      * Create an instance with a custom number format for components.
  77.      * @param format the custom format for components.
  78.      */
  79.     protected VectorFormat(final NumberFormat format) {
  80.         this(DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_SEPARATOR, format);
  81.     }

  82.     /**
  83.      * Create an instance with custom prefix, suffix and separator.
  84.      * @param prefix prefix to use instead of the default "{"
  85.      * @param suffix suffix to use instead of the default "}"
  86.      * @param separator separator to use instead of the default "; "
  87.      */
  88.     protected VectorFormat(final String prefix, final String suffix,
  89.                           final String separator) {
  90.         this(prefix, suffix, separator, CompositeFormat.getDefaultNumberFormat());
  91.     }

  92.     /**
  93.      * Create an instance with custom prefix, suffix, separator and format
  94.      * for components.
  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.      * @param format the custom format for components.
  99.      */
  100.     protected VectorFormat(final String prefix, final String suffix,
  101.                           final String separator, final NumberFormat format) {
  102.         this.prefix      = prefix;
  103.         this.suffix      = suffix;
  104.         this.separator   = separator;
  105.         trimmedPrefix    = prefix.trim();
  106.         trimmedSuffix    = suffix.trim();
  107.         trimmedSeparator = separator.trim();
  108.         this.format      = format;
  109.     }

  110.     /**
  111.      * Get the set of locales for which point/vector formats are available.
  112.      * <p>This is the same set as the {@link NumberFormat} set.</p>
  113.      * @return available point/vector format locales.
  114.      */
  115.     public static Locale[] getAvailableLocales() {
  116.         return NumberFormat.getAvailableLocales();
  117.     }

  118.     /**
  119.      * Get the format prefix.
  120.      * @return format prefix.
  121.      */
  122.     public String getPrefix() {
  123.         return prefix;
  124.     }

  125.     /**
  126.      * Get the format suffix.
  127.      * @return format suffix.
  128.      */
  129.     public String getSuffix() {
  130.         return suffix;
  131.     }

  132.     /**
  133.      * Get the format separator between components.
  134.      * @return format separator.
  135.      */
  136.     public String getSeparator() {
  137.         return separator;
  138.     }

  139.     /**
  140.      * Get the components format.
  141.      * @return components format.
  142.      */
  143.     public NumberFormat getFormat() {
  144.         return format;
  145.     }

  146.     /**
  147.      * Formats a {@link Vector} object to produce a string.
  148.      * @param vector the object to format.
  149.      * @return a formatted string.
  150.      */
  151.     public String format(Vector<S, V> vector) {
  152.         return format(vector, new StringBuffer(), new FieldPosition(0)).toString();
  153.     }

  154.     /**
  155.      * Formats a {@link Vector} object to produce a string.
  156.      * @param vector the object to format.
  157.      * @param toAppendTo where the text is to be appended
  158.      * @param pos On input: an alignment field, if desired. On output: the
  159.      *            offsets of the alignment field
  160.      * @return the value passed in as toAppendTo.
  161.      */
  162.     public abstract StringBuffer format(Vector<S, V> vector,
  163.                                         StringBuffer toAppendTo, FieldPosition pos);

  164.     /**
  165.      * Formats the coordinates of a {@link Vector} to produce a string.
  166.      * @param toAppendTo where the text is to be appended
  167.      * @param pos On input: an alignment field, if desired. On output: the
  168.      *            offsets of the alignment field
  169.      * @param coordinates coordinates of the object to format.
  170.      * @return the value passed in as toAppendTo.
  171.      */
  172.     protected StringBuffer format(StringBuffer toAppendTo, FieldPosition pos,
  173.                                   double ... coordinates) {

  174.         pos.setBeginIndex(0);
  175.         pos.setEndIndex(0);

  176.         // format prefix
  177.         toAppendTo.append(prefix);

  178.         // format components
  179.         for (int i = 0; i < coordinates.length; ++i) {
  180.             if (i > 0) {
  181.                 toAppendTo.append(separator);
  182.             }
  183.             CompositeFormat.formatDouble(coordinates[i], format, toAppendTo, pos);
  184.         }

  185.         // format suffix
  186.         toAppendTo.append(suffix);

  187.         return toAppendTo;

  188.     }

  189.     /**
  190.      * Parses a string to produce a {@link Vector} object.
  191.      * @param source the string to parse
  192.      * @return the parsed {@link Vector} object.
  193.      * @throws MathIllegalStateException if the beginning of the specified string
  194.      * cannot be parsed.
  195.      */
  196.     public abstract Vector<S, V> parse(String source) throws MathIllegalStateException;

  197.     /**
  198.      * Parses a string to produce a {@link Vector} object.
  199.      * @param source the string to parse
  200.      * @param pos input/output parsing parameter.
  201.      * @return the parsed {@link Vector} object.
  202.      */
  203.     public abstract Vector<S, V> parse(String source, ParsePosition pos);

  204.     /**
  205.      * Parses a string to produce an array of coordinates.
  206.      * @param dimension dimension of the space
  207.      * @param source the string to parse
  208.      * @param pos input/output parsing parameter.
  209.      * @return coordinates array.
  210.      */
  211.     protected double[] parseCoordinates(int dimension, String source, ParsePosition pos) {

  212.         int initialIndex = pos.getIndex();
  213.         double[] coordinates = new double[dimension];

  214.         // parse prefix
  215.         CompositeFormat.parseAndIgnoreWhitespace(source, pos);
  216.         if (!CompositeFormat.parseFixedstring(source, trimmedPrefix, pos)) {
  217.             return null; // NOPMD
  218.         }

  219.         for (int i = 0; i < dimension; ++i) {

  220.             // skip whitespace
  221.             CompositeFormat.parseAndIgnoreWhitespace(source, pos);

  222.             // parse separator
  223.             if (i > 0 && !CompositeFormat.parseFixedstring(source, trimmedSeparator, pos)) {
  224.                 return null; // NOPMD
  225.             }

  226.             // skip whitespace
  227.             CompositeFormat.parseAndIgnoreWhitespace(source, pos);

  228.             // parse coordinate
  229.             Number c = CompositeFormat.parseNumber(source, format, pos);
  230.             if (c == null) {
  231.                 // invalid coordinate
  232.                 // set index back to initial, error index should already be set
  233.                 pos.setIndex(initialIndex);
  234.                 return null; // NOPMD
  235.             }

  236.             // store coordinate
  237.             coordinates[i] = c.doubleValue();

  238.         }

  239.         // parse suffix
  240.         CompositeFormat.parseAndIgnoreWhitespace(source, pos);
  241.         if (!CompositeFormat.parseFixedstring(source, trimmedSuffix, pos)) {
  242.             return null; // NOPMD
  243.         }

  244.         return coordinates;

  245.     }

  246. }