001/*
002 * Units of Measurement Reference Implementation
003 * Copyright (c) 2005-2016, Jean-Marie Dautelle, Werner Keil, V2COM.
004 *
005 * All rights reserved.
006 *
007 * Redistribution and use in source and binary forms, with or without modification,
008 * are permitted provided that the following conditions are met:
009 *
010 * 1. Redistributions of source code must retain the above copyright notice,
011 *    this list of conditions and the following disclaimer.
012 *
013 * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
014 *    and the following disclaimer in the documentation and/or other materials provided with the distribution.
015 *
016 * 3. Neither the name of JSR-363 nor the names of its contributors may be used to endorse or promote products
017 *    derived from this software without specific prior written permission.
018 *
019 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
020 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
021 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
022 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
023 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
024 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
025 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
026 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
027 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
028 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
029 */
030package tec.units.ri.format;
031
032import java.io.IOException;
033import java.util.logging.Logger;
034
035import javax.measure.Unit;
036import javax.measure.format.ParserException;
037import javax.measure.format.UnitFormat;
038
039import tec.units.ri.AbstractUnit;
040
041/**
042 * <p>
043 * This class provides the interface for formatting and parsing {@link AbstractUnit units}.
044 * </p>
045 *
046 * <p>
047 * For all metric units, the 20 SI prefixes used to form decimal multiples and sub-multiples of SI units are recognized. For example:<br>
048 * <code>
049 * AbstractUnit.parse("m°C").equals(MetricPrefix.MILLI(Units.CELSIUS))
050 * AbstractUnit.parse("kW").equals(MetricPrefix.KILO(Units.WATT))</code>
051 * </p>
052 *
053 * @author <a href="mailto:jean-marie@dautelle.com">Jean-Marie Dautelle</a>
054 * @author <a href="mailto:units@catmedia.us">Werner Keil</a>
055 * @version 1.0, August 9, 2016
056 * 
057 */
058public abstract class AbstractUnitFormat implements UnitFormat {
059  /**
060   * serialVersionUID
061   */
062  // private static final long serialVersionUID = -2046025267890654321L;
063
064  protected static final Logger logger = Logger.getLogger(AbstractUnitFormat.class.getName());
065
066  /**
067   * Formats an object to produce a string. This is equivalent to <blockquote> {@link #format(Unit, StringBuilder) format}<code>(unit,
068   *         new StringBuilder()).toString();</code> </blockquote>
069   *
070   * @param obj
071   *          The object to format
072   * @return Formatted string.
073   * @exception IllegalArgumentException
074   *              if the Format cannot format the given object
075   */
076  public final String format(Unit<?> unit) {
077    if (unit instanceof AbstractUnit) {
078      return format((AbstractUnit<?>) unit, new StringBuilder()).toString();
079    } else {
080      try {
081        return (this.format(unit, new StringBuilder())).toString();
082      } catch (IOException ex) {
083        throw new ParserException(ex); // Should never happen.
084      }
085    }
086  }
087
088  /**
089   * Formats the specified unit.
090   *
091   * @param unit
092   *          the unit to format.
093   * @param appendable
094   *          the appendable destination.
095   * @return The appendable destination passed in as {@code appendable}, with formatted text appended.
096   * @throws IOException
097   *           if an error occurs.
098   */
099  public abstract Appendable format(Unit<?> unit, Appendable appendable) throws IOException;
100
101  /**
102   * Parses a portion of the specified <code>CharSequence</code> from the specified position to produce a unit. If there is no unit to parse
103   * {@link AbstractUnit#ONE} is returned.
104   *
105   * @param csq
106   *          the <code>CharSequence</code> to parse.
107   * @param index
108   *          the current parsing index.
109   * @return the unit parsed from the specified character sub-sequence.
110   * @throws IllegalArgumentException
111   *           if any problem occurs while parsing the specified character sequence (e.g. illegal syntax).
112   */
113  protected abstract Unit<?> parse(CharSequence csq, int index) throws IllegalArgumentException;
114
115  public boolean isLocaleSensitive() {
116    return false;
117  }
118
119  /**
120   * Convenience method equivalent to {@link #format(AbstractUnit, Appendable)} except it does not raise an IOException.
121   *
122   * @param unit
123   *          the unit to format.
124   * @param dest
125   *          the appendable destination.
126   * @return the specified <code>StringBuilder</code>.
127   */
128  final StringBuilder format(AbstractUnit<?> unit, StringBuilder dest) {
129    try {
130      return (StringBuilder) this.format(unit, (Appendable) dest);
131    } catch (IOException ex) {
132      throw new ParserException(ex); // Should never happen.
133    }
134  }
135}