org.opengis.referencing.NoSuchAuthorityCodeException Java Examples

The following examples show how to use org.opengis.referencing.NoSuchAuthorityCodeException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GeoTools.java    From xyz-hub with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a mathematical transformation from the first given EPSG coordinate reference system into the second one. This method can be
 * used in conjunction with the {@link JTS#transform(Geometry, MathTransform)} method.
 *
 * @param fromCrsId the CRS identifier of the source coordinate reference system.
 * @param toCrsId the CRS identifier of the destination coordinate reference system.
 * @throws NullPointerException if any of the given EPSG identifier is null.
 * @throws NoSuchAuthorityCodeException if any of the given EPSG identifier is unknown.
 * @throws FactoryException if the requested coordinate reference system can't be created or the transformation or the coordinate failed.
 */
public static MathTransform mathTransform(final String fromCrsId, final String toCrsId)
    throws NullPointerException, NoSuchAuthorityCodeException, FactoryException {
  if (fromCrsId == null) {
    throw new NullPointerException("fromCrsId");
  }
  if (toCrsId == null) {
    throw new NullPointerException("toCrsId");
  }
  final String id = fromCrsId + ":" + toCrsId;
  if (transformCache.containsKey(id)) {
    return transformCache.get(id);
  }
  final CoordinateReferenceSystem fromCRS = crs(fromCrsId);
  final CoordinateReferenceSystem toCRS = crs(toCrsId);
  final MathTransform newTransform = CRS.findMathTransform(fromCRS, toCRS, true);
  final MathTransform existingTransform = transformCache.putIfAbsent(id, newTransform);
  if (existingTransform != null) {
    return existingTransform;
  }
  return newTransform;
}
 
Example #2
Source File: IdentifiedObjectFinder.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an object equals (optionally ignoring metadata), to the specified object
 * using only the {@linkplain AbstractIdentifiedObject#getIdentifiers identifiers}.
 * If no such object is found, returns {@code null}.
 *
 * <p>This method may be used in order to get a fully identified object from a partially identified one.</p>
 *
 * @param  object  the object looked up.
 * @return the identified object, or {@code null} if not found.
 * @throws FactoryException if an error occurred while creating an object.
 *
 * @see #createFromCodes(IdentifiedObject)
 * @see #createFromNames(IdentifiedObject)
 */
private IdentifiedObject createFromIdentifiers(final IdentifiedObject object) throws FactoryException {
    for (final Identifier id : object.getIdentifiers()) {
        final String code = IdentifiedObjects.toString(id);
        /*
         * We will process only codes with a namespace (e.g. "AUTHORITY:CODE") for avoiding ambiguity.
         * We do not try to check by ourselves if the identifier is in the namespace of the factory,
         * because calling factory.getAuthorityCodes() or factory.getCodeSpaces() may be costly for
         * some implementations.
         */
        if (code.indexOf(Constants.DEFAULT_SEPARATOR) >= 0) {
            final IdentifiedObject candidate;
            try {
                candidate = create(code);
            } catch (NoSuchAuthorityCodeException e) {
                // The identifier was not recognized. No problem, let's go on.
                exceptionOccurred(e);
                continue;
            }
            if (match(candidate, object)) {
                return candidate;
            }
        }
    }
    return null;
}
 
Example #3
Source File: BandFeatureIterator.java    From geowave with Apache License 2.0 6 votes vote down vote up
private void init(final Filter cqlFilter) throws NoSuchAuthorityCodeException, FactoryException {
  final SimpleFeatureTypeBuilder typeBuilder =
      sceneIterator.getProvider().bandFeatureTypeBuilder();
  final SimpleFeatureType bandType = typeBuilder.buildFeatureType();

  Iterator<SimpleFeature> featureIterator = new FeatureIteratorIterator<>(sceneIterator);
  featureIterator =
      Iterators.concat(
          Iterators.transform(featureIterator, new SceneToBandFeatureTransform(bandType)));

  if ((cqlFilter != null) && !cqlFilter.equals(Filter.INCLUDE)) {
    final String[] attributes = DataUtilities.attributeNames(cqlFilter, bandType);

    // we can rely on the scene filtering if we don't have to check any
    // specific band filters
    if (ArrayUtils.contains(attributes, BAND_ATTRIBUTE_NAME)) {
      featureIterator =
          Iterators.filter(
              featureIterator,
              new SceneFeatureIterator.CqlFilterPredicate(cqlFilter));
    }
  }
  iterator = featureIterator;
}
 
Example #4
Source File: BandFeatureIterator.java    From geowave with Apache License 2.0 6 votes vote down vote up
public BandFeatureIterator(
    final String providerName,
    final String collection,
    final String platform,
    final String location,
    final Date startDate,
    final Date endDate,
    final int orbitNumber,
    final int relativeOrbitNumber,
    final Filter cqlFilter,
    final String workspaceDir) throws MalformedURLException, IOException,
    NoSuchAuthorityCodeException, FactoryException, GeneralSecurityException {
  this(
      new SceneFeatureIterator(
          providerName,
          collection,
          platform,
          location,
          startDate,
          endDate,
          orbitNumber,
          relativeOrbitNumber,
          cqlFilter,
          workspaceDir),
      cqlFilter);
}
 
Example #5
Source File: CommonAuthorityFactory.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the unit of measurement for the given EPSG code.
 * This is used only for codes in the legacy {@code "AUTO"} namespace.
 */
private static Unit<?> createUnitFromEPSG(final double code) throws NoSuchAuthorityCodeException {
    String message = null;      // Error message to be used only in case of failure.
    final String s;             // The string representation of the code, to be used only in case of failure.
    final int c = (int) code;
    if (c == code) {
        final Unit<?> unit = Units.valueOfEPSG(c);
        if (Units.isLinear(unit)) {
            return unit;
        } else if (unit != null) {
            message = Errors.format(Errors.Keys.NonLinearUnit_1, unit);
        }
        s = String.valueOf(c);
    } else {
        s = String.valueOf(code);
    }
    if (message == null) {
        message = Resources.format(Resources.Keys.NoSuchAuthorityCode_3, Constants.EPSG, Unit.class, s);
    }
    throw new NoSuchAuthorityCodeException(message, Constants.EPSG, s);
}
 
Example #6
Source File: MultiAuthoritiesFactoryTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests {@code MultiAuthoritiesFactory.createFoo(String)} from codes in the
 * {@code "urn:ogc:def:type:authority:version:code"} form.
 *
 * @throws FactoryException if an authority or a code is not recognized.
 */
@Test
@DependsOnMethod("testCreateFromSimpleCodes")
public void testCreateFromURNs() throws FactoryException {
    final Set<AuthorityFactoryMock> mock = Collections.singleton(new AuthorityFactoryMock("MOCK", "2.3"));
    final MultiAuthoritiesFactory factory = new MultiAuthoritiesFactory(mock, mock, mock, null);

    assertSame("Empty version", HardCodedCRS  .WGS84_φλ,  factory.createGeographicCRS("urn:ogc:def:crs:MOCK::4326"));
    assertSame("With spaces",   HardCodedCRS  .WGS84,     factory.createGeographicCRS(" urn : ogc  : def:crs :  mock : :  84 "));
    assertSame("Mixed case",    HardCodedCRS  .DEPTH,     factory.createVerticalCRS  (" Urn : OGC : dEf : CRS : MoCk : : 9905"));
    assertSame("With version",  HardCodedDatum.WGS84,     factory.createDatum        ("urn:ogc:def:datum:mock:2.3:6326"));
    assertSame("Empty version", HardCodedDatum.GREENWICH, factory.createObject       ("urn:ogc:def:meridian: MoCk :: 8901"));
    assertSame("Version 0",     HardCodedDatum.SPHERE,    factory.createGeodeticDatum("urn:ogc:def:datum:MOCK: 0 :6047"));
    assertSame("Upper case",    Units         .METRE,     factory.createUnit         ("URN:OGC:DEF:UOM:MOCK::9001"));
    try {
        factory.createGeographicCRS("urn:ogc:def:datum:MOCK::4326");
        fail("Should create an object of the wrong type.");
    } catch (NoSuchAuthorityCodeException e) {
        final String message = e.getMessage();
        assertTrue(message, message.contains("datum"));
        assertTrue(message, message.contains("GeographicCRS"));
    }
}
 
Example #7
Source File: SceneFeatureIterator.java    From geowave with Apache License 2.0 6 votes vote down vote up
public SceneFeatureIterator(
    final String providerName,
    final String collection,
    final String platform,
    final String location,
    final Date startDate,
    final Date endDate,
    final int orbitNumber,
    final int relativeOrbitNumber,
    final Filter cqlFilter,
    final String workspaceDir) throws NoSuchAuthorityCodeException, FactoryException,
    MalformedURLException, IOException, GeneralSecurityException {
  init(
      new File(workspaceDir, SCENES_DIR),
      providerName,
      collection,
      platform,
      location,
      startDate,
      endDate,
      orbitNumber,
      relativeOrbitNumber,
      cqlFilter);
}
 
Example #8
Source File: MultiAuthoritiesFactoryTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests {@code MultiAuthoritiesFactory.createFoo(String)} from codes in the
 * {@code "http://www.opengis.net/gml/srs/authority.xml#code"} form.
 *
 * @throws FactoryException if an authority or a code is not recognized.
 */
@Test
@DependsOnMethod("testCreateFromURNs")
public void testCreateFromHTTPs() throws FactoryException {
    final Set<AuthorityFactoryMock> mock = Collections.singleton(new AuthorityFactoryMock("MOCK", "2.3"));
    final MultiAuthoritiesFactory factory = new MultiAuthoritiesFactory(mock, mock, mock, null);

    assertSame("HTTP",          HardCodedCRS  .WGS84_φλ,  factory.createGeographicCRS("http://www.opengis.net/def/crs/mock/0/4326"));
    assertSame("GML",           HardCodedCRS  .WGS84_φλ,  factory.createObject       ("http://www.opengis.net/gml/srs/mock.xml#4326"));
    assertSame("With spaces",   HardCodedCRS  .WGS84,     factory.createGeographicCRS("http://www.opengis.net/gml/srs/ mock.xml # 84 "));
    assertSame("Mixed case",    HardCodedCRS  .DEPTH,     factory.createVerticalCRS  ("HTTP://www.OpenGIS.net/GML/SRS/MoCk.xml#9905"));
    try {
        factory.createDatum("http://www.opengis.net/gml/srs/mock.xml#6326");
        fail("Should create an object of the wrong type.");
    } catch (NoSuchAuthorityCodeException e) {
        final String message = e.getMessage();
        assertTrue(message, message.contains("crs"));
        assertTrue(message, message.contains("Datum"));
    }
}
 
Example #9
Source File: PolygonAreaCalculator.java    From geowave with Apache License 2.0 6 votes vote down vote up
private CoordinateReferenceSystem lookupUtmCrs(final double centerLat, final double centerLon)
    throws NoSuchAuthorityCodeException, FactoryException {
  final int epsgCode =
      (32700 - (Math.round((45f + (float) centerLat) / 90f) * 100))
          + Math.round((183f + (float) centerLon) / 6f);

  final String crsId = "EPSG:" + Integer.toString(epsgCode);

  CoordinateReferenceSystem crs = crsMap.get(crsId);

  if (crs == null) {
    crs = CRS.decode(crsId, true);

    crsMap.put(crsId, crs);
  }

  return crs;
}
 
Example #10
Source File: AuthorityFactoryMock.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the unit of measurement for the given code.
 *
 * @return the unit of measurement.
 * @throws NoSuchAuthorityCodeException if the given code is unknown.
 */
@Override
public Unit<?> createUnit(final String code) throws NoSuchAuthorityCodeException {
    assertFalse("This factory has been closed.", isClosed());
    final int n;
    try {
        n = Integer.parseInt(trimNamespace(code));
    } catch (NumberFormatException e) {
        throw new NoSuchAuthorityCodeException(e.toString(), "MOCK", code);
    }
    final Unit<?> unit = Units.valueOfEPSG(n);
    if (unit == null) {
        throw new NoSuchAuthorityCodeException(code, authority.getTitle().toString(), code);
    }
    return unit;
}
 
Example #11
Source File: AuthorityFactoryMock.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the geodetic object for the given code.
 *
 * @throws NoSuchAuthorityCodeException if the given code is unknown.
 */
@Override
public IdentifiedObject createObject(final String code) throws NoSuchAuthorityCodeException {
    assertFalse("This factory has been closed.", isClosed());
    final int n;
    try {
        n = Integer.parseInt(trimNamespace(code));
    } catch (NumberFormatException e) {
        throw new NoSuchAuthorityCodeException(e.toString(), "MOCK", code);
    }
    switch (n) {
        case   84: return HardCodedCRS.WGS84;
        case 4326: return HardCodedCRS.WGS84_φλ;
        case 4979: return HardCodedCRS.GEOCENTRIC;
        case 5714: return HardCodedCRS.GRAVITY_RELATED_HEIGHT;
        case 9905: return HardCodedCRS.DEPTH;
        case 8901: return HardCodedDatum.GREENWICH;
        case 8903: return HardCodedDatum.PARIS;
        case 8914: return HardCodedDatum.PARIS_RGS;
        case 6326: return HardCodedDatum.WGS84;
        case 6322: return HardCodedDatum.WGS72;
        case 6807: return HardCodedDatum.NTF;
        case 6301: return HardCodedDatum.TOKYO;
        case 6612: return HardCodedDatum.JGD2000;
        case 6047: return HardCodedDatum.SPHERE;
        case 5100: return HardCodedDatum.MEAN_SEA_LEVEL;
        case 6422: return HardCodedCS.GEODETIC_φλ;
        case 6424: return HardCodedCS.GEODETIC_2D;
        default: throw new NoSuchAuthorityCodeException(code, authority.getTitle().toString(), code);
    }
}
 
Example #12
Source File: CoordManagerTest.java    From sldeditor with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Test method for {@link com.sldeditor.common.coordinate.CoordManager#getInstance()}. Test
 * method for {@link com.sldeditor.common.coordinate.CoordManager#getCRSList()}. Test method for
 * {@link
 * com.sldeditor.common.coordinate.CoordManager#getCRSCode(org.opengis.referencing.crs.CoordinateReferenceSystem)}.
 * Test method for {@link com.sldeditor.common.coordinate.CoordManager#getWGS84()}.
 *
 * @throws NoSuchAuthorityCodeException the no such authority code exception
 * @throws FactoryException the factory exception
 */
@Test
public void testGetInstance() throws NoSuchAuthorityCodeException, FactoryException {
    CoordManager.getInstance().populateCRSList();
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    List<ValueComboBoxData> crsList = CoordManager.getInstance().getCRSList();
    assertTrue(crsList.size() > 0);

    CoordinateReferenceSystem crs = CoordManager.getInstance().getCRS(null);
    assertNull(crs);

    crs = CoordManager.getInstance().getWGS84();
    assertTrue(crs != null);

    String code = CoordManager.getInstance().getCRSCode(null);
    assertTrue(code.compareTo("") == 0);

    code = CoordManager.getInstance().getCRSCode(crs);
    assertTrue(code.compareTo("EPSG:4326") == 0);

    String projectedCRSCode = "EPSG:27700";
    CoordinateReferenceSystem projectedCRS = CRS.decode(projectedCRSCode);

    code = CoordManager.getInstance().getCRSCode(projectedCRS);
    assertTrue(code.compareTo(projectedCRSCode) == 0);
}
 
Example #13
Source File: SceneFeatureIteratorTest.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Test
public void testIterateProviders()
    throws IOException, CQLException, ParseException, NoSuchAuthorityCodeException,
    FactoryException, MalformedURLException, GeneralSecurityException {
  for (final Sentinel2ImageryProvider provider : Sentinel2ImageryProvider.getProviders()) {
    testIterate(provider.providerName());
  }
}
 
Example #14
Source File: GamaOsmFile.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
public OSMInfo(final String propertiesString) throws NoSuchAuthorityCodeException, FactoryException {
	super(propertiesString);
	if (!hasFailed) {
		final String[] segments = split(propertiesString);
		itemNumber = Integer.parseInt(segments[1]);
		final String crsString = segments[2];
		if ("null".equals(crsString)) {
			crs = null;
		} else {
			crs = CRS.parseWKT(crsString);
		}
		width = Double.parseDouble(segments[3]);
		height = Double.parseDouble(segments[4]);
		if (segments.length > 5) {
			final String[] names = splitByWholeSeparatorPreserveAllTokens(segments[5], SUB_DELIMITER);
			final String[] types = splitByWholeSeparatorPreserveAllTokens(segments[6], SUB_DELIMITER);
			for (int i = 0; i < names.length; i++) {
				attributes.put(names[i], types[i]);
			}
		}
	} else {
		itemNumber = 0;
		width = 0.0;
		height = 0.0;
		crs = null;
	}
}
 
Example #15
Source File: GeometryUtility.java    From geofence with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Project geometry.
 *
 * @param originalGeom
 *            the original geom
 * @param srcCRSCode
 *            the src crs code
 * @param trgCRSCode
 *            the trg crs code
 * @return the geometry
 * @throws NoSuchAuthorityCodeException
 *             the no such authority code exception
 * @throws FactoryException
 *             the factory exception
 * @throws MismatchedDimensionException
 *             the mismatched dimension exception
 * @throws TransformException
 *             the transform exception
 */
public static Geometry projectGeometry(Geometry originalGeom, String srcCRSCode,
    String trgCRSCode) throws NoSuchAuthorityCodeException, FactoryException, MismatchedDimensionException,
    TransformException
{

    Geometry projectedGeometry = null;
    final MathTransform transform = CRS.findMathTransform(CRS.decode(srcCRSCode, true), CRS.decode(trgCRSCode, true), true);

    // converting geometries into a linear system
    try
    {
        projectedGeometry = JTS.transform(originalGeom, transform);
    }
    catch (Exception e)
    {
        GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(
                    PrecisionModel.FLOATING), 4326);
        WKTReader reader = new WKTReader(geometryFactory);

        try
        {
            Polygon worldCutPolygon = (Polygon) reader.read("POLYGON((-180 -89.9, -180 89.9, 180 89.9, 180 -89.9, -180 -89.9))");

            projectedGeometry = JTS.transform(originalGeom.intersection(worldCutPolygon),
                    transform);
        }
        catch (Exception ex)
        {
            throw new RuntimeException(ex);
        }
    }

    return projectedGeometry;
}
 
Example #16
Source File: BandFeatureIterator.java    From geowave with Apache License 2.0 5 votes vote down vote up
/**
 * Default SimpleFeatureTypeBuilder which provides the Bands schema of a Sentinel2 provider.
 */
public static SimpleFeatureTypeBuilder defaultBandFeatureTypeBuilder(final String typeName)
    throws NoSuchAuthorityCodeException, FactoryException {
  final SimpleFeatureTypeBuilder sceneBuilder =
      SceneFeatureIterator.defaultSceneFeatureTypeBuilder(typeName);

  final SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();
  typeBuilder.init(sceneBuilder.buildFeatureType());
  typeBuilder.setName(typeName);
  typeBuilder.setDefaultGeometry(SceneFeatureIterator.SHAPE_ATTRIBUTE_NAME);
  typeBuilder.minOccurs(1).maxOccurs(1).nillable(false).add(BAND_ATTRIBUTE_NAME, String.class);

  return typeBuilder;
}
 
Example #17
Source File: AbstractFunction.java    From GeoTriples with Apache License 2.0 5 votes vote down vote up
protected Geometry computeGeometry(Object object, QLTerm term) throws SAXException, IOException,
		ParserConfigurationException, NoSuchAuthorityCodeException, FactoryException, MalformedGeometryException, ParseException {

	if (!term.equals(QLTerm.SHP_CLASS) && cache.containsKey(object)) {
		return cache.get(object);
	}
	switch (term) {
	case SHP_CLASS:
		return (Geometry) object;
	case ROW_CLASS:
		Geometry result = computeGeometry((String) object, term);
		return result;
	case XPATH_CLASS:
		Geometry result1 = computeGeometry((String) object, term);
		cache.put(object, result1);
		return result1;
	case CSV_CLASS:
		Geometry result2 = computeGeometry((String) object, term);
		cache.put(object, result2);
		return result2;
	case JSONPATH_CLASS:
		Geometry result3 = computeGeometry((String) object, term);
		cache.put(object, result3);
		return result3;
	default:
		throw new MalformedGeometryException("GeoTriples cannot recognize this type of geometry");
	}

}
 
Example #18
Source File: CRSBuilder.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Possibly sets {@link #datum}, {@link #coordinateSystem} and {@link #referenceSystem}
 * to predefined objects matching the axes defined in the netCDF file.
 */
@Override void setPredefinedComponents(final Decoder decoder) throws FactoryException {
    super.setPredefinedComponents(decoder);
    if (isPredefinedCS(Units.DEGREE)) {
        GeographicCRS crs;
        if (is3D()) {
            crs = defaultCRS.geographic3D();
            if (isLongitudeFirst) {
                crs = DefaultGeographicCRS.castOrCopy(crs).forConvention(AxesConvention.RIGHT_HANDED);
            }
        } else if (isLongitudeFirst) {
            crs = defaultCRS.normalizedGeographic();
        } else {
            crs = defaultCRS.geographic();
        }
        referenceSystem  = crs;
        coordinateSystem = crs.getCoordinateSystem();
        datum            = crs.getDatum();
    } else {
        datum = defaultCRS.datum();
        final Integer epsg = epsgCandidateCS(Units.DEGREE);
        if (epsg != null) try {
            coordinateSystem = decoder.getCSAuthorityFactory().createEllipsoidalCS(epsg.toString());
        } catch (NoSuchAuthorityCodeException e) {
            recoverableException(e);
        }
    }
}
 
Example #19
Source File: CRSBuilder.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a coordinate system (CS) with the same axis directions than the given CS but potentially different units.
 * If a coordinate system exists in the EPSG database with the requested characteristics, that CS will be returned
 * in order to have a richer set of metadata (name, minimal and maximal values, <i>etc</i>). Otherwise an CS with
 * an arbitrary name will be returned.
 *
 * @see CoordinateSystems#replaceLinearUnit(CoordinateSystem, Unit)
 */
private CartesianCS replaceLinearUnit(final CartesianCS cs, final Unit<Length> unit) throws FactoryException {
    final Integer epsg = CoordinateSystems.getEpsgCode(unit, CoordinateSystems.getAxisDirections(cs));
    if (epsg != null) try {
        return getCSAuthorityFactory().createCartesianCS(epsg.toString());
    } catch (NoSuchAuthorityCodeException e) {
        reader.owner.warning(null, e);
    }
    return (CartesianCS) CoordinateSystems.replaceLinearUnit(cs, unit);
}
 
Example #20
Source File: CRSBuilder.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a coordinate system (CS) with the same axis directions than the given CS but potentially different units.
 * If a coordinate system exists in the EPSG database with the requested characteristics, that CS will be returned
 * in order to have a richer set of metadata (name, minimal and maximal values, <i>etc</i>). Otherwise an CS with
 * an arbitrary name will be returned.
 *
 * @see CoordinateSystems#replaceAngularUnit(CoordinateSystem, Unit)
 */
private EllipsoidalCS replaceAngularUnit(final EllipsoidalCS cs, final Unit<Angle> unit) throws FactoryException {
    final Integer epsg = CoordinateSystems.getEpsgCode(unit, CoordinateSystems.getAxisDirections(cs));
    if (epsg != null) try {
        return getCSAuthorityFactory().createEllipsoidalCS(epsg.toString());
    } catch (NoSuchAuthorityCodeException e) {
        reader.owner.warning(null, e);
    }
    return (EllipsoidalCS) CoordinateSystems.replaceAngularUnit(cs, unit);
}
 
Example #21
Source File: CommonAuthorityFactoryTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests {@link CommonAuthorityFactory#createProjectedCRS(String)} with the {@code "AUTO:42001"} code.
 *
 * @throws FactoryException if an error occurred while creating a CRS.
 */
@Test
public void testAuto42001() throws FactoryException {
    final ProjectedCRS crs = factory.createProjectedCRS("AUTO:42001,-123,0");
    assertSame("With other coord.",   crs, factory.createProjectedCRS("AUTO : 42001, -122, 10 "));
    assertSame("Omitting namespace.", crs, factory.createProjectedCRS(" 42001, -122 , 10 "));
    assertSame("With explicit unit.", crs, factory.createProjectedCRS("AUTO2 :  42001, 1, -122 , 10 "));
    assertSame("With explicit unit.", crs, factory.createProjectedCRS("AUTO1 :  42001, 9001, -122 , 10 "));
    assertSame("Legacy namespace.",   crs, factory.createProjectedCRS("AUTO:42001,9001,-122,10"));
    assertSame("When the given parameters match exactly the UTM central meridian and latitude of origin,"
            + " the CRS created by AUTO:42002 should be the same than the CRS created by AUTO:42001.",
            crs, factory.createProjectedCRS("AUTO2:42002,1,-123,0"));

    assertEpsgNameAndIdentifierEqual("WGS 84 / UTM zone 10N", 32610, crs);
    final ParameterValueGroup p = crs.getConversionFromBase().getParameterValues();
    assertEquals(TransverseMercator.NAME, crs.getConversionFromBase().getMethod().getName().getCode());
    assertAxisDirectionsEqual("CS", crs.getCoordinateSystem(), AxisDirection.EAST, AxisDirection.NORTH);
    assertEquals(Constants.CENTRAL_MERIDIAN, -123, p.parameter(Constants.CENTRAL_MERIDIAN)  .doubleValue(), STRICT);
    assertEquals(Constants.LATITUDE_OF_ORIGIN,  0, p.parameter(Constants.LATITUDE_OF_ORIGIN).doubleValue(), STRICT);
    assertEquals(Constants.FALSE_NORTHING,      0, p.parameter(Constants.FALSE_NORTHING)    .doubleValue(), STRICT);
    assertEquals("axis[0].unit", Units.METRE, crs.getCoordinateSystem().getAxis(0).getUnit());
    try {
        factory.createObject("AUTO:42001");
        fail("Should not have accepted incomplete code.");
    } catch (NoSuchAuthorityCodeException e) {
        assertEquals("42001", e.getAuthorityCode());
    }
}
 
Example #22
Source File: EPSGDataAccess.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a description of the object corresponding to a code.
 * This method returns the object name in a lightweight manner, without creating the full {@link IdentifiedObject}.
 *
 * @param  code  value allocated by authority.
 * @return the object name, or {@code null} if the object corresponding to the specified {@code code} has no name.
 * @throws NoSuchAuthorityCodeException if the specified {@code code} was not found.
 * @throws FactoryException if the query failed for some other reason.
 */
@Override
public InternationalString getDescriptionText(final String code) throws NoSuchAuthorityCodeException, FactoryException {
    try {
        for (final TableInfo table : TableInfo.EPSG) {
            final String text = getCodeMap(table.type).get(code);
            if (text != null) {
                return (table.nameColumn != null) ? new SimpleInternationalString(text) : null;
            }
        }
    } catch (SQLException exception) {
        throw new FactoryException(exception.getLocalizedMessage(), exception);
    }
    throw noSuchAuthorityCode(IdentifiedObject.class, code);
}
 
Example #23
Source File: GeoTools.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the cached coordinate reference system for the given EPSG identifier.
 *
 * @param crsId the CRS identifier of the coordinate reference system.
 * @return the coordinate reference system.
 * @throws NullPointerException if the given epsgId is null.
 * @throws NoSuchAuthorityCodeException if the given EPSG identifier is unknown.
 * @throws FactoryException if the requested coordinate reference system can't be created.
 */
public static CoordinateReferenceSystem crs(final String crsId)
    throws NullPointerException, NoSuchAuthorityCodeException, FactoryException {
  if (crsId == null) {
    throw new NullPointerException("crsId");
  }
  if (crsCache.containsKey(crsId)) {
    return crsCache.get(crsId);
  }
  final CoordinateReferenceSystem newCRS = factory.createCoordinateReferenceSystem(crsId);
  final CoordinateReferenceSystem existingCRS = crsCache.putIfAbsent(crsId, newCRS);
  if (existingCRS != null) {
    return existingCRS;
  }
  return newCRS;
}
 
Example #24
Source File: EPSGDataAccess.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a prime meridian defining the origin from which longitude values are determined.
 *
 * <div class="note"><b>Example:</b>
 * some EPSG codes for prime meridians are:
 *
 * <table class="sis">
 * <caption>EPSG codes examples</caption>
 *   <tr><th>Code</th> <th>Description</th></tr>
 *   <tr><td>8901</td> <td>Greenwich</td></tr>
 *   <tr><td>8903</td> <td>Paris</td></tr>
 *   <tr><td>8904</td> <td>Bogota</td></tr>
 *   <tr><td>8905</td> <td>Madrid</td></tr>
 *   <tr><td>8906</td> <td>Rome</td></tr>
 * </table></div>
 *
 * @param  code  value allocated by EPSG.
 * @return the prime meridian for the given code.
 * @throws NoSuchAuthorityCodeException if the specified {@code code} was not found.
 * @throws FactoryException if the object creation failed for some other reason.
 *
 * @see #createGeodeticDatum(String)
 * @see org.apache.sis.referencing.datum.DefaultPrimeMeridian
 */
@Override
public synchronized PrimeMeridian createPrimeMeridian(final String code)
        throws NoSuchAuthorityCodeException, FactoryException
{
    ArgumentChecks.ensureNonNull("code", code);
    PrimeMeridian returnValue = null;
    try (ResultSet result = executeQuery("Prime Meridian", "PRIME_MERIDIAN_CODE", "PRIME_MERIDIAN_NAME",
            "SELECT PRIME_MERIDIAN_CODE," +
                  " PRIME_MERIDIAN_NAME," +
                  " GREENWICH_LONGITUDE," +
                  " UOM_CODE," +
                  " REMARKS," +
                  " DEPRECATED" +
            " FROM [Prime Meridian]" +
            " WHERE PRIME_MERIDIAN_CODE = ?", code))
    {
        while (result.next()) {
            final Integer epsg       = getInteger  (code, result, 1);
            final String  name       = getString   (code, result, 2);
            final double  longitude  = getDouble   (code, result, 3);
            final String  unitCode   = getString   (code, result, 4);
            final String  remarks    = getOptionalString (result, 5);
            final boolean deprecated = getOptionalBoolean(result, 6);
            final Unit<Angle> unit = owner.createUnit(unitCode).asType(Angle.class);
            final PrimeMeridian primeMeridian = owner.datumFactory.createPrimeMeridian(
                    createProperties("Prime Meridian", name, epsg, remarks, deprecated), longitude, unit);
            returnValue = ensureSingleton(primeMeridian, returnValue, code);
        }
    } catch (SQLException exception) {
        throw databaseFailure(PrimeMeridian.class, code, exception);
    }
    if (returnValue == null) {
        throw noSuchAuthorityCode(PrimeMeridian.class, code);
    }
    return returnValue;
}
 
Example #25
Source File: EPSGFactoryTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests the creation of CRS using name instead of primary key.
 *
 * @throws FactoryException if an error occurred while querying the factory.
 *
 * @see #testProjectedByName()
 */
@Test
public void testCreateByName() throws FactoryException {
    final EPSGFactory factory = TestFactorySource.factory;
    assumeNotNull(factory);
    assertSame   (factory.createUnit("9002"), factory.createUnit("foot"));
    assertNotSame(factory.createUnit("9001"), factory.createUnit("foot"));
    assertSame   (factory.createUnit("9202"), factory.createUnit("ppm"));       // Search in alias table.
    /*
     * Test a name with colons.
     */
    final CoordinateSystem cs = factory.createCoordinateSystem(
            "Ellipsoidal 2D CS. Axes: latitude, longitude. Orientations: north, east. UoM: degree");
    assertEpsgNameAndIdentifierEqual(
            "Ellipsoidal 2D CS. Axes: latitude, longitude. Orientations: north, east. UoM: degree", 6422, cs);
    /*
     * Tests with a unknown name. The exception should be NoSuchAuthorityCodeException
     * (some previous version wrongly threw a SQLException when using HSQL database).
     */
    try {
        factory.createGeographicCRS("WGS83");
        fail("Should not find a geographic CRS named “WGS83” (the actual name is “WGS 84”).");
    } catch (NoSuchAuthorityCodeException e) {
        // This is the expected exception.
        assertEquals("WGS83", e.getAuthorityCode());
    }
}
 
Example #26
Source File: EPSGDataAccess.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Creates description of the algorithm and parameters used to perform a coordinate operation.
 * An {@code OperationMethod} is a kind of metadata: it does not perform any coordinate operation
 * (e.g. map projection) by itself, but tells us what is needed in order to perform such operation.
 *
 * <div class="note"><b>Example:</b>
 * some EPSG codes for operation methods are:
 *
 * <table class="sis">
 * <caption>EPSG codes examples</caption>
 *   <tr><th>Code</th> <th>Description</th></tr>
 *   <tr><td>9804</td> <td>Mercator (variant A)</td></tr>
 *   <tr><td>9802</td> <td>Lambert Conic Conformal (2SP)</td></tr>
 *   <tr><td>9810</td> <td>Polar Stereographic (variant A)</td></tr>
 *   <tr><td>9624</td> <td>Affine parametric transformation</td></tr>
 * </table></div>
 *
 * @param  code  value allocated by EPSG.
 * @return the operation method for the given code.
 * @throws NoSuchAuthorityCodeException if the specified {@code code} was not found.
 * @throws FactoryException if the object creation failed for some other reason.
 */
@Override
public synchronized OperationMethod createOperationMethod(final String code)
        throws NoSuchAuthorityCodeException, FactoryException
{
    ArgumentChecks.ensureNonNull("code", code);
    OperationMethod returnValue = null;
    try (ResultSet result = executeQuery("Coordinate_Operation Method", "COORD_OP_METHOD_CODE", "COORD_OP_METHOD_NAME",
            "SELECT COORD_OP_METHOD_CODE," +
                  " COORD_OP_METHOD_NAME," +
                  " REMARKS," +
                  " DEPRECATED" +
             " FROM [Coordinate_Operation Method]" +
            " WHERE COORD_OP_METHOD_CODE = ?", code))
    {
        while (result.next()) {
            final Integer epsg       = getInteger  (code, result, 1);
            final String  name       = getString   (code, result, 2);
            final String  remarks    = getOptionalString (result, 3);
            final boolean deprecated = getOptionalBoolean(result, 4);
            final Integer[] dim = getDimensionsForMethod(epsg);
            final ParameterDescriptor<?>[] descriptors = createParameterDescriptors(epsg);
            Map<String,Object> properties = createProperties("Coordinate_Operation Method", name, epsg, remarks, deprecated);
            // We do not store the formula at this time, because the text is very verbose and rarely used.
            final OperationMethod method = new DefaultOperationMethod(properties, dim[0], dim[1],
                        new DefaultParameterDescriptorGroup(properties, 1, 1, descriptors));
            returnValue = ensureSingleton(method, returnValue, code);
        }
    } catch (SQLException exception) {
        throw databaseFailure(OperationMethod.class, code, exception);
    }
    if (returnValue == null) {
         throw noSuchAuthorityCode(OperationMethod.class, code);
    }
    return returnValue;
}
 
Example #27
Source File: CommonAuthorityFactory.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Rewrites the given code in a canonical format.
 * If the code can not be reformatted, then this method returns {@code null}.
 */
static String reformat(final String code) {
    try {
        return format(Integer.parseInt(code.substring(skipNamespace(code) & ~LEGACY_MASK)));
    } catch (NoSuchAuthorityCodeException | NumberFormatException e) {
        Logging.recoverableException(Logging.getLogger(Loggers.CRS_FACTORY), CommonAuthorityFactory.class, "reformat", e);
        return null;
    }
}
 
Example #28
Source File: AuthorityFactoryMock.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the spatial extent for the given code.
 *
 * @return the spatial extent.
 * @throws NoSuchAuthorityCodeException if the given code is unknown.
 */
@Override
public Extent createExtent(final String code) throws NoSuchAuthorityCodeException {
    assertFalse("This factory has been closed.", isClosed());
    final int n;
    try {
        n = Integer.parseInt(trimNamespace(code));
    } catch (NumberFormatException e) {
        throw new NoSuchAuthorityCodeException(e.toString(), "MOCK", code);
    }
    switch (n) {
        case 1262: return Extents.WORLD;
        default: throw new NoSuchAuthorityCodeException(code, authority.getTitle().toString(), code);
    }
}
 
Example #29
Source File: CRSTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Test {@link CRS#forCode(String)} with values that should be invalid.
 *
 * @throws FactoryException if an error other than {@link NoSuchAuthorityCodeException} happened.
 */
@Test
public void testForInvalidCode() throws FactoryException {
    try {
        CRS.forCode("EPSG:4");
        fail("Should not find EPSG:4");
    } catch (NoSuchAuthorityCodeException e) {
        assertEquals("4", e.getAuthorityCode());
    }
}
 
Example #30
Source File: EPSGFactoryFallback.java    From sis with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a coordinate reference system for the given EPSG code. This method is invoked
 * as a fallback when {@link CRS#forCode(String)} can not create a CRS for a given code.
 */
@Override
public CoordinateReferenceSystem createCoordinateReferenceSystem(final String code) throws NoSuchAuthorityCodeException {
    return (CoordinateReferenceSystem) predefined(code, CRS);
}