Class Formatter

java.lang.Object
org.apache.sis.io.wkt.Formatter
All Implemented Interfaces:
Localized

public class Formatter extends Object implements Localized
Provides support methods for formatting a Well Known Text (WKT).

Formatter instances are created by WKTFormat and given to the FormattableObject.formatTo(Formatter) method of the object to format. Formatter provides the following services:

  • A series of append(…) methods to be invoked by the formatTo(Formatter) implementations.
  • Contextual information. In particular, the contextual units depend on the enclosing WKT element.
  • A flag for declaring the object unformattable.
Since:
0.4
Version:
1.1
See Also:
  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    private org.opengis.metadata.citation.Citation
    The preferred authority for objects or parameter names.
    (package private) static final String
    The value of X364.BACKGROUND_DEFAULT.sequence(), hard-coded for avoiding X364 class loading.
    (package private) static final int
    Accuracy of geographic bounding boxes, in number of fraction digits.
    private StringBuffer
    The buffer in which to format.
    private int
    Incremented when setColor(ElementKind) is invoked, and decremented when resetColor() is invoked.
    private Colors
    The colors to use for this formatter, or null for no syntax coloring.
    private Convention
    The preferred convention for objects or parameter names.
    private final DateFormat
    The object to use for formatting dates.
    private final FieldPosition
    Dummy field position.
    private int
    Index of the first character in the buffer where the element content will be formatted.
    private final List<FormattableObject>
    The enclosing WKT element being formatted.
    private final Locale
    The locale for error messages (not for formatting).
    (package private) static final String
    The value of X364.FOREGROUND_DEFAULT.sequence(), hard-coded for avoiding X364 class loading.
    private long
    A bits mask of elements which defined a contextual units.
    private boolean
    true if the last formatted element was invalid WKT and shall be highlighted with syntactic coloration.
    private byte
    The amount of spaces to use in indentation, or -1 if indentation is disabled.
    private boolean
    true if we are in the process of formatting the optional complementary attributes.
    private IntegerList
    Indices where to insert additional margin, or null if none.
    private int
    Maximum number of elements to show in lists, or Integer.MAX_VALUE if unlimited.
    private final Locale
    The locale for the localization of international strings.
    private byte
    -1 for short keywords, +1 for long keywords or 0 for the default.
    private int
    The amount of space to write on the left side of each line.
    private final NumberFormat
    The object to use for formatting numbers.
    private boolean
    true if a new line were requested during the execution of append(FormattableObject).
    private final String
    The value of Symbols.getSeparator() without trailing spaces, followed by the system line separator.
    private final Symbols
    The symbols to use for this formatter.
    private byte
    1 if keywords shall be converted to upper cases, or -1 for lower cases.
    (package private) Transliterator
    Transliterator.IDENTITY for preserving non-ASCII characters.
    private final UnitFormat
    The object to use for formatting unit symbols.
    private final Map<javax.measure.Unit<?>,javax.measure.Unit<?>>
    The contextual units for writing lengths, angles or other type of measurements.
    (package private) boolean
    true if this Formatter should verify the validity of characters in quoted texts.
    private static final int
    Maximal accuracy of vertical extents, in number of fraction digits.
    private Warnings
    The warnings that occurred during WKT formatting, or null if none.
  • Constructor Summary

    Constructors
    Constructor
    Description
    Creates a new formatter instance with the default configuration.
    Formatter(Locale locale, Locale errorLocale, Symbols symbols, NumberFormat numberFormat, DateFormat dateFormat, UnitFormat unitFormat)
    Constructor for private use by WKTFormat only.
    Formatter(Convention convention, Symbols symbols, int indentation)
    Creates a new formatter instance with the specified convention, symbols and indentation.
  • Method Summary

    Modifier and Type
    Method
    Description
    <Q extends javax.measure.Quantity<Q>>
    javax.measure.Unit<Q>
    addContextualUnit(javax.measure.Unit<Q> unit)
    Adds a unit to use for the next measurements of the quantity Q.
    void
    append(boolean value)
    Appends a boolean value.
    void
    append(double number)
    Appends an floating point value.
    void
    append(long number)
    Appends an integer value.
    void
    append(String text, ElementKind type)
    Appends a character string between quotes.
    void
    append(Date date)
    Appends a date.
    void
    append(javax.measure.Unit<?> unit)
    Appends a unit in a Unit[…] element or one of the specialized elements.
    void
    Appends the given FormattableObject.
    void
    append(Vector[] rows, int... fractionDigits)
    Appends rows of numbers.
    void
    append(org.opengis.metadata.extent.GeographicBoundingBox bbox, int fractionDigits)
    Appends the given geographic bounding box in a BBOX[…] element.
    void
    append(org.opengis.referencing.operation.MathTransform transform)
    Appends the given math transform, typically (but not necessarily) in a PARAM_MT[…] element.
    void
    append(org.opengis.util.CodeList<?> code)
    Appends an enumeration or code list value.
    void
    Appends an object or an array of objects.
    private void
    appendComplement(org.opengis.referencing.IdentifiedObject object, FormattableObject parent, FormattableObject gp)
    Appends the optional complementary attributes common to many IdentifiedObject subtypes.
    (package private) final boolean
    Tries to append an object of the KEYWORD[something] form.
    private void
    appendExact(double number)
    Appends a number which is assumed to have no rounding error greater than the limit of IEEE 754 accuracy.
    private void
    appendForSubtypes(org.opengis.referencing.IdentifiedObject object)
    Appends the anchor, scope and domain of validity of the given object.
    private void
    appendOnNewLine(String keyword, org.opengis.util.InternationalString text, ElementKind type)
    Appends an international text in an element having the given keyword.
    private void
    appendPreset(double number)
    Appends the given number without any change to the NumberFormat setting.
    private void
    Conditionally appends a separator to the buffer, if needed.
    private void
    Appends the given temporal extent, if non-null.
    (package private) final boolean
    Tries to append a small unit of information like number, date, boolean, code list, character string or an array of those.
    private void
    Appends the given vertical extent, if non-null.
    (package private) final void
    Appends the warnings after the WKT string.
    (package private) final void
    Clears this formatter before formatting a new object.
    private void
    closeElement(boolean newLine)
    Closes the element opened by openElement(boolean, String).
    private void
    closeQuote(int fromIndex)
    Double or delete any closing quote character that may appear at or after the given index, then append the closing quote character.
    (package private) final void
    configure(Convention convention, org.opengis.metadata.citation.Citation authority, Colors colors, byte toUpperCase, byte longKeywords, byte indentation, int listSizeLimit)
    Sets the convention, authority, colors and indentation to use for formatting WKT elements.
    Delegates the formatting to another FormattableObject implementation.
    Returns the convention to use for formatting the WKT.
    Returns the enclosing WKT element, or null if element being formatted is the root.
    final Locale
    Returns the locale to use for localizing InternationalString instances.
    private static String
    getName(Class<?> unformattable)
    Returns the name of the GeoAPI interface implemented by the given class.
    final org.opengis.metadata.citation.Citation
    Returns the preferred authority for choosing the projection and parameter names.
    Returns a mapper between Java character sequences and the characters to write in WKT.
    (package private) final Warnings
    Returns the warnings, or null if none.
    boolean
    hasContextualUnit(int depth)
    Returns true if the element at the given depth specified a contextual unit.
    void
    indent(int amount)
    Increases or decreases the indentation.
    boolean
    Returns true if the WKT written by this formatter is not strictly compliant to the WKT specification.
    void
    Request a line separator before the next element to format.
    private void
    openElement(boolean newLine, String keyword)
    Appends a separator if needed, then opens a new element.
    private void
    quote(String text, ElementKind type)
    Appends the given string as a quoted text.
    private void
    Appends in the buffer the ANSI escape sequence for resetting the color to the default.
    void
    restoreContextualUnit(javax.measure.Unit<?> unit, javax.measure.Unit<?> previous)
    Restores the contextual unit to its previous state before the call to addContextualUnit(Unit).
    (package private) final void
    Sets the destination buffer.
    private void
    Appends in the buffer the ANSI escape sequence for the given kind of element.
    void
    setInvalidWKT(Class<?> unformattable, Exception cause)
    Marks the current WKT representation of the given class as not strictly compliant with the WKT specification.
    private void
    setInvalidWKT(String invalidElement, Exception cause)
    Implementation of public setInvalidWKT(…) methods.
    void
    setInvalidWKT(org.opengis.referencing.IdentifiedObject unformattable, Exception cause)
    Marks the current WKT representation of the given object as not strictly compliant with the WKT specification.
    shortOrLong(String shortKeyword, String longKeyword)
    Selects a short or long keyword depending on the KeywordStyle value.
    <Q extends javax.measure.Quantity<Q>>
    javax.measure.Unit<Q>
    toContextualUnit(javax.measure.Unit<Q> unit)
    Returns the unit to use instead of the given one, or unit if there is no replacement.
    Returns a string representation of this formatter for debugging purpose.
    Returns the WKT formatted by this object.
    private Warnings
    Returns the object where to store warnings.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
  • Field Details

    • BBOX_ACCURACY

      static final int BBOX_ACCURACY
      Accuracy of geographic bounding boxes, in number of fraction digits. We use the accuracy recommended by ISO 19162.
      See Also:
    • VERTICAL_ACCURACY

      private static final int VERTICAL_ACCURACY
      Maximal accuracy of vertical extents, in number of fraction digits. The value used here is arbitrary and may change in any future SIS version.
      See Also:
    • FOREGROUND_DEFAULT

      static final String FOREGROUND_DEFAULT
      The value of X364.FOREGROUND_DEFAULT.sequence(), hard-coded for avoiding X364 class loading.
      See Also:
    • BACKGROUND_DEFAULT

      static final String BACKGROUND_DEFAULT
      The value of X364.BACKGROUND_DEFAULT.sequence(), hard-coded for avoiding X364 class loading.
      See Also:
    • locale

      private final Locale locale
      The locale for the localization of international strings. This is not the same than Symbols.getLocale().
      See Also:
    • symbols

      private final Symbols symbols
      The symbols to use for this formatter.
      See Also:
    • separatorNewLine

      private final String separatorNewLine
      The value of Symbols.getSeparator() without trailing spaces, followed by the system line separator. Computed by Symbols.separatorNewLine() and stored for reuse.
    • colors

      private Colors colors
      The colors to use for this formatter, or null for no syntax coloring. If non-null, the terminal must be ANSI X3.64 compatible. The default value is null.
      See Also:
    • convention

      private Convention convention
      The preferred convention for objects or parameter names. This field should never be null.
      See Also:
    • authority

      private org.opengis.metadata.citation.Citation authority
      The preferred authority for objects or parameter names.
      See Also:
    • transliterator

      Transliterator transliterator
      Transliterator.IDENTITY for preserving non-ASCII characters. The default value is Transliterator.DEFAULT, which causes replacements like "é" → "e" in all elements except REMARKS["…"]. May also be a user supplied transliterator.
      See Also:
    • verifyCharacterValidity

      boolean verifyCharacterValidity
      true if this Formatter should verify the validity of characters in quoted texts. ISO 19162 restricts quoted texts to ASCII characters with addition of degree symbol (°).
    • enclosingElements

      private final List<FormattableObject> enclosingElements
      The enclosing WKT element being formatted.
      See Also:
    • units

      private final Map<javax.measure.Unit<?>,javax.measure.Unit<?>> units
      The contextual units for writing lengths, angles or other type of measurements. A unit not present in this map means that the "natural" unit of the WKT element shall be used. This value is set for example by "GEOGCS", which force its enclosing "PRIMEM" to take the same units than itself.
      See Also:
    • hasContextualUnit

      private long hasContextualUnit
      A bits mask of elements which defined a contextual units. The rightmost bit is for the current element. The bit before the rightmost is for the parent of current element, etc.
      See Also:
    • numberFormat

      private final NumberFormat numberFormat
      The object to use for formatting numbers.
    • dateFormat

      private final DateFormat dateFormat
      The object to use for formatting dates.
    • unitFormat

      private final UnitFormat unitFormat
      The object to use for formatting unit symbols.
    • dummy

      private final FieldPosition dummy
      Dummy field position.
    • buffer

      private StringBuffer buffer
      The buffer in which to format. Consider this field as final. The only method to change (indirectly) the value of this field is WKTFormat.format(Object, Appendable).
      See Also:
    • elementStart

      private int elementStart
      Index of the first character in the buffer where the element content will be formatted. This is set after the opening bracket and is used for determining if a separator needs to be appended.
      See Also:
    • toUpperCase

      private byte toUpperCase
      1 if keywords shall be converted to upper cases, or -1 for lower cases.
      See Also:
    • longKeywords

      private byte longKeywords
      -1 for short keywords, +1 for long keywords or 0 for the default.
    • listSizeLimit

      private int listSizeLimit
      Maximum number of elements to show in lists, or Integer.MAX_VALUE if unlimited. If a list is longer than this length, only the first and the last elements will be shown. This limit applies in particular to MathTransform parameter values of double[] type, since those parameters may be large interpolation tables.
      See Also:
    • colorApplied

      private int colorApplied
      Incremented when setColor(ElementKind) is invoked, and decremented when resetColor() is invoked. Used in order to prevent child elements to overwrite the colors decided by enclosing elements.
    • indentation

      private byte indentation
      The amount of spaces to use in indentation, or -1 if indentation is disabled.
      See Also:
    • margin

      private int margin
      The amount of space to write on the left side of each line. This amount is increased by indentation every time a FormattableObject is appended in a new indentation level.
    • keywordSpaceAt

      private IntegerList keywordSpaceAt
      Indices where to insert additional margin, or null if none. The margin to insert will be the the width of the keyword (e.g. "BOX"), which is usually unknown to Formatter until FormattableObject finished to write the element. This field is usually null, unless formatting geometries.
    • requestNewLine

      private boolean requestNewLine
      true if a new line were requested during the execution of append(FormattableObject). This is used to determine if the next UNIT and ID elements shall appear on a new line.
    • isComplement

      private boolean isComplement
      true if we are in the process of formatting the optional complementary attributes. Those attributes are SCOPE, AREA, BBOX, VERTICALEXTENT, TIMEEXTENT, ID (previously known as AUTHORITY) and REMARKS, and have a special treatment: they are written by append(FormattableObject) after the formatTo(Formatter) method returned.
      See Also:
    • highlightError

      private boolean highlightError
      true if the last formatted element was invalid WKT and shall be highlighted with syntactic coloration. This field has no effect if colors is null. This field is reset to false after the invalid part has been processed by append(FormattableObject), in order to highlight only the first erroneous element without clearing the warnings value.
    • warnings

      private Warnings warnings
      The warnings that occurred during WKT formatting, or null if none.
      See Also:
    • errorLocale

      private final Locale errorLocale
      The locale for error messages (not for formatting).
      See Also:
  • Constructor Details

    • Formatter

      public Formatter()
      Creates a new formatter instance with the default configuration.
    • Formatter

      public Formatter(Convention convention, Symbols symbols, int indentation)
      Creates a new formatter instance with the specified convention, symbols and indentation.
      Parameters:
      convention - the convention to use.
      symbols - the symbols.
      indentation - the amount of spaces to use in indentation for WKT formatting, or WKTFormat.SINGLE_LINE for formatting the whole WKT on a single line.
    • Formatter

      Formatter(Locale locale, Locale errorLocale, Symbols symbols, NumberFormat numberFormat, DateFormat dateFormat, UnitFormat unitFormat)
      Constructor for private use by WKTFormat only. This allows to use the number format created by WKTFormat.createFormat(Class), which may be overridden by the user.
      Parameters:
      locale - the locale for the localization of international strings.
      errorLocale - the locale for error messages (not for parsing), or null for the system default.
      symbols - the symbols to use for this formatter.
      numberFormat - the object to use for formatting numbers.
      dateFormat - the object to use for formatting dates.
      unitFormat - the object to use for formatting unit symbols.
  • Method Details

    • setBuffer

      final void setBuffer(StringBuffer buffer)
      Sets the destination buffer. Used by WKTFormat.format(Object, Appendable) only.
    • configure

      final void configure(Convention convention, org.opengis.metadata.citation.Citation authority, Colors colors, byte toUpperCase, byte longKeywords, byte indentation, int listSizeLimit)
      Sets the convention, authority, colors and indentation to use for formatting WKT elements. This method does not validate the argument — validation must be done by the caller.
      Parameters:
      convention - the convention, or null for the default value.
      authority - the authority, or null for inferring it from the convention.
      colors - the syntax coloring, or null if none.
      toUpperCase - whether keywords shall be converted to upper cases.
      longKeywords - -1 for short keywords, +1 for long keywords or 0 for the default.
      indentation - the amount of spaces to use in indentation for WKT formatting, or WKTFormat.SINGLE_LINE.
      listSizeLimit - maximum number of elements to show in lists, or Integer.MAX_VALUE if unlimited.
    • getConvention

      public final Convention getConvention()
      Returns the convention to use for formatting the WKT. The default is Convention.WKT2.
      Returns:
      the convention (never null).
      See Also:
    • getTransliterator

      public final Transliterator getTransliterator()
      Returns a mapper between Java character sequences and the characters to write in WKT. The intent is to specify how to write characters that are not allowed in WKT strings according ISO 19162 specification. Return values can be:
      Returns:
      the mapper between Java character sequences and the characters to write in WKT.
      Since:
      0.6
      See Also:
    • getNameAuthority

      public final org.opengis.metadata.citation.Citation getNameAuthority()
      Returns the preferred authority for choosing the projection and parameter names.

      The preferred authority can be set by the WKTFormat.setNameAuthority(Citation) method. This is not necessarily the authority who created the object to format.

      Example: The EPSG name of the EPSG:6326 datum is "World Geodetic System 1984". However if the preferred authority is OGC, then the formatted datum name will rather look like "WGS84" (the exact string depends on the object aliases).
      Returns:
      the authority for projection and parameter names.
      See Also:
    • getLocale

      public final Locale getLocale()
      Returns the locale to use for localizing InternationalString instances. This is not the locale for formatting dates and numbers.
      Specified by:
      getLocale in interface Localized
      Returns:
      the locale to use for localizing international strings.
    • setColor

      private void setColor(ElementKind type)
      Appends in the buffer the ANSI escape sequence for the given kind of element. This method does nothing unless syntax coloring has been explicitly enabled.
    • resetColor

      private void resetColor()
      Appends in the buffer the ANSI escape sequence for resetting the color to the default. This method does nothing unless syntax coloring has been explicitly enabled.
    • newLine

      public void newLine()
      Request a line separator before the next element to format. Invoking this method before any append(…) method call will cause the next element to appear on the next line.

      This method has no effect in any of the following cases:

      • This method has already been invoked before the next append(…).
      • The indentation is WKTFormat.SINGLE_LINE.
    • indent

      public void indent(int amount)
      Increases or decreases the indentation. A value of +1 increases the indentation by the amount of spaces specified at construction time, and a value of -1 reduces it by the same amount.
      Parameters:
      amount - +1 for increasing the indentation, or -1 for decreasing it, or 0 for no-op.
    • shortOrLong

      public String shortOrLong(String shortKeyword, String longKeyword)
      Selects a short or long keyword depending on the KeywordStyle value. This method can be used by FormattableObject.formatTo(Formatter) implementations for choosing the return value.
      Parameters:
      shortKeyword - the keyword to return if the style is KeywordStyle.SHORT.
      longKeyword - the keyword to return if the style is KeywordStyle.LONG.
      Returns:
      the short or long keyword depending on the keyword style setting.
      Since:
      0.6
      See Also:
    • appendSeparator

      private void appendSeparator()
      Conditionally appends a separator to the buffer, if needed. This method does nothing if there is currently no element at the buffer end.
    • openElement

      private void openElement(boolean newLine, String keyword)
      Appends a separator if needed, then opens a new element.
      Parameters:
      newLine - true for invoking newLine() first.
      keyword - the element keyword (e.g. "DATUM", "AXIS", etc).
    • closeElement

      private void closeElement(boolean newLine)
      Closes the element opened by openElement(boolean, String).
      Parameters:
      newLine - true for invoking newLine() last.
    • append

      public void append(FormattableObject object)
      Appends the given FormattableObject. This method performs the following steps:
      • Invoke object.formatTo(this).
      • Prepend the keyword returned by the above method call (e.g. "GEOCS").
      • If the given object is an instance of IdentifiedObject, then append complementary information:
      Complementary WKT elements
      WKT 2 elementWKT 1 elementFor types
      Anchor[…] Datum
      Scope[…] ReferenceSystem, Datum, CoordinateOperation
      Area[…] ReferenceSystem, Datum, CoordinateOperation
      BBox[…] ReferenceSystem, Datum, CoordinateOperation
      VerticalExtent[…] ReferenceSystem, Datum, CoordinateOperation
      TimeExtent[…] ReferenceSystem, Datum, CoordinateOperation
      Id[…]Authority[…]IdentifiedObject
      Remarks[…] ReferenceSystem, CoordinateOperation
      Parameters:
      object - the formattable object to append to the WKT, or null if none.
    • appendComplement

      private void appendComplement(org.opengis.referencing.IdentifiedObject object, FormattableObject parent, FormattableObject gp)
      Appends the optional complementary attributes common to many IdentifiedObject subtypes. Those attributes are ANCHOR, SCOPE, AREA, BBOX, VERTICALEXTENT, TIMEEXTENT, ID (previously known as AUTHORITY) and REMARKS, and have a special treatment: they are written by append(FormattableObject) after the formatTo(Formatter) method returned.

      The ID[<name>,<code>,…] element is normally written only for the root element (unless the convention is INTERNAL), but there is various exceptions to this rule. If formatted, the ID element will be by default on the same line than the enclosing element (e.g. SPHEROID["Clarke 1866", …, ID["EPSG", 7008]]). Other example:

      For non-internal conventions, all elements other than ID[…] are formatted only for CoordinateOperation and root ReferenceSystem instances, with an exception for remarks of ReferenceSystem embedded inside CoordinateOperation. Those restrictions are our interpretation of the following ISO 19162 requirement:
      (…snip…) <scope extent identifier remark> is a collection of four optional attributes which may be applied to a coordinate reference system, a coordinate operation or a boundCRS. (…snip…) Identifier (…snip…) may also be utilised for components of these objects although this is not recommended except for coordinate operation methods (including map projections) and parameters. (…snip…) A <remark> can be included within the descriptions of source and target CRS embedded within a coordinate transformation as well as within the coordinate transformation itself.
    • appendForSubtypes

      private void appendForSubtypes(org.opengis.referencing.IdentifiedObject object)
      Appends the anchor, scope and domain of validity of the given object. Those information are available only for ReferenceSystem, Datum and CoordinateOperation objects.
    • append

      public void append(org.opengis.metadata.extent.GeographicBoundingBox bbox, int fractionDigits)
      Appends the given geographic bounding box in a BBOX[…] element. Longitude and latitude values will be formatted in decimal degrees. Longitudes are relative to the Greenwich meridian, with values increasing toward East. Latitudes values are increasing toward North.

      Numerical precision

      The ISO 19162 standards recommends to format those values with only 2 decimal digits. This is because GeographicBoundingBox does not specify the datum, so this box is an approximated information only.
      Parameters:
      bbox - the geographic bounding box to append to the WKT, or null.
      fractionDigits - the number of fraction digits to use. The recommended value is 2.
    • appendVerticalExtent

      private void appendVerticalExtent(MeasurementRange<Double> range)
      Appends the given vertical extent, if non-null. This method chooses an accuracy from the vertical span. Examples:
      • VerticalExtent[102, 108, LengthUnit["m", 1]]” (Δz = 6)
      • VerticalExtent[100.2, 100.8, LengthUnit["m", 1]]” (Δz = 0.6)
      Note that according ISO 19162, heights are positive toward up and relative to an unspecified mean sea level. It is caller's responsibility to ensure that the given range complies with that specification as much as possible.
    • appendTemporalExtent

      private void appendTemporalExtent(Range<Date> range)
      Appends the given temporal extent, if non-null. Examples:
      • TemporalExtent[1980-04-12, 1980-04-18]
      • TemporalExtent[1980-04-12T18:00:00.0Z, 1980-04-12T21:00:00.0Z]
    • append

      public void append(org.opengis.referencing.operation.MathTransform transform)
      Appends the given math transform, typically (but not necessarily) in a PARAM_MT[…] element.
      Parameters:
      transform - the transform object to append to the WKT, or null if none.
    • appendOnNewLine

      private void appendOnNewLine(String keyword, org.opengis.util.InternationalString text, ElementKind type)
      Appends an international text in an element having the given keyword. Since this method is typically invoked for long descriptions, the element will be written on its own line.
      Example:
      • Scope["Large scale topographic mapping and cadastre."]
      • Area["Netherlands offshore."]
      Parameters:
      keyword - the camel-case keyword. Example: "Scope", "Area" or "Remarks".
      text - the text, or null if none.
      type - the key of the colors to apply if syntax coloring is enabled.
    • append

      public void append(String text, ElementKind type)
      Appends a character string between quotes. The element separator will be written before the text if needed.
      Parameters:
      text - the string to format to the WKT, or null if none.
      type - the key of the colors to apply if syntax coloring is enabled, or null if none.
    • quote

      private void quote(String text, ElementKind type)
      Appends the given string as a quoted text. If the given string contains the closing quote character, that character will be doubled (WKT 2) or deleted (WKT 1). We check for the closing quote only because it is the character that the parser will look for determining the text end.
    • closeQuote

      private void closeQuote(int fromIndex)
      Double or delete any closing quote character that may appear at or after the given index, then append the closing quote character. The action taken for the quote character depends on the WKT version:
      • For WKT 2, double the quote as specified in the standard.
      • For WKT 1, conservatively delete the quote because the standard does not said what to do.
    • append

      public void append(org.opengis.util.CodeList<?> code)
      Appends an enumeration or code list value. The element separator will be written before the code list if needed.

      For the WKT 2 format, this method uses the ISO name if available (for example "northEast"). For the WKT 1 format, this method uses the programmatic name instead (for example "NORTH_EAST").

      Parameters:
      code - the code list to append to the WKT, or null if none.
    • append

      public void append(Date date)
      Appends a date. The element separator will be written before the date if needed.
      Parameters:
      date - the date to append to the WKT, or null if none.
    • append

      public void append(boolean value)
      Appends a boolean value. The element separator will be written before the boolean if needed.
      Parameters:
      value - the boolean to append to the WKT.
    • append

      public void append(long number)
      Appends an integer value. The element separator will be written before the number if needed.
      Parameters:
      number - the integer to append to the WKT.
    • append

      public void append(double number)
      Appends an floating point value. The element separator will be written before the number if needed.
      Parameters:
      number - the floating point value to append to the WKT.
    • append

      public void append(Vector[] rows, int... fractionDigits)
      Appends rows of numbers. Each number is separated by a space, and each row is separated by a comma. Rows usually have all the same length, but this is not mandatory. This method can be used for formatting geometries or matrix.
      Parameters:
      rows - the rows to append, or null if none.
      fractionDigits - the number of fraction digits for each column in a row, or null for default. A precision can be specified for each column because those columns are often different dimensions of a Coordinate Reference System (CRS), each with their own units of measurement. If a row contains more numbers than fractionDigits.length, then the last value in this array is repeated for all remaining row numbers.
      Since:
      1.0
    • appendPreset

      private void appendPreset(double number)
      Appends the given number without any change to the NumberFormat setting. Caller shall ensure that the following method has been invoked prior this method call:
    • appendExact

      private void appendExact(double number)
      Appends a number which is assumed to have no rounding error greater than the limit of IEEE 754 accuracy. This method is invoked for formatting the unit conversion factors, which are defined by the Unit library rather than specified by the user. The given number is formatted by Double.toString(double) both for accuracy and for automatic usage of scientific notation. If the given number is an integer, then it formatted without the trailing ".0".
    • append

      public void append(javax.measure.Unit<?> unit)
      Appends a unit in a Unit[…] element or one of the specialized elements. Specialized elements are AngleUnit, LengthUnit, ScaleUnit, ParametricUnit and TimeUnit. By default, specialized unit keywords are used with the WKT 2 convention.
      Example: append(Units.KILOMETRE) will append "LengthUnit["km", 1000]" to the WKT.
      Parameters:
      unit - the unit to append to the WKT, or null if none.
      See Also:
    • appendAny

      public void appendAny(Object value)
      Appends an object or an array of objects. This method performs the following choices:
      • If the given value is null, then this method appends the "null" string (without quotes).
      • Otherwise if the given value is an array, then this method appends the opening sequence symbol, formats all elements by invoking this method recursively, then appends the closing sequence symbol.
      • Otherwise if the value type is assignable to the argument type of one of the append(…) methods in this class, then the formatting will be delegated to that method.
      • Otherwise the given value is appended as a quoted text with its toString() representation.
      Parameters:
      value - the value to append to the WKT, or null.
    • appendValue

      final boolean appendValue(Object value)
      Tries to append a small unit of information like number, date, boolean, code list, character string or an array of those. The key difference between this method and appendElement(Object) is that the values formatted by this appendValue(Object) method do not have keyword.
      Returns:
      true on success, or false if the given type is not recognized.
    • appendElement

      final boolean appendElement(Object value)
      Tries to append an object of the KEYWORD[something] form. The given value is typically, but not necessarily, a FormattableObject object or an instance of an interface that can be converted to FormattableObject.
      Returns:
      true on success, or false if the given type is not recognized.
    • delegateTo

      public String delegateTo(Object other) throws UnformattableObjectException
      Delegates the formatting to another FormattableObject implementation. Invoking this method is equivalent to first verifying the other class, then delegating as below: This method is useful for FormattableObject which are wrapper around another object. It allows to delegate the WKT formatting to the wrapped object.
      Parameters:
      other - the object to format with this formatter.
      Returns:
      the value returned by FormattableObject.formatTo(Formatter).
      Throws:
      UnformattableObjectException
      Since:
      0.5
    • getEnclosingElement

      public FormattableObject getEnclosingElement(int depth)
      Returns the enclosing WKT element, or null if element being formatted is the root. This method can be invoked by child elements having some aspects that depend on the enclosing element.
      Parameters:
      depth - 1 for the immediate parent, 2 for the parent of the parent, etc.
      Returns:
      the parent element at the given depth, or null.
    • hasContextualUnit

      public boolean hasContextualUnit(int depth)
      Returns true if the element at the given depth specified a contextual unit. This method returns true if the formattable object given by getEnclosingElement(depth) has invoked addContextualUnit(Unit) with a non-null unit at least once.
      Note: The main purpose of this method is to allow AXIS[…] elements to determine if they should inherit the unit specified by the enclosing CRS, or if they should specify their unit explicitly.
      Parameters:
      depth - 1 for the immediate parent, 2 for the parent of the parent, etc.
      Returns:
      whether the parent element at the given depth has invoked addContextualUnit(…) at least once.
    • addContextualUnit

      public <Q extends javax.measure.Quantity<Q>> javax.measure.Unit<Q> addContextualUnit(javax.measure.Unit<Q> unit)
      Adds a unit to use for the next measurements of the quantity Q. The given unit will apply to all WKT elements containing a value of quantity Q without their own UNIT[…] element, until the restoreContextualUnit(Unit, Unit) method is invoked.

      If the given unit is null, then this method does nothing and returns null.

      Special case

      If the WKT conventions are WKT1_COMMON_UNITS, then this method ignores the given unit and returns null. See Convention.WKT1_COMMON_UNITS javadoc for more information.
      Type Parameters:
      Q - the unit quantity.
      Parameters:
      unit - the contextual unit to add, or null if none.
      Returns:
      the previous contextual unit for quantity Q, or null if none.
    • restoreContextualUnit

      public void restoreContextualUnit(javax.measure.Unit<?> unit, javax.measure.Unit<?> previous)
      Restores the contextual unit to its previous state before the call to addContextualUnit(Unit). This method is used in the following pattern:
      Parameters:
      unit - the value given in argument to addContextualUnit(unit) (can be null).
      previous - the value returned by addContextualUnit(unit) (can be null).
      Throws:
      IllegalStateException - if this method has not been invoked in the pattern documented above.
      Since:
      0.6
    • toContextualUnit

      public <Q extends javax.measure.Quantity<Q>> javax.measure.Unit<Q> toContextualUnit(javax.measure.Unit<Q> unit)
      Returns the unit to use instead of the given one, or unit if there is no replacement. This method searches for a unit specified by addContextualUnit(Unit) which is compatible with the given unit.
      Type Parameters:
      Q - the quantity of the unit.
      Parameters:
      unit - the unit to replace by the contextual unit, or null.
      Returns:
      a contextual unit compatible with the given unit, or unit (which may be null) if no contextual unit has been found.
    • isInvalidWKT

      public boolean isInvalidWKT()
      Returns true if the WKT written by this formatter is not strictly compliant to the WKT specification. This method returns true if setInvalidWKT(IdentifiedObject, Exception) has been invoked at least once. The action to take regarding invalid WKT is caller-dependent. For example, FormattableObject.toString() will accepts loose WKT formatting and ignore this flag, while FormattableObject.toWKT() requires strict WKT formatting and will thrown an exception if this flag is set.
      Returns:
      true if the WKT is invalid.
    • warnings

      private Warnings warnings()
      Returns the object where to store warnings.
    • setInvalidWKT

      public void setInvalidWKT(org.opengis.referencing.IdentifiedObject unformattable, Exception cause)
      Marks the current WKT representation of the given object as not strictly compliant with the WKT specification. This method can be invoked by implementations of FormattableObject.formatTo(Formatter) when the object to format is more complex than what the WKT specification allows. Applications can test isInvalidWKT() later for checking WKT validity.
      Parameters:
      unformattable - the object that cannot be formatted,
      cause - the cause for the failure to format, or null if the cause is not an exception.
    • setInvalidWKT

      public void setInvalidWKT(Class<?> unformattable, Exception cause)
      Marks the current WKT representation of the given class as not strictly compliant with the WKT specification. This method can be used as an alternative to setInvalidWKT(IdentifiedObject, Exception) when the problematic object is not an instance of IdentifiedObject.
      Parameters:
      unformattable - the class of the object that cannot be formatted,
      cause - the cause for the failure to format, or null if the cause is not an exception.
    • setInvalidWKT

      private void setInvalidWKT(String invalidElement, Exception cause)
      Implementation of public setInvalidWKT(…) methods.
      Note: the message is stored as an InternationalString in order to defer the actual message formatting until needed.
    • getName

      private static String getName(Class<?> unformattable)
      Returns the name of the GeoAPI interface implemented by the given class. If no GeoAPI interface is found, fallback on the class name.
    • getWarnings

      final Warnings getWarnings()
      Returns the warnings, or null if none.
    • appendWarnings

      final void appendWarnings() throws IOException
      Appends the warnings after the WKT string. If there are no warnings, then this method does nothing. If this method is invoked, then it shall be the last method before toWKT().
      Throws:
      IOException
    • toWKT

      public String toWKT()
      Returns the WKT formatted by this object.
      Returns:
      the WKT formatted by this formatter.
    • toString

      public String toString()
      Returns a string representation of this formatter for debugging purpose.
      Overrides:
      toString in class Object
      Returns:
      a string representation of this formatter.
    • clear

      final void clear()
      Clears this formatter before formatting a new object. This method clears also the WKT validity flag.