diff --git "a/data/train/Java/AbstractEpsgFactory.java" "b/data/train/Java/AbstractEpsgFactory.java"
deleted file mode 100644--- "a/data/train/Java/AbstractEpsgFactory.java"
+++ /dev/null
@@ -1,3668 +0,0 @@
-/*
- * GeoTools - The Open Source Java GIS Toolkit
- * http://geotools.org
- *
- * (C) 2005-2008, Open Source Geospatial Foundation (OSGeo)
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation;
- * version 2.1 of the License.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- */
-package org.geotools.referencing.factory.epsg;
-
-import static org.geotools.measure.Units.DEGREE_ANGLE;
-import static org.geotools.measure.Units.DEGREE_MINUTE_SECOND;
-import static org.geotools.measure.Units.FOOT;
-import static org.geotools.measure.Units.GRADE;
-import static org.geotools.measure.Units.KILOMETER;
-import static org.geotools.measure.Units.METRE;
-import static org.geotools.measure.Units.MICRORADIAN;
-import static org.geotools.measure.Units.MINUTE_ANGLE;
-import static org.geotools.measure.Units.NAUTICAL_MILE;
-import static org.geotools.measure.Units.ONE;
-import static org.geotools.measure.Units.PPM;
-import static org.geotools.measure.Units.RADIAN;
-import static org.geotools.measure.Units.SECOND_ANGLE;
-import static org.geotools.measure.Units.SEXAGESIMAL_DMS;
-
-import java.awt.RenderingHints;
-import java.io.File;
-import java.io.IOException;
-import java.io.ObjectStreamException;
-import java.io.Serializable;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.sql.Connection;
-import java.sql.DatabaseMetaData;
-import java.sql.Date;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.ResultSetMetaData;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.AbstractMap;
-import java.util.AbstractSet;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.IdentityHashMap;
-import java.util.Iterator;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.NoSuchElementException;
-import java.util.Set;
-import java.util.logging.Level;
-import java.util.logging.LogRecord;
-import javax.measure.Unit;
-import javax.measure.quantity.Angle;
-import javax.measure.quantity.Length;
-import javax.naming.NamingException;
-import javax.sql.DataSource;
-import org.geotools.measure.Units;
-import org.geotools.metadata.i18n.ErrorKeys;
-import org.geotools.metadata.i18n.Errors;
-import org.geotools.metadata.i18n.LoggingKeys;
-import org.geotools.metadata.i18n.Loggings;
-import org.geotools.metadata.i18n.Vocabulary;
-import org.geotools.metadata.i18n.VocabularyKeys;
-import org.geotools.metadata.iso.citation.CitationImpl;
-import org.geotools.metadata.iso.citation.Citations;
-import org.geotools.metadata.iso.extent.ExtentImpl;
-import org.geotools.metadata.iso.extent.GeographicBoundingBoxImpl;
-import org.geotools.metadata.iso.quality.AbsoluteExternalPositionalAccuracyImpl;
-import org.geotools.metadata.iso.quality.QuantitativeResultImpl;
-import org.geotools.parameter.DefaultParameterDescriptor;
-import org.geotools.parameter.DefaultParameterDescriptorGroup;
-import org.geotools.referencing.AbstractIdentifiedObject;
-import org.geotools.referencing.NamedIdentifier;
-import org.geotools.referencing.cs.DefaultCoordinateSystemAxis;
-import org.geotools.referencing.datum.BursaWolfParameters;
-import org.geotools.referencing.datum.DefaultGeodeticDatum;
-import org.geotools.referencing.factory.AbstractCachedAuthorityFactory;
-import org.geotools.referencing.factory.BufferedAuthorityFactory;
-import org.geotools.referencing.factory.DirectAuthorityFactory;
-import org.geotools.referencing.factory.IdentifiedObjectFinder;
-import org.geotools.referencing.operation.DefaultConcatenatedOperation;
-import org.geotools.referencing.operation.DefaultOperation;
-import org.geotools.referencing.operation.DefaultOperationMethod;
-import org.geotools.referencing.operation.DefiningConversion;
-import org.geotools.referencing.util.CRSUtilities;
-import org.geotools.util.LocalName;
-import org.geotools.util.ObjectCache;
-import org.geotools.util.ScopedName;
-import org.geotools.util.SimpleInternationalString;
-import org.geotools.util.TableWriter;
-import org.geotools.util.Version;
-import org.geotools.util.factory.GeoTools;
-import org.geotools.util.factory.Hints;
-import org.geotools.util.logging.Logging;
-import org.opengis.metadata.Identifier;
-import org.opengis.metadata.citation.Citation;
-import org.opengis.metadata.extent.Extent;
-import org.opengis.metadata.quality.EvaluationMethodType;
-import org.opengis.metadata.quality.PositionalAccuracy;
-import org.opengis.parameter.InvalidParameterValueException;
-import org.opengis.parameter.ParameterDescriptor;
-import org.opengis.parameter.ParameterNotFoundException;
-import org.opengis.parameter.ParameterValue;
-import org.opengis.parameter.ParameterValueGroup;
-import org.opengis.referencing.FactoryException;
-import org.opengis.referencing.IdentifiedObject;
-import org.opengis.referencing.NoSuchAuthorityCodeException;
-import org.opengis.referencing.NoSuchIdentifierException;
-import org.opengis.referencing.crs.CRSFactory;
-import org.opengis.referencing.crs.CompoundCRS;
-import org.opengis.referencing.crs.CoordinateReferenceSystem;
-import org.opengis.referencing.crs.GeneralDerivedCRS;
-import org.opengis.referencing.crs.GeocentricCRS;
-import org.opengis.referencing.crs.GeographicCRS;
-import org.opengis.referencing.crs.ProjectedCRS;
-import org.opengis.referencing.crs.SingleCRS;
-import org.opengis.referencing.cs.AxisDirection;
-import org.opengis.referencing.cs.CSFactory;
-import org.opengis.referencing.cs.CartesianCS;
-import org.opengis.referencing.cs.CoordinateSystem;
-import org.opengis.referencing.cs.CoordinateSystemAxis;
-import org.opengis.referencing.cs.EllipsoidalCS;
-import org.opengis.referencing.cs.SphericalCS;
-import org.opengis.referencing.cs.VerticalCS;
-import org.opengis.referencing.datum.Datum;
-import org.opengis.referencing.datum.DatumFactory;
-import org.opengis.referencing.datum.Ellipsoid;
-import org.opengis.referencing.datum.EngineeringDatum;
-import org.opengis.referencing.datum.GeodeticDatum;
-import org.opengis.referencing.datum.PrimeMeridian;
-import org.opengis.referencing.datum.VerticalDatum;
-import org.opengis.referencing.datum.VerticalDatumType;
-import org.opengis.referencing.operation.ConcatenatedOperation;
-import org.opengis.referencing.operation.Conversion;
-import org.opengis.referencing.operation.CoordinateOperation;
-import org.opengis.referencing.operation.MathTransform;
-import org.opengis.referencing.operation.OperationMethod;
-import org.opengis.referencing.operation.Projection;
-import org.opengis.referencing.operation.Transformation;
-import org.opengis.util.GenericName;
-import org.opengis.util.InternationalString;
-import si.uom.NonSI;
-import si.uom.SI;
-
-/**
- * A coordinate reference system factory backed by the EPSG database tables.
- *
- *
The EPSG database is freely available at http://www.epsg.org. Current version of this class requires EPSG
- * database version 6.6 or above.
- *
- *
This factory makes use of a provided {@link ObjectCache}, and may be deployed in stand aline
- * fashion; or as a worker for a {@link MultiEpsgFactory}.
- *
- *
This class is abstract - please see the subclasses for dialect specific implementations:
- *
- *
- *
{@link AccessDialectEpsgFactory}
- *
{@link AnsiDialectEpsgFactory}
- *
{@link OracleDialectEpsgFactory}
- *
- *
- * These factories accepts names as well as numerical identifiers. For example "NTF (Paris) /
- * France I" and {@code "27581"} both fetchs the same object. However, names may be ambiguous
- * since the same name may be used for more than one object. This is the case of "WGS 84" for
- * example. If such an ambiguity is found, an exception will be thrown. If names are not wanted as a
- * legal EPSG code, subclasses can override the {@link #isPrimaryKey} method.
- *
- * @since 2.4
- * @version $Id$
- * @author Yann Cézard
- * @author Martin Desruisseaux (IRD)
- * @author Rueben Schulz
- * @author Matthias Basler
- * @author Andrea Aime
- */
-@SuppressWarnings("PMD.CloseResource") // class implements its own PreparedStatement pooling
-public abstract class AbstractEpsgFactory extends AbstractCachedAuthorityFactory {
- /// Datum shift operation methods
- /** First Bursa-Wolf method. */
- private static final int BURSA_WOLF_MIN_CODE = 9603;
-
- /** Last Bursa-Wolf method. */
- private static final int BURSA_WOLF_MAX_CODE = 9607;
-
- /** Rotation frame method. */
- private static final int ROTATION_FRAME_CODE = 9607;
-
- /** Dummy operation to ignore. */
- private static final int DUMMY_OPERATION = 1;
-
- /** The name for the transformation accuracy metadata. */
- private static final InternationalString TRANSFORMATION_ACCURACY =
- Vocabulary.formatInternational(VocabularyKeys.TRANSFORMATION_ACCURACY);
-
- /**
- * The authority for this database. Will be created only when first needed. This authority will
- * contains the database version in the {@linkplain Citation#getEdition edition} attribute,
- * together with the {@linkplain Citation#getEditionDate edition date}.
- */
- private transient Citation authority; // FIXME: always EPSG
-
- /** A DataSource to the EPSG database being used. */
- protected javax.sql.DataSource dataSource;
-
- /**
- * The connection to the EPSG database - this is create in a lazy manner from the DataSource.
- *
- *
This field is managed as part of our connection lifecycle.
- */
- private Connection connection;
-
- /**
- * A pool of prepared statements. Key are {@link String} object related to their originating
- * method name (for example "Ellipsoid" for {@link #createEllipsoid}, while values are {@link
- * PreparedStatement} objects.
- *
- *
Note: It is okay to use {@link IdentityHashMap} instead of {@link
- * HashMap} because the keys will always be the exact same object, namely the hard-coded
- * argument given to calls to {@link #prepareStatement} in this class.
- *
- *
This field is managed as part of our connection lifecycle.
- */
- private final Map statements = new IdentityHashMap<>();
-
- /**
- * Last object type returned by {@link #createObject}, or -1 if none. This type is an index in
- * the {@link #TABLES_INFO} array and is strictly for {@link #createObject} internal use.
- */
- private int lastObjectType = -1;
-
- /**
- * The last table in which object name were looked for. This is for internal use by {@link
- * #toPrimaryKey} only.
- */
- private transient String lastTableForName;
-
- /**
- * Cache for axis names. This service is not provided by {@link BufferedAuthorityFactory} since
- * {@link AxisName} object are particular to the EPSG database.
- *
- * @see #getAxisName
- */
- private final Map axisNames = new HashMap<>();
-
- /**
- * Cache for axis numbers. This service is not provided by {@link BufferedAuthorityFactory}
- * since the number of axis is used internally in this class.
- *
- * @see #getDimensionForCRS
- */
- private final Map axisCounts = new HashMap<>();
-
- /**
- * Cache for projection checks. This service is not provided by {@link BufferedAuthorityFactory}
- * since the check that a transformation is a projection is used internally in this class.
- *
- * @see #isProjection
- */
- private final Map codeProjection = new HashMap<>();
-
- /** Pool of naming systems, used for caching. There is usually few of them (about 15). */
- private final Map scopes = new HashMap<>();
-
- /**
- * The properties to be given the objects to construct. Reused every time {@link
- * #createProperties} is invoked.
- */
- private final Map properties = new HashMap<>();
-
- /**
- * A safety guard for preventing never-ending loops in recursive calls to {@link #createDatum}.
- * This is used by {@link #createBursaWolfParameters}, which need to create a target datum. The
- * target datum could have its own Bursa-Wolf parameters, with one of them pointing again to the
- * source datum.
- */
- private final Set safetyGuard = new HashSet<>();
-
- public AbstractEpsgFactory(final Hints userHints) throws FactoryException {
- super(MAXIMUM_PRIORITY - 20);
- // The following hints have no effect on this class behaviour,
- // but tell to the user what this factory do about axis order.
- hints.put(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.FALSE);
- hints.put(Hints.FORCE_STANDARD_AXIS_DIRECTIONS, Boolean.FALSE);
- hints.put(Hints.FORCE_STANDARD_AXIS_UNITS, Boolean.FALSE);
-
- //
- // We need to obtain our DataSource
- if (userHints != null) {
- Object hint = userHints.get(Hints.EPSG_DATA_SOURCE);
- if (hint instanceof String) {
- String name = (String) hint;
- try {
- // BUG: CWE-20 Improper Input Validation
- // dataSource = (DataSource) GeoTools.getInitialContext().lookup(name);
- // FIXED:
- dataSource = (DataSource) GeoTools.jndiLookup(name);
- } catch (NamingException e) {
- throw new FactoryException("A EPSG_DATA_SOURCE hint is required:" + e);
- }
- hints.put(Hints.EPSG_DATA_SOURCE, dataSource);
- } else if (hint instanceof DataSource) {
- dataSource = (DataSource) hint;
- hints.put(Hints.EPSG_DATA_SOURCE, dataSource);
- } else {
- throw new FactoryException("A EPSG_DATA_SOURCE hint is required.");
- }
- } else {
- throw new FactoryException("A EPSG_DATA_SOURCE hint is required.");
- }
- }
-
- public AbstractEpsgFactory(final Hints userHints, final javax.sql.DataSource dataSource) {
- super(MAXIMUM_PRIORITY - 20);
-
- this.dataSource = dataSource;
- // The following hints have no effect on this class behaviour,
- // but tell to the user what this factory do about axis order.
- hints.put(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.FALSE);
- hints.put(Hints.FORCE_STANDARD_AXIS_DIRECTIONS, Boolean.FALSE);
- hints.put(Hints.FORCE_STANDARD_AXIS_UNITS, Boolean.FALSE);
- hints.put(Hints.EPSG_DATA_SOURCE, dataSource);
- }
- /**
- * Constructs an authority factory using the specified connection.
- *
- * @param userHints The underlying factories used for objects creation.
- * @param connection The connection to the underlying EPSG database.
- */
- public AbstractEpsgFactory(final Hints userHints, final Connection connection) {
- super(MAXIMUM_PRIORITY - 20, userHints);
- // The following hints have no effect on this class behaviour,
- // but tell to the user what this factory do about axis order.
- hints.put(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.FALSE);
- hints.put(Hints.FORCE_STANDARD_AXIS_DIRECTIONS, Boolean.FALSE);
- hints.put(Hints.FORCE_STANDARD_AXIS_UNITS, Boolean.FALSE);
- this.connection = connection;
- ensureNonNull("connection", connection);
- }
-
- /**
- * Returns the authority for this EPSG database. This authority will contains the database
- * version in the {@linkplain Citation#getEdition edition} attribute, together with the
- * {@linkplain Citation#getEditionDate edition date}.
- */
- @Override
- public synchronized Citation getAuthority() {
- if (authority == null)
- try {
- final String query =
- adaptSQL(
- "SELECT VERSION_NUMBER, VERSION_DATE FROM [Version History]"
- + " ORDER BY VERSION_DATE DESC");
- final DatabaseMetaData metadata = getConnection().getMetaData();
- try (Statement statement = getConnection().createStatement();
- ResultSet result = statement.executeQuery(query)) {
- if (result.next()) {
- final String version = result.getString(1);
- final Date date = result.getDate(2);
- final String engine = metadata.getDatabaseProductName();
- final CitationImpl c = new CitationImpl(Citations.EPSG);
- c.getAlternateTitles()
- .add(
- Vocabulary.formatInternational(
- VocabularyKeys.DATA_BASE_$3,
- "EPSG",
- version,
- engine));
- c.setEdition(new SimpleInternationalString(version));
- c.setEditionDate(date);
- authority = (Citation) c.unmodifiable();
- hints.put(
- Hints.VERSION,
- new Version(version)); // For getImplementationHints()
- } else {
- authority = Citations.EPSG;
- }
- }
- } catch (SQLException exception) {
- Logging.unexpectedException(
- LOGGER, AbstractEpsgFactory.class, "getAuthority", exception);
- return Citations.EPSG;
- }
- return authority;
- }
-
- /**
- * Returns a description of the database engine.
- *
- * @throws FactoryException if the database's metadata can't be fetched.
- */
- @Override
- public synchronized String getBackingStoreDescription() throws FactoryException {
- final Citation authority = getAuthority();
- try (TableWriter table = new TableWriter(null, " ")) {
- final Vocabulary resources = Vocabulary.getResources(null);
- CharSequence cs;
- if ((cs = authority.getEdition()) != null) {
- table.write(resources.getString(VocabularyKeys.VERSION_OF_$1, "EPSG"));
- table.write(':');
- table.nextColumn();
- table.write(cs.toString());
- table.nextLine();
- }
- try {
- String s;
- final DatabaseMetaData metadata = getConnection().getMetaData();
- if ((s = metadata.getDatabaseProductName()) != null) {
- table.write(resources.getLabel(VocabularyKeys.DATABASE_ENGINE));
- table.nextColumn();
- table.write(s);
- if ((s = metadata.getDatabaseProductVersion()) != null) {
- table.write(' ');
- table.write(resources.getString(VocabularyKeys.VERSION_$1, s));
- }
- table.nextLine();
- }
- if ((s = metadata.getURL()) != null) {
- table.write(resources.getLabel(VocabularyKeys.DATABASE_URL));
- table.nextColumn();
- table.write(s);
- table.nextLine();
- }
- } catch (SQLException exception) {
- throw new FactoryException(exception);
- }
- return table.toString();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Returns the implementation hints for this factory. The returned map contains all the values
- * specified in {@linkplain DirectAuthorityFactory#getImplementationHints subclass}, with the
- * addition of {@link Hints#VERSION VERSION}.
- */
- @Override
- public Map getImplementationHints() {
- if (authority == null) {
- // For the computation of Hints.VERSION.
- getAuthority();
- }
- return super.getImplementationHints();
- }
-
- /**
- * Returns the set of authority codes of the given type.
- *
- * @param type The spatial reference objects type (may be {@code Object.class}).
- * @return The set of authority codes for spatial reference objects of the given type. If this
- * factory doesn't contains any object of the given type, then this method returns an empty
- * set.
- * @throws FactoryException if access to the underlying database failed.
- */
- @Override
- protected synchronized Set generateAuthorityCodes(final Class type)
- throws FactoryException {
- Set result = new HashSet<>();
- for (final TableInfo table : TABLES_INFO) {
- if (table.isTypeOf(type)) {
- final AuthorityCodeSet codes = new AuthorityCodeSet(table, type);
- result.addAll(codes);
- }
- }
- return result;
- }
-
- /**
- * Gets a description of the object corresponding to a code.
- *
- * @param code Value allocated by authority.
- * @return A description of the object, or {@code null} if the object corresponding to the
- * specified {@code code} has no description.
- * @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 FactoryException {
- IdentifiedObject identifiedObject = createObject(code);
- final Identifier identifier = identifiedObject.getName();
- if (identifier instanceof GenericName) {
- return ((GenericName) identifier).toInternationalString();
- }
- return new SimpleInternationalString(identifier.getCode());
- }
-
- /**
- * Returns a prepared statement for the specified name. Most {@link PreparedStatement} creations
- * are performed through this method, except {@link #getNumericalIdentifier} and {@link
- * #createObject}.
- *
- * @param key A key uniquely identifying the caller (e.g. {@code "Ellipsoid"} for {@link
- * #createEllipsoid}).
- * @param sql The SQL statement to use if for creating the {@link PreparedStatement} object.
- * Will be used only if no prepared statement was already created for the specified key.
- * @return The prepared statement.
- * @throws SQLException if the prepared statement can't be created.
- */
- private PreparedStatement prepareStatement(final String key, final String sql)
- throws SQLException {
- assert Thread.holdsLock(this);
- PreparedStatement stmt = statements.get(key);
- if (stmt == null) {
- stmt = getConnection().prepareStatement(adaptSQL(sql));
- statements.put(key, stmt);
- }
- return stmt;
- }
-
- /**
- * Gets the string from the specified {@link ResultSet}. The string is required to be non-null.
- * A null string will throw an exception.
- *
- * @param result The result set to fetch value from.
- * @param columnIndex The column index (1-based).
- * @param code The identifier of the record where the string was found.
- * @return The string at the specified column.
- * @throws SQLException if a SQL error occured.
- * @throws FactoryException If a null value was found.
- */
- private static String getString(
- final ResultSet result, final int columnIndex, final String code)
- throws SQLException, FactoryException {
- final String value = result.getString(columnIndex);
- ensureNonNull(result, columnIndex, code);
- return value.trim();
- }
-
- /**
- * Same as {@link #getString(ResultSet,int,String)}, but report the fault on an alternative
- * column if the value is null.
- */
- private static String getString(
- final ResultSet result, final int columnIndex, final String code, final int columnFault)
- throws SQLException, FactoryException {
- final String str = result.getString(columnIndex);
- if (result.wasNull()) {
- final ResultSetMetaData metadata = result.getMetaData();
- final String column = metadata.getColumnName(columnFault);
- final String table = metadata.getTableName(columnFault);
- result.close();
- throw new FactoryException(
- Errors.format(ErrorKeys.NULL_VALUE_IN_TABLE_$3, code, column, table));
- }
- return str.trim();
- }
-
- /**
- * Gets the value from the specified {@link ResultSet}. The value is required to be non-null. A
- * null value (i.e. blank) will throw an exception.
- *
- * @param result The result set to fetch value from.
- * @param columnIndex The column index (1-based).
- * @param code The identifier of the record where the string was found.
- * @return The double at the specified column.
- * @throws SQLException if a SQL error occured.
- * @throws FactoryException If a null value was found.
- */
- private static double getDouble(
- final ResultSet result, final int columnIndex, final String code)
- throws SQLException, FactoryException {
- final double value = result.getDouble(columnIndex);
- ensureNonNull(result, columnIndex, code);
- return value;
- }
-
- /**
- * Gets the value from the specified {@link ResultSet}. The value is required to be non-null. A
- * null value (i.e. blank) will throw an exception.
- *
- * @param result The result set to fetch value from.
- * @param columnIndex The column index (1-based).
- * @param code The identifier of the record where the string was found.
- * @return The integer at the specified column.
- * @throws SQLException if a SQL error occured.
- * @throws FactoryException If a null value was found.
- */
- private static int getInt(final ResultSet result, final int columnIndex, final String code)
- throws SQLException, FactoryException {
- final int value = result.getInt(columnIndex);
- ensureNonNull(result, columnIndex, code);
- return value;
- }
-
- /**
- * Make sure that the last result was non-null. Used for {@code getString}, {@code getDouble}
- * and {@code getInt} methods only.
- */
- private static void ensureNonNull(
- final ResultSet result, final int columnIndex, final String code)
- throws SQLException, FactoryException {
- if (result.wasNull()) {
- final ResultSetMetaData metadata = result.getMetaData();
- final String column = metadata.getColumnName(columnIndex);
- final String table = metadata.getTableName(columnIndex);
- result.close();
- throw new FactoryException(
- Errors.format(ErrorKeys.NULL_VALUE_IN_TABLE_$3, code, column, table));
- }
- }
-
- /**
- * Converts a code from an arbitrary name to the numerical identifier (the primary key). If the
- * supplied code is already a numerical value, then it is returned unchanged. If the code is not
- * found in the name column, it is returned unchanged as well so that the caller will produces
- * an appropriate "Code not found" error message. If the code is found more than once, then an
- * exception is thrown.
- *
- *
Note that this method includes a call to {@link #trimAuthority}, so there is no need to
- * call it before or after this method.
- *
- * @param type The type of object to create.
- * @param code The code to check.
- * @param table The table where the code should appears.
- * @param codeColumn The column name for the code.
- * @param nameColumn The column name for the name.
- * @return The numerical identifier (i.e. the table primary key value).
- * @throws SQLException if an error occured while reading the database.
- */
- private String toPrimaryKey(
- final Class type,
- final String code,
- final String table,
- final String codeColumn,
- final String nameColumn)
- throws SQLException, FactoryException {
- assert Thread.holdsLock(this);
- String identifier = trimAuthority(code);
- if (!isPrimaryKey(identifier)) {
- /*
- * The character is not the numerical code. Search the value in the database.
- * If a prepared statement is already available, reuse it providing that it was
- * created for the current table. Otherwise, we will create a new statement.
- */
- final String KEY = "NumericalIdentifier";
- PreparedStatement statement = statements.get(KEY);
- if (statement != null) {
- if (!table.equals(lastTableForName)) {
- statements.remove(KEY);
- statement.close();
- statement = null;
- lastTableForName = null;
- }
- }
- if (statement == null) {
- final String query =
- "SELECT " + codeColumn + " FROM " + table + " WHERE " + nameColumn + " = ?";
- statement = getConnection().prepareStatement(adaptSQL(query));
- statements.put(KEY, statement);
- }
- statement.setString(1, identifier);
- identifier = null;
- try (ResultSet result = statement.executeQuery()) {
- while (result.next()) {
- identifier = ensureSingleton(result.getString(1), identifier, code);
- }
- }
- if (identifier == null) {
- throw noSuchAuthorityCode(type, code);
- }
- }
- return identifier;
- }
-
- /**
- * Make sure that an object constructed from the database is not incoherent. If the code
- * supplied to a {@code createFoo} method exists in the database, then we should find only one
- * record. However, we will do a paranoiac check and verify if there is more records, using a
- * {@code while (results.next())} loop instead of {@code if (results.next())}. This method is
- * invoked in the loop for making sure that, if there is more than one record (which should
- * never happen), at least they have identical contents.
- *
- * @param newValue The newly constructed object.
- * @param oldValue The object previously constructed, or {@code null} if none.
- * @param code The EPSG code (for formatting error message).
- * @throws FactoryException if a duplication has been detected.
- * @todo Use generic type when we will be allowed to compile for J2SE 1.5.
- */
- private static T ensureSingleton(final T newValue, final T oldValue, final String code)
- throws FactoryException {
- if (oldValue == null) {
- return newValue;
- }
- if (oldValue.equals(newValue)) {
- return oldValue;
- }
- throw new FactoryException(Errors.format(ErrorKeys.DUPLICATED_VALUES_$1, code));
- }
-
- /**
- * Returns the name for the {@link IdentifiedObject} to construct. This method also search for
- * alias.
- *
- * @param name The name for the {@link IndentifiedObject} to construct.
- * @param code The EPSG code of the object to construct.
- * @param remarks Remarks, or {@code null} if none.
- * @return The name together with a set of properties.
- */
- private Map generateProperties(
- final String name, final String code, String remarks)
- throws SQLException, FactoryException {
- properties.clear();
- final Citation authority = getAuthority();
- if (name != null) {
- properties.put(IdentifiedObject.NAME_KEY, new NamedIdentifier(authority, name.trim()));
- }
- if (code != null) {
- final InternationalString edition = authority.getEdition();
- final String version = (edition != null) ? edition.toString() : null;
- properties.put(
- IdentifiedObject.IDENTIFIERS_KEY,
- new NamedIdentifier(authority, code.trim(), version));
- }
- if (remarks != null && (remarks = remarks.trim()).length() != 0) {
- properties.put(IdentifiedObject.REMARKS_KEY, remarks);
- }
- /*
- * Search for alias.
- */
- List alias = null;
- final PreparedStatement stmt =
- prepareStatement(
- "Alias",
- "SELECT NAMING_SYSTEM_NAME, ALIAS"
- + " FROM [Alias] INNER JOIN [Naming System]"
- + " ON [Alias].NAMING_SYSTEM_CODE ="
- + " [Naming System].NAMING_SYSTEM_CODE"
- + " WHERE OBJECT_CODE = ?");
- stmt.setString(1, code);
- try (ResultSet result = stmt.executeQuery()) {
- while (result.next()) {
- final String scope = result.getString(1);
- final String local = getString(result, 2, code);
- final GenericName generic;
- if (scope == null) {
- generic = new LocalName(local);
- } else {
- LocalName cached = scopes.get(scope);
- if (cached == null) {
- cached = new LocalName(scope);
- scopes.put(scope, cached);
- }
- generic = new ScopedName(cached, local);
- }
- if (alias == null) {
- alias = new ArrayList<>();
- }
- alias.add(generic);
- }
- }
- if (alias != null) {
- properties.put(
- IdentifiedObject.ALIAS_KEY, alias.toArray(new GenericName[alias.size()]));
- }
- return properties;
- }
-
- /**
- * Returns the name for the {@link IdentifiedObject} to construct. This method also search for
- * alias.
- *
- * @param name The name for the {@link IndentifiedObject} to construct.
- * @param code The EPSG code of the object to construct.
- * @param area The area of use, or {@code null} if none.
- * @param scope The scope, or {@code null} if none.
- * @param remarks Remarks, or {@code null} if none.
- * @return The name together with a set of properties.
- */
- private Map generateProperties(
- final String name, final String code, String area, String scope, String remarks)
- throws SQLException, FactoryException {
- final Map properties = generateProperties(name, code, remarks);
- if (area != null && (area = area.trim()).length() != 0) {
- final Extent extent = generateExtent(area);
- properties.put(Datum.DOMAIN_OF_VALIDITY_KEY, extent);
- }
- if (scope != null && (scope = scope.trim()).length() != 0) {
- properties.put(Datum.SCOPE_KEY, scope);
- }
- return properties;
- }
-
- /**
- * Returns an arbitrary object from a code. The default implementation invokes one of {@link
- * #createCoordinateReferenceSystem}, {@link #createCoordinateSystem}, {@link #createDatum},
- * {@link #createEllipsoid}, or {@link #createUnit} methods according the object type.
- *
- * @param code The EPSG value.
- * @return The object.
- * @throws NoSuchAuthorityCodeException if this method can't find the requested code.
- * @throws FactoryException if some other kind of failure occured in the backing store. This
- * exception usually have {@link SQLException} as its cause.
- */
- @Override
- @SuppressWarnings("PMD.OverrideBothEqualsAndHashcode")
- public synchronized IdentifiedObject generateObject(final String code) throws FactoryException {
- ensureNonNull("code", code);
- final String KEY = "IdentifiedObject";
- PreparedStatement stmt = statements.get(KEY); // Null allowed.
- StringBuilder query = null; // Will be created only if the last statement doesn't suit.
- /*
- * Iterates through all tables listed in TABLES_INFO, starting with the table used during
- * the last call to 'createObject(code)'. This approach assumes that two consecutive calls
- * will often return the same type of object. If the object type changed, then this method
- * will have to discard the old prepared statement and prepare a new one, which may be a
- * costly operation. Only the last successful prepared statement is cached, in order to keep
- * the amount of statements low. Unsuccessful statements are immediately disposed.
- */
- final String epsg = trimAuthority(code);
- final boolean isPrimaryKey = isPrimaryKey(epsg);
- final int tupleToSkip = isPrimaryKey ? lastObjectType : -1;
- int index = -1;
- for (int i = -1; i < TABLES_INFO.length; i++) {
- if (i == tupleToSkip) {
- // Avoid to test the same table twice. Note that this test also avoid a
- // NullPointerException if 'stmt' is null, since 'lastObjectType' should
- // be -1 in this case.
- continue;
- }
- try {
- if (i >= 0) {
- final TableInfo table = TABLES_INFO[i];
- final String column = isPrimaryKey ? table.codeColumn : table.nameColumn;
- if (column == null) {
- continue;
- }
- if (query == null) {
- query = new StringBuilder("SELECT ");
- }
- query.setLength(7); // 7 is the length of "SELECT " in the line above.
- query.append(table.codeColumn);
- query.append(" FROM ");
- query.append(table.table);
- query.append(" WHERE ");
- query.append(column);
- query.append(" = ?");
- if (isPrimaryKey) {
- assert !statements.containsKey(KEY) : table;
- stmt = prepareStatement(KEY, query.toString());
- } else {
- // Do not cache the statement for names.
- stmt = getConnection().prepareStatement(adaptSQL(query.toString()));
- }
- }
- /*
- * Checks if at least one record is found for the code. If the code is the primary
- * key, then we will stop at the first table found since a well-formed EPSG database
- * should not contains any duplicate identifiers. In the code is a name, then search
- * in all tables since duplicate names exist.
- */
- stmt.setString(1, epsg);
- try (final ResultSet result = stmt.executeQuery()) {
- final boolean present = result.next();
- if (present) {
- if (index >= 0) {
- throw new FactoryException(
- Errors.format(ErrorKeys.DUPLICATED_VALUES_$1, code));
- }
- index = (i < 0) ? lastObjectType : i;
- if (isPrimaryKey) {
- // Don't scan other tables, since primary keys should be unique.
- // Note that names may be duplicated, so we don't stop for names.
- break;
- }
- }
- }
- if (isPrimaryKey) {
- if (statements.remove(KEY) == null) {
- throw new AssertionError(code); // Should never happen.
- }
- }
- stmt.close();
- } catch (SQLException exception) {
- throw databaseFailure(IdentifiedObject.class, code, exception);
- }
- }
- /*
- * If a record has been found in one table, then delegates to the appropriate method.
- */
- if (isPrimaryKey) {
- lastObjectType = index;
- }
- if (index >= 0) {
- switch (index) {
- case 0:
- return createCoordinateReferenceSystem(code);
- case 1:
- return createCoordinateSystem(code);
- case 2:
- return createCoordinateSystemAxis(code);
- case 3:
- return createDatum(code);
- case 4:
- return createEllipsoid(code);
- case 5:
- return createPrimeMeridian(code);
- case 6:
- return createCoordinateOperation(code);
- case 7:
- return generateOperationMethod(code);
- case 8:
- return generateParameterDescriptor(code);
- case 9:
- break; // Can't cast Unit to IdentifiedObject
- default:
- throw new AssertionError(index); // Should not happen
- }
- }
- return super.createObject(code);
- }
-
- /**
- * Returns an unit from a code.
- *
- * @param code Value allocated by authority.
- * @return The unit object.
- * @throws NoSuchAuthorityCodeException if this method can't find the requested code.
- * @throws FactoryException if some other kind of failure occured in the backing store. This
- * exception usually have {@link SQLException} as its cause.
- */
- @Override
- public synchronized Unit> generateUnit(final String code) throws FactoryException {
- ensureNonNull("code", code);
- Unit> returnValue = null;
- try {
- final String primaryKey =
- toPrimaryKey(
- Unit.class, code, "[Unit of Measure]", "UOM_CODE", "UNIT_OF_MEAS_NAME");
- final PreparedStatement stmt =
- prepareStatement(
- "Unit",
- "SELECT UOM_CODE,"
- + " FACTOR_B,"
- + " FACTOR_C,"
- + " TARGET_UOM_CODE"
- + " FROM [Unit of Measure]"
- + " WHERE UOM_CODE = ?");
- stmt.setString(1, primaryKey);
- try (ResultSet result = stmt.executeQuery()) {
- while (result.next()) {
- final int source = getInt(result, 1, code);
- final double b = result.getDouble(2);
- final double c = result.getDouble(3);
- final int target = getInt(result, 4, code);
- final Unit> base = getUnit(target);
- if (base == null) {
- throw noSuchAuthorityCode(Unit.class, String.valueOf(target));
- }
- Unit unit = getUnit(source);
- if (unit == null) {
- // TODO: check unit consistency here.
- if (b != 0 && c != 0) {
- unit = (b == c) ? base : base.multiply(b / c);
- } else {
- // TODO: provide a localized message.
- throw new FactoryException("Unsupported unit: " + code);
- }
- }
- returnValue = ensureSingleton(unit, returnValue, code);
- }
- }
- } catch (SQLException exception) {
- throw databaseFailure(Unit.class, code, exception);
- }
- if (returnValue == null) {
- throw noSuchAuthorityCode(Unit.class, code);
- }
- return returnValue;
- }
-
- /**
- * Returns an ellipsoid from a code.
- *
- * @param code The EPSG value.
- * @return The ellipsoid object.
- * @throws NoSuchAuthorityCodeException if this method can't find the requested code.
- * @throws FactoryException if some other kind of failure occured in the backing store. This
- * exception usually have {@link SQLException} as its cause.
- */
- @Override
- public synchronized Ellipsoid generateEllipsoid(final String code) throws FactoryException {
- ensureNonNull("code", code);
- Ellipsoid returnValue = null;
- try {
- final String primaryKey =
- toPrimaryKey(
- Ellipsoid.class,
- code,
- "[Ellipsoid]",
- "ELLIPSOID_CODE",
- "ELLIPSOID_NAME");
- final PreparedStatement stmt =
- prepareStatement(
- "Ellipsoid",
- "SELECT ELLIPSOID_CODE,"
- + " ELLIPSOID_NAME,"
- + " SEMI_MAJOR_AXIS,"
- + " INV_FLATTENING,"
- + " SEMI_MINOR_AXIS,"
- + " UOM_CODE,"
- + " REMARKS"
- + " FROM [Ellipsoid]"
- + " WHERE ELLIPSOID_CODE = ?");
- stmt.setString(1, primaryKey);
- try (ResultSet result = stmt.executeQuery()) {
- while (result.next()) {
- /*
- * One of 'semiMinorAxis' and 'inverseFlattening' values can be NULL in
- * the database. Consequently, we don't use 'getString(ResultSet, int)'
- * because we don't want to thrown an exception if a NULL value is found.
- */
- final String epsg = getString(result, 1, code);
- final String name = getString(result, 2, code);
- final double semiMajorAxis = getDouble(result, 3, code);
- final double inverseFlattening = result.getDouble(4);
- final double semiMinorAxis = result.getDouble(5);
- final String unitCode = getString(result, 6, code);
- final String remarks = result.getString(7);
- @SuppressWarnings("unchecked")
- final Unit unit = (Unit) createUnit(unitCode);
- final Map properties = generateProperties(name, epsg, remarks);
- final Ellipsoid ellipsoid;
- if (inverseFlattening == 0) {
- if (semiMinorAxis == 0) {
- // Both are null, which is not allowed.
- final String column = result.getMetaData().getColumnName(3);
- result.close();
- throw new FactoryException(
- Errors.format(ErrorKeys.NULL_VALUE_IN_TABLE_$3, code, column));
- } else {
- // We only have semiMinorAxis defined -> it's OK
- ellipsoid =
- factories
- .getDatumFactory()
- .createEllipsoid(
- properties, semiMajorAxis, semiMinorAxis, unit);
- }
- } else {
- if (semiMinorAxis != 0) {
- // Both 'inverseFlattening' and 'semiMinorAxis' are defined.
- // Log a warning and create the ellipsoid using the inverse flattening.
- final LogRecord record =
- Loggings.format(
- Level.WARNING, LoggingKeys.AMBIGUOUS_ELLIPSOID, code);
- record.setLoggerName(LOGGER.getName());
- LOGGER.log(record);
- }
- ellipsoid =
- factories
- .getDatumFactory()
- .createFlattenedSphere(
- properties, semiMajorAxis, inverseFlattening, unit);
- }
- /*
- * Now that we have built an ellipsoid, compare
- * it with the previous one (if any).
- */
- returnValue = ensureSingleton(ellipsoid, returnValue, code);
- }
- }
- } catch (SQLException exception) {
- throw databaseFailure(Ellipsoid.class, code, exception);
- }
- if (returnValue == null) {
- throw noSuchAuthorityCode(Ellipsoid.class, code);
- }
- return returnValue;
- }
-
- /**
- * Returns a prime meridian, relative to Greenwich.
- *
- * @param code Value allocated by authority.
- * @return The prime meridian object.
- * @throws NoSuchAuthorityCodeException if this method can't find the requested code.
- * @throws FactoryException if some other kind of failure occured in the backing store. This
- * exception usually have {@link SQLException} as its cause.
- */
- @Override
- public synchronized PrimeMeridian generatePrimeMeridian(final String code)
- throws FactoryException {
- ensureNonNull("code", code);
- PrimeMeridian returnValue = null;
- try {
- final String primaryKey =
- toPrimaryKey(
- PrimeMeridian.class,
- code,
- "[Prime Meridian]",
- "PRIME_MERIDIAN_CODE",
- "PRIME_MERIDIAN_NAME");
- final PreparedStatement stmt =
- prepareStatement(
- "PrimeMeridian",
- "SELECT PRIME_MERIDIAN_CODE,"
- + " PRIME_MERIDIAN_NAME,"
- + " GREENWICH_LONGITUDE,"
- + " UOM_CODE,"
- + " REMARKS"
- + " FROM [Prime Meridian]"
- + " WHERE PRIME_MERIDIAN_CODE = ?");
- stmt.setString(1, primaryKey);
- try (ResultSet result = stmt.executeQuery()) {
- while (result.next()) {
- final String epsg = getString(result, 1, code);
- final String name = getString(result, 2, code);
- final double longitude = getDouble(result, 3, code);
- final String unit_code = getString(result, 4, code);
- final String remarks = result.getString(5);
- @SuppressWarnings("unchecked")
- final Unit unit =
- (Unit) createUnit(unit_code);
- final Map properties = generateProperties(name, epsg, remarks);
- PrimeMeridian primeMeridian =
- factories
- .getDatumFactory()
- .createPrimeMeridian(properties, 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;
- }
-
- /**
- * Returns an area of use.
- *
- * @param code Value allocated by authority.
- * @return The area of use.
- * @throws NoSuchAuthorityCodeException if this method can't find the requested code.
- * @throws FactoryException if some other kind of failure occured in the backing store. This
- * exception usually have {@link SQLException} as its cause.
- */
- public synchronized Extent generateExtent(final String code) throws FactoryException {
- ensureNonNull("code", code);
- Extent returnValue = null;
- try {
- final String primaryKey =
- toPrimaryKey(Extent.class, code, "[Area]", "AREA_CODE", "AREA_NAME");
- final PreparedStatement stmt =
- prepareStatement(
- "Area",
- "SELECT AREA_OF_USE,"
- + " AREA_SOUTH_BOUND_LAT,"
- + " AREA_NORTH_BOUND_LAT,"
- + " AREA_WEST_BOUND_LON,"
- + " AREA_EAST_BOUND_LON"
- + " FROM [Area]"
- + " WHERE AREA_CODE = ?");
- stmt.setString(1, primaryKey);
- try (ResultSet result = stmt.executeQuery()) {
- while (result.next()) {
- ExtentImpl extent = null;
- final String description = result.getString(1);
- if (description != null) {
- extent = new ExtentImpl();
- extent.setDescription(new SimpleInternationalString(description));
- }
- final double ymin = result.getDouble(2);
- if (!result.wasNull()) {
- final double ymax = result.getDouble(3);
- if (!result.wasNull()) {
- final double xmin = result.getDouble(4);
- if (!result.wasNull()) {
- final double xmax = result.getDouble(5);
- if (!result.wasNull()) {
- if (extent == null) {
- extent = new ExtentImpl();
- }
- extent.setGeographicElements(
- Collections.singleton(
- new GeographicBoundingBoxImpl(
- xmin, xmax, ymin, ymax)));
- }
- }
- }
- }
- if (extent != null) {
- returnValue =
- (Extent) ensureSingleton(extent.unmodifiable(), returnValue, code);
- }
- }
- }
- } catch (SQLException exception) {
- throw databaseFailure(Extent.class, code, exception);
- }
- if (returnValue == null) {
- throw noSuchAuthorityCode(Extent.class, code);
- }
- return returnValue;
- }
-
- /**
- * Returns Bursa-Wolf parameters for a geodetic datum. If the specified datum has no conversion
- * informations, then this method will returns {@code null}.
- *
- * @param code The EPSG code of the {@link GeodeticDatum}.
- * @param toClose The result set to close if this method is going to invokes {@link
- * #createDatum} recursively. This hack is necessary because many JDBC drivers do not
- * support multiple result sets for the same statement. The result set is closed if an only
- * if this method returns a non-null value.
- * @return an array of Bursa-Wolf parameters (in which case {@code toClose} has been closed), or
- * {@code null} (in which case {@code toClose} has not been closed).
- */
- private BursaWolfParameters[] generateBursaWolfParameters(
- final String code, final ResultSet toClose) throws SQLException, FactoryException {
- if (safetyGuard.contains(code)) {
- /*
- * Do not try to create Bursa-Wolf parameters if the datum is already
- * in process of being created. This check avoid never-ending loops in
- * recursive call to 'createDatum'.
- */
- return null;
- }
- PreparedStatement stmt =
- prepareStatement(
- "BursaWolfParametersSet",
- "SELECT CO.COORD_OP_CODE,"
- + " CO.COORD_OP_METHOD_CODE,"
- + " CRS2.DATUM_CODE"
- + " FROM [Coordinate_Operation] AS CO"
- + " INNER JOIN [Coordinate Reference System] AS CRS2"
- + " ON CO.TARGET_CRS_CODE = CRS2.COORD_REF_SYS_CODE"
- + " WHERE CO.COORD_OP_METHOD_CODE >= "
- + BURSA_WOLF_MIN_CODE
- + " AND CO.COORD_OP_METHOD_CODE <= "
- + BURSA_WOLF_MAX_CODE
- + " AND CO.COORD_OP_CODE <> "
- + DUMMY_OPERATION // GEOT-1008
- + " AND CO.SOURCE_CRS_CODE IN ("
- + " SELECT CRS1.COORD_REF_SYS_CODE " // GEOT-1129
- + " FROM [Coordinate Reference System] AS CRS1 "
- + " WHERE CRS1.DATUM_CODE = ?)"
- + " ORDER BY CRS2.DATUM_CODE,"
- + " ABS(CO.DEPRECATED), CO.COORD_OP_ACCURACY,"
- + " CO.COORD_OP_CODE DESC"); // GEOT-846 fix
- stmt.setString(1, code);
- List