gpt4 book ai didi

org.apache.sis.io.wkt.WKTFormat类的使用及代码示例

转载 作者:知者 更新时间:2024-03-22 19:37:05 26 4
gpt4 key购买 nike

本文整理了Java中org.apache.sis.io.wkt.WKTFormat类的一些代码示例,展示了WKTFormat类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。WKTFormat类的具体详情如下:
包路径:org.apache.sis.io.wkt.WKTFormat
类名称:WKTFormat

WKTFormat介绍

[英]Parser and formatter for Well Known Text (WKT) strings. This format handles a pair of Parser and Formatter, used by the parse(…) and format(…) methods respectively. WKTFormat objects allow the following configuration:

  • The preferred authority of IdentifiedObject#getName() to format (see Formatter#getNameAuthority() for more information).
  • The Symbols to use (curly braces or brackets, etc).
  • The Transliterator to use for replacing Unicode characters by ASCII ones.
  • Whether ANSI X3.64 colors are allowed or not (default is not).
  • The indentation.
    String expansion Because the strings to be parsed by this class are long and tend to contain repetitive substrings, WKTFormat provides a mechanism for performing string substitutions before the parsing take place. Long strings can be assigned short names by calls to the #addFragment(String,String) method. After fragments have been added, any call to a parsing method will replace all occurrences (except in quoted text) of tokens like $foo by the WKT fragment named "foo".

Example: In the example below, the $WGS84 substring which appear in the argument given to the parseObject(…) method will be expanded into the full GeodeticCRS[“WGS84”, …]string before the parsing proceed. #addFragment("deg", "AngleUnit[“degree”, 0.0174532925199433]"); #addFragment("lat", "Axis[“Latitude”, NORTH, $deg]"); #addFragment("lon", "Axis[“Longitude”, EAST, $deg]"); #addFragment("MyBaseCRS", "GeodeticCRS[“WGS84”, Datum[…etc…], CS[…etc…], $lat, $lon]"); Object crs = #parseObject(String)("ProjectedCRS[“Mercator_1SP”, $MyBaseCRS,…etc…]"); Note that the parsing of WKT fragment does not always produce the same object. In particular, the default linear and angular units depend on the context in which the WKT fragment appears.
Limitations

  • The WKT format is not lossless! Objects formatted by WKTFormat are not guaranteed to be identical after parsing. Some metadata may be lost or altered, but the coordinate operations between two CRS should produce the same numerical results provided that the two CRS were formatted independently (do not rely on org.opengis.referencing.crs.GeneralDerivedCRS#getConversionFromBase() for instance).
  • Instances of this class are not synchronized for multi-threading. It is recommended to create separated format instances for each thread. If multiple threads access a WKTFormat concurrently, it must be synchronized externally.
  • Serialized objects of this class are not guaranteed to be compatible with future Apache SIS releases. Serialization support is appropriate for short term storage or RMI between applications running the same version of Apache SIS.
    [中]著名文本(WKT)字符串的解析器和格式化程序。这种格式处理一对解析器和格式化程序,分别由parse(…)和format(…)方法使用。WKTFormat对象允许进行以下配置:
    *要格式化的IdentifiedObject#getName()的首选权限(有关更多信息,请参阅格式化程序#getNameAuthority()。
    *要使用的符号(大括号或括号等)。
    *用于将Unicode字符替换为ASCII字符的音译器。
    *是否为ANSI X3。允许或不允许64种颜色(默认为不允许)。
    *压痕。
    字符串扩展由于此类要分析的字符串很长,并且往往包含重复的替换字符串,WKTFormat提供了一种在分析之前执行字符串替换的机制。长字符串可以通过调用#addFragment(String,String)方法来分配短名称。添加片段后,对解析方法的任何调用都将用名为“foo”的WKT片段替换所有出现的标记,如$foo(引号中的文本除外)。
    示例:在下面的示例中,在解析继续之前,在给定给parseObject(…)方法的参数中出现的$WGS84子字符串将扩展为完整的GeoMethodicRS[“WGS84”,…]字符串。#addFragment("deg", "AngleUnit[“degree”, 0.0174532925199433]"); #addFragment("lat", "Axis[“Latitude”, NORTH, $deg]"); #addFragment("lon", "Axis[“Longitude”, EAST, $deg]"); #addFragment("MyBaseCRS", "GeodeticCRS[“WGS84”, Datum[等...], CS[等...], $lat, $lon]"); Object crs = #parseObject(String)("ProjectedCRS[“Mercator_1SP”, $MyBaseCRS,等...]");注意,WKT片段的解析并不总是产生相同的对象。特别是,默认的线性和角度单位取决于WKT片段出现的上下文。
    局限性
    *WKT格式不是无损的!WKTFormat格式化的对象在解析后不保证完全相同。一些元数据可能会丢失或更改,但如果两个CR的格式是独立的(例如,不要依赖org.opengis.reference.CRS.GeneralDerivedCRS#getConversionFromBase()),那么两个CR之间的坐标操作应该会产生相同的数值结果。
    *对于多线程,此类的实例不同步。建议为每个线程创建单独的格式实例。如果多个线程同时访问WKTFormat,则必须对其进行外部同步。
    *此类的序列化对象不保证与未来的Apache SIS版本兼容。序列化支持适用于运行同一版本Apache SIS的应用程序之间的短期存储或RMI。

代码示例

代码示例来源:origin: Geomatys/geotoolkit

/**
 * Formats the given CRS as a string.
 *
 * @throws ContentFormatException if the given CRS is not formattable as a WKT.
 */
private static String format(final CoordinateReferenceSystem crs) throws ContentFormatException {
  final WKTFormat format = new WKTFormat(null, null);
  format.setConvention(Convention.WKT1);
  format.setIndentation(WKTFormat.SINGLE_LINE);
  final String wkt = format.format(crs);
  final Warnings warning = format.getWarnings();
  if (warning != null) {
    throw new ContentFormatException(warning.toString());
  }
  return wkt;
}

代码示例来源:origin: apache/sis

/**
   * Tests the usage of {@code WKTFormat} with WKT fragments.
   *
   * @throws ParseException if the parsing failed.
   */
  @Test
  public void testFragments() throws ParseException {
    format = new WKTFormat(null, null);
    format.addFragment("deg",    "UNIT[“degree”, 0.0174532925199433]");
    format.addFragment("Bessel", "SPHEROID[“Bessel 1841”, 6377397.155, 299.1528128, AUTHORITY[“EPSG”,“7004”]]");
    format.addFragment("Tokyo",  "DATUM[“Tokyo”, $Bessel]");
    format.addFragment("Lat",    "AXIS[“Lat”, NORTH, $deg]");
    format.addFragment("Lon",    "AXIS[“Long”, EAST, $deg]");
    final Object crs = format.parseObject("GEOGCS[“Tokyo”, $Tokyo, $Lat, $Lon]");
    final String wkt = format.format(crs);
    assertMultilinesEquals(
        "GEODCRS[\"Tokyo\",\n" +
        "  DATUM[\"Tokyo\",\n" +
        "    ELLIPSOID[\"Bessel 1841\", 6377397.155, 299.1528128, LENGTHUNIT[\"metre\", 1]]],\n" +
        "    PRIMEM[\"Greenwich\", 0.0, ANGLEUNIT[\"degree\", 0.017453292519943295]],\n" +
        "  CS[ellipsoidal, 2],\n" +
        "    AXIS[\"Latitude (B)\", north, ORDER[1]],\n" +
        "    AXIS[\"Longitude (L)\", east, ORDER[2]],\n" +
        "    ANGLEUNIT[\"degree\", 0.017453292519943295]]", wkt);
  }
}

代码示例来源:origin: apache/sis

/**
 * Implementation of {@link #testConsistency()} for a single WKT.
 *
 * @throws ParseException if the parsing failed.
 */
private void testConsistency(final String wkt) throws ParseException {
  final Object expected = parser.parseObject(wkt);
  final String reformat = format.format(expected);
  final Object reparsed = format.parseObject(reformat);
  assertEqualsIgnoreMetadata(expected, reparsed);
}

代码示例来源:origin: apache/sis

/**
 * Parses the given Well Known Text (version 1) into a math transform.
 */
@Override
public synchronized MathTransform createFromWKT(final String wkt) throws FactoryException {
  ArgumentChecks.ensureNonEmpty("wkt", wkt);
  if (parser == null) {
    parser = new WKTFormat(null, null);
    parser.setFactory(CRSAuthorityFactory.class, this);
    parser.setFactory(MathTransformFactory.class, this);
    parser.setFactory(CoordinateOperationFactory.class, this);
  }
  try {
    return (MathTransform) parser.parseObject(wkt);
  } catch (ParseException | ClassCastException e) {
    throw new FactoryException(e);
  }
}

代码示例来源:origin: apache/sis

/**
 * Prints the coordinate operation or math transform in Well Known Text format.
 * This information is printed only if the {@code --verbose} option was specified.
 */
private void printDetails() throws IOException {
  final boolean debug = options.containsKey(Option.DEBUG);
  final WKTFormat f = new WKTFormat(locale, timezone);
  if (colors) f.setColors(Colors.DEFAULT);
  f.setConvention(convention);
  CharSequence[] lines = CharSequences.splitOnEOL(f.format(debug ? operation.getMathTransform() : operation));
  for (int i=0; i<lines.length; i++) {
    if (i == 0) {
      printHeader(Vocabulary.Keys.Details);
    } else {
      printCommentLinePrefix();
      outHeader.nextColumn();
    }
    outHeader.append(lines[i]);
    outHeader.nextLine();
  }
  final Warnings warnings = f.getWarnings();
  if (warnings != null) {
    lines = CharSequences.splitOnEOL(warnings.toString());
    if (lines.length != 0) {                                            // Paranoiac check.
      printHeader(Vocabulary.Keys.Note);
      outHeader.append(lines[0]);
      outHeader.nextLine();
    }
  }
}

代码示例来源:origin: apache/sis

/**
 * Tests consistency between the parser and the formatter when using the WKT 1 format.
 * This test parses a WKT, formats it then parses again. We should obtain the same result.
 *
 * @throws ParseException if a parsing failed.
 */
@Test
@DependsOnMethod("testConsistencyOfWKT1")
public void testConsistencyOfWKT1_WithCommonUnits() throws ParseException {
  format = new WKTFormat(null, null);
  format.setConvention(Convention.WKT1_COMMON_UNITS);
  parser = new WKTFormat(null, null);
  parser.setConvention(Convention.WKT1);
  testConsistency();
  testConsistencyWithDenormalizedBaseCRS();
}

代码示例来源:origin: apache/sis

final Symbols symbols = new Symbols(Symbols.SQUARE_BRACKETS);
symbols.setPairedQuotes("“”");
parser = format = new WKTFormat(null, null);
format.setSymbols(symbols);
final DefaultProjectedCRS crs = (DefaultProjectedCRS) parser.parseObject(
  "PROJCS[“OSGB 1936 / British National Grid”,\n" +
  "  GEOGCS[“OSGB 1936”,\n" +
format.setConvention(Convention.WKT1);
assertMultilinesEquals(
  "PROJCS[“OSGB 1936 / British National Grid”,\n" +
  "  AXIS[“Easting”, EAST],\n" +
  "  AXIS[“Northing”, NORTH]]",
  format.format(crs));
format.setNameAuthority(Citations.GEOTIFF);
assertMultilinesEquals(
  "PROJCS[“OSGB 1936 / British National Grid”,\n" +
  "  AXIS[“Easting”, EAST],\n" +
  "  AXIS[“Northing”, NORTH]]",
  format.format(crs));
format.setNameAuthority(Citations.ESRI);
format.setConvention(Convention.WKT1_COMMON_UNITS);
assertMultilinesEquals(
  "PROJCS[“OSGB 1936 / British National Grid”,\n" +

代码示例来源:origin: apache/sis

DefaultPrimeMeridian pm = new DefaultPrimeMeridian(Collections.singletonMap(
    DefaultPrimeMeridian.NAME_KEY, "Invalid “$name” here"), -10, Units.DEGREE);
format = new WKTFormat(null, null);
final String   wkt      = format.format(pm);
final Warnings warnings = format.getWarnings();
assertNotNull("warnings", warnings);
assertEquals ("warnings.numMessages", 1, warnings.getNumMessages());
pm = (DefaultPrimeMeridian) format.parseObject(wkt);
assertEquals("Invalid \"$name\" here", pm.getName().getCode());

代码示例来源:origin: apache/sis

final String code, final CoordinateReferenceSystem crs)
String wkt = f.format(crs);
final Warnings warnings = f.getWarnings();
if (warnings != null && !warnings.getExceptions().isEmpty()) {
  print(code, "WARNING", warnings.getException(0));
  parsed = (CoordinateReferenceSystem) f.parseObject(wkt);
} catch (ParseException e) {
  print(code, "ERROR", "Can not parse the WKT below.");
  return null;
final String again = f.format(parsed);
final CharSequence[] expectedLines = CharSequences.splitOnEOL(wkt);
final CharSequence[] actualLines   = CharSequences.splitOnEOL(again);
if (f.getConvention().majorVersion() >= 2) {
  for (int i=0; i < expectedLines.length; i++) {
    final CharSequence line = expectedLines[i];

代码示例来源:origin: apache/sis

/**
 * Tests integration in {@link WKTFormat#parse(CharSequence, ParsePosition)}.
 * This method tests only a simple WKT because it is not the purpose of this
 * method to test the parser itself. We only want to tests its integration in
 * the {@link WKTFormat} class.
 *
 * @throws ParseException if the parsing failed.
 */
@Test
public void testParse() throws ParseException {
  format = new WKTFormat(null, null);
  final VerticalCRS crs = (VerticalCRS) format.parseObject(
      "VERT_CS[“Gravity-related height”,\n" +
      "  VERT_DATUM[“Mean Sea Level”, 2005],\n" +
      "  UNIT[“metre”, 1],\n" +
      "  AXIS[“Gravity-related height”, UP]]");
  GeodeticObjectParserTest.assertNameAndIdentifierEqual("Gravity-related height", 0, crs);
  GeodeticObjectParserTest.assertNameAndIdentifierEqual("Mean Sea Level", 0, crs.getDatum());
}

代码示例来源:origin: apache/sis

/**
 * Asserts that the WKT of the given object according the given convention is equal to the given regular expression.
 * This method is like {@link #assertWktEquals(String, Object)}, but the use of regular expression allows some
 * tolerance for example on numerical parameter values that may be subject to a limited form of rounding errors.
 *
 * @param convention  the WKT convention to use.
 * @param expected    the expected regular expression, or {@code null} if {@code object} is expected to be null.
 * @param object      the object to format in <cite>Well Known Text</cite> format, or {@code null}.
 *
 * @since 0.6
 */
public static void assertWktEqualsRegex(final Convention convention, final String expected, final Object object) {
  if (expected == null) {
    assertNull(object);
  } else {
    assertNotNull(object);
    final String wkt;
    synchronized (WKT_FORMAT) {
      WKT_FORMAT.setConvention(convention);
      wkt = WKT_FORMAT.format(object);
    }
    if (!wkt.matches(expected.replace("\n", System.lineSeparator()))) {
      fail("WKT does not match the expected regular expression. The WKT that we got is:\n" + wkt);
    }
  }
}

代码示例来源:origin: apache/sis

/**
 * Creates a new {@link DefaultCoordinateOperationFactory} to use for testing purpose.
 * The same factory will be used for all tests in this class.
 *
 * @throws ParseException if an error occurred while preparing the WKT parser.
 */
@BeforeClass
public static void createFactory() throws ParseException {
  factory = new DefaultCoordinateOperationFactory();
  parser  = new WKTFormat(null, null);
  parser.addFragment("NTF",
      "Datum[“Nouvelle Triangulation Française (Paris)”,\n" +
      "  Ellipsoid[“Clarke 1880 (IGN)”, 6378249.2, 293.4660212936269]]");
}

代码示例来源:origin: apache/sis

/**
 * Returns the CRS for the given Well Known Text.
 */
private static CoordinateReferenceSystem parse(final String wkt) throws ParseException {
  return (CoordinateReferenceSystem) parser.parseObject(wkt);
}

代码示例来源:origin: apache/sis

final WKTFormat f = new WKTFormat(locale, timezone);
if (convention != null) {
  f.setConvention(convention);
  f.setColors(Colors.DEFAULT);
f.format(object, out);
out.println();
break;

代码示例来源:origin: apache/sis

/**
 * Tests consistency between the parser and the formatter when using the WKT 1 format.
 * This test parses a WKT, formats it then parses again. We should obtain the same result.
 *
 * @throws ParseException if a parsing failed.
 */
@Test
public void testConsistencyOfWKT1() throws ParseException {
  format = new WKTFormat(null, null);
  format.setConvention(Convention.WKT1);
  parser = format;
  testConsistency();
  testConsistencyWithDenormalizedBaseCRS();
}

代码示例来源:origin: Geomatys/geotoolkit

@Test
  public void testFromWKT() throws ParseException, TransformException {
    final WKTFormat parser = new WKTFormat(null, null);
    final MathTransform mt = (MathTransform) parser.parseObject("Param_MT[\"Ellipsoid_To_Geoid\"]");
    DirectPosition pos = new GeneralDirectPosition(new double[] {45, 45, 1000});
    pos = mt.transform(pos, pos);
    assertEquals(  45.000, pos.getOrdinate(0), 0.001);
    assertEquals(  45.000, pos.getOrdinate(1), 0.001);
    assertEquals(1001.515, pos.getOrdinate(2), 0.001);
  }
}

代码示例来源:origin: apache/sis

/**
 * Asserts that the WKT of the given object according the given convention is equal to the expected one.
 * This method expected the {@code “…”} quotation marks instead of {@code "…"} for easier readability of
 * {@link String} constants in Java code.
 *
 * @param convention  the WKT convention to use.
 * @param expected    the expected text, or {@code null} if {@code object} is expected to be null.
 * @param object      the object to format in <cite>Well Known Text</cite> format, or {@code null}.
 */
public static void assertWktEquals(final Convention convention, final String expected, final Object object) {
  if (expected == null) {
    assertNull(object);
  } else {
    assertNotNull(object);
    final String wkt;
    synchronized (WKT_FORMAT) {
      WKT_FORMAT.setConvention(convention);
      wkt = WKT_FORMAT.format(object);
    }
    assertMultilinesEquals((object instanceof IdentifiedObject) ?
        ((IdentifiedObject) object).getName().getCode() : object.getClass().getSimpleName(), expected, wkt);
  }
}

代码示例来源:origin: apache/sis

public static void createFactory() throws ParseException {
  factory = new DefaultCoordinateOperationFactory();
  parser  = new WKTFormat(null, null);
  parser.addFragment("Sphere",
      "GEOGCS[“Sphere”,\n" +
      "  Datum[“Sphere”, Ellipsoid[“Sphere”, 6370997, 0]],\n" +
  parser.addFragment("NTF",
      "DATUM[“Nouvelle Triangulation Française”,\n" +
      "  SPHEROID[“Clarke 1880 (IGN)”, 6378249.2, 293.466021293627],\n" +

代码示例来源:origin: apache/sis

/**
 * Returns the CRS for the given Well Known Text.
 */
private static CoordinateReferenceSystem parse(final String wkt) throws ParseException {
  return (CoordinateReferenceSystem) parser.parseObject(wkt);
}

代码示例来源:origin: apache/sis

/**
 * Tests consistency between the parser and the formatter when using the WKT 2 format.
 * This test parses a WKT, formats it then parses again. We should obtain the same result.
 *
 * @throws ParseException if a parsing failed.
 */
@Test
@DependsOnMethod("testConsistencyOfWKT1")
public void testConsistencyOfWKT2() throws ParseException {
  format = new WKTFormat(null, null);
  format.setConvention(Convention.WKT2);
  parser = format;
  testConsistency();
}

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com