You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sis.apache.org by de...@apache.org on 2015/12/19 18:09:32 UTC
svn commit: r1720947 - in /sis/branches/JDK8/core:
sis-referencing/src/main/java/org/apache/sis/referencing/factory/
sis-referencing/src/main/java/org/apache/sis/referencing/factory/sql/
sis-utility/src/main/java/org/apache/sis/util/resources/
Author: desruisseaux
Date: Sat Dec 19 17:09:32 2015
New Revision: 1720947
URL: http://svn.apache.org/viewvc?rev=1720947&view=rev
Log:
Port of EPSGFactory.createFromCoordinateReferenceSystemCodes(String, String).
Added:
sis/branches/JDK8/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/IdentifiedObjectSet.java (with props)
sis/branches/JDK8/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/sql/CoordinateOperationSet.java (with props)
Modified:
sis/branches/JDK8/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/sql/EPSGFactory.java
sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.java
sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.properties
sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors_fr.properties
Added: sis/branches/JDK8/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/IdentifiedObjectSet.java
URL: http://svn.apache.org/viewvc/sis/branches/JDK8/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/IdentifiedObjectSet.java?rev=1720947&view=auto
==============================================================================
--- sis/branches/JDK8/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/IdentifiedObjectSet.java (added)
+++ sis/branches/JDK8/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/IdentifiedObjectSet.java [UTF-8] Sat Dec 19 17:09:32 2015
@@ -0,0 +1,534 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.referencing.factory;
+
+import java.util.Set;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Collection;
+import java.util.AbstractSet;
+import java.util.LinkedHashMap;
+import java.util.NoSuchElementException;
+import java.util.Locale;
+import java.util.logging.Level;
+import java.util.logging.LogRecord;
+import org.opengis.util.FactoryException;
+import org.opengis.util.NoSuchIdentifierException;
+import org.opengis.metadata.Identifier;
+import org.opengis.referencing.AuthorityFactory;
+import org.opengis.referencing.IdentifiedObject;
+import org.opengis.referencing.NoSuchAuthorityCodeException;
+import org.apache.sis.referencing.IdentifiedObjects;
+import org.apache.sis.internal.system.Loggers;
+import org.apache.sis.util.logging.Logging;
+import org.apache.sis.util.resources.Errors;
+import org.apache.sis.util.collection.BackingStoreException;
+import org.apache.sis.util.collection.CheckedContainer;
+import org.apache.sis.util.ArgumentChecks;
+
+// Branch-dependent imports
+import java.util.Objects;
+
+
+/**
+ * A lazy set of {@code IdentifiedObject} instances created from their authority codes only when first needed.
+ * This set delegates {@link IdentifiedObject} creation to the most appropriate {@code createFoo(String)} method
+ * of the {@link AuthorityFactory} given at construction time.
+ *
+ * <p>Elements can be added to this collection with calls to {@link #addAuthorityCode(String)} for deferred
+ * {@linkplain #createObject(String) object creation}, or to {@link #add(IdentifiedObject)} for objects
+ * that are already instantiated. This collection can not contain two {@code IdentifiedObject} instances
+ * having the same identifier. However the identifiers used by this class can be controlled by overriding
+ * {@link #getAuthorityCode(IdentifiedObject)}.</p>
+ *
+ * <p>Iterations over elements in this collection preserve insertion order.</p>
+ *
+ * <div class="section">Purpose</div>
+ * {@code IdentifiedObjectSet} can be used as the set returned by implementations of the
+ * {@link GeodeticAuthorityFactory#createFromCoordinateReferenceSystemCodes(String, String)} method.
+ * Deferred creation can have great performance impact since some set may contain as much as 40 entries
+ * (e.g. transformations from <cite>"ED50"</cite> (EPSG::4230) to <cite>"WGS 84"</cite> (EPSG::4326))
+ * while some users only want to look for the first entry.
+ *
+ * <div class="section">Exception handling</div>
+ * If the underlying factory failed to creates an object because of an unsupported operation method
+ * ({@link NoSuchIdentifierException}), the exception is logged at {@link Level#WARNING} and the iteration continue.
+ * If the operation creation failed for any other kind of reason ({@link FactoryException}), then the exception is
+ * re-thrown as an unchecked {@link BackingStoreException}. This default behavior can be changed by overriding
+ * the {@link #isRecoverableFailure(FactoryException)} method.
+ *
+ * <div class="section">Thread safety</div>
+ * This class is thread-safe for allowing caching by {@link ConcurrentAuthorityFactory}. However, implementors
+ * are encouraged to wrap in {@linkplain java.util.Collections#unmodifiableSet unmodifiable set} if they intend
+ * to cache {@code IdentifiedObjectSet} instances.
+ *
+ * @param <T> The type of objects to be included in this set.
+ *
+ * @author Martin Desruisseaux (IRD, Geomatys)
+ * @since 0.7
+ * @version 0.7
+ * @module
+ */
+public class IdentifiedObjectSet<T extends IdentifiedObject> extends AbstractSet<T> implements CheckedContainer<T> {
+ /**
+ * The map of object codes (keys), and the actual identified objects (values) when they have been created.
+ * Each entry has a null value until the corresponding object is created.
+ *
+ * <p><b>Note:</b> using {@code ConcurrentHahMap} would be more efficient.
+ * But the later does not support null values and does not preserve insertion order.</p>
+ */
+ final Map<String,T> objects = new LinkedHashMap<>();
+
+ /**
+ * The {@link #objects} keys, created for iteration purpose when first needed and cleared when the map is modified.
+ * We need to use such array as a snapshot of the map state at the time the iterator was created because the map
+ * may be modified during iteration or by concurrent threads.
+ */
+ private transient String[] codes;
+
+ /**
+ * The factory to use for creating {@code IdentifiedObject}s when first needed.
+ * This is the authority factory given at construction time.
+ */
+ protected final AuthorityFactory factory;
+
+ /**
+ * A proxy to the most specific {@linkplain #factory} method to invoke
+ * for the {@linkplain #type} of objects included in this set.
+ */
+ private final AuthorityFactoryProxy<? super T> proxy;
+
+ /**
+ * The type of objects included in this set.
+ *
+ * @see #getElementType()
+ */
+ private final Class<T> type;
+
+ /**
+ * Creates an initially empty set. The set can be populated after construction by calls
+ * to {@link #addAuthorityCode(String)} for deferred {@code IdentifiedObject} creation,
+ * or to {@link #add(IdentifiedObject)} for already instantiated objects.
+ *
+ * @param factory The factory to use for deferred {@code IdentifiedObject} instances creation.
+ * @param type The type of objects included in this set.
+ */
+ public IdentifiedObjectSet(final AuthorityFactory factory, final Class<T> type) {
+ ArgumentChecks.ensureNonNull("factory", factory);
+ ArgumentChecks.ensureNonNull("type", type);
+ proxy = AuthorityFactoryProxy.getInstance(type);
+ this.factory = factory;
+ this.type = type;
+ }
+
+ /**
+ * Returns the type of {@code IdentifiedObject} included in this set.
+ *
+ * @return The type of {@code IdentifiedObject} included in this set.
+ */
+ @Override
+ public Class<T> getElementType() {
+ return type;
+ }
+
+ /**
+ * Removes all of the elements from this collection.
+ */
+ @Override
+ public void clear() {
+ synchronized (objects) {
+ codes = null;
+ objects.clear();
+ }
+ }
+
+ /**
+ * Returns the number of objects available in this set. Note that this number may decrease
+ * during the iteration process if the creation of some {@code IdentifiedObject}s failed.
+ *
+ * @return The number of objects available in this set.
+ */
+ @Override
+ public int size() {
+ synchronized (objects) {
+ return objects.size();
+ }
+ }
+
+ /**
+ * Returns the authority codes of all {@code IdentifiedObject}s contained in this collection, in insertion order.
+ * This method does not trig the {@linkplain #createObject(String) creation} of any object.
+ *
+ * @return The authority codes in iteration order.
+ */
+ public String[] getAuthorityCodes() {
+ synchronized (objects) {
+ if (codes == null) {
+ final Set<String> keys = objects.keySet();
+ codes = keys.toArray(new String[keys.size()]);
+ }
+ return codes.clone();
+ }
+ }
+
+ /**
+ * Sets the content of this collection to the object identified by the given codes.
+ * For any code in the given sequence, this method will preserve the corresponding {@code IdentifiedObject}
+ * instance if it was already created. Otherwise objects will be {@linkplain #createObject(String) created}
+ * only when first needed.
+ *
+ * <div class="note"><b>Purpose:</b>
+ * this method is typically used together with {@link #getAuthorityCodes()} for altering the iteration order
+ * on the basis of authority codes. If the specified {@code codes} sequence contains the same elements than
+ * the ones in the array returned by {@link #getAuthorityCodes()} but in a different order, then this method
+ * just sets the new ordering.</div>
+ *
+ * @param codes The authority codes of identified objects to store in this set.
+ *
+ * @see #addAuthorityCode(String)
+ */
+ public void setAuthorityCodes(final String... codes) {
+ synchronized (objects) {
+ this.codes = null;
+ final Map<String,T> copy = new HashMap<>(objects);
+ objects.clear();
+ for (final String code : codes) {
+ objects.put(code, copy.get(code));
+ }
+ }
+ }
+
+ /**
+ * Ensures that this collection contains an object for the specified authority code.
+ * If this collection does not contain any element for the given code, then this method
+ * will instantiate an {@code IdentifiedObject} for the given code only when first needed.
+ * Otherwise this collection is unchanged.
+ *
+ * @param code The code authority code of the {@code IdentifiedObject} to include in this set.
+ */
+ public void addAuthorityCode(final String code) {
+ synchronized (objects) {
+ if (objects.putIfAbsent(code, null) == null) {
+ codes = null;
+ }
+ }
+ }
+
+ /**
+ * Ensures that this collection contains the specified object. This collection does not allow
+ * multiple objects for the same {@linkplain #getAuthorityCode(IdentifiedObject) authority code}.
+ * If this collection already contains an object using the same authority code than the given object,
+ * then the old object is replaced by the new one regardless of whether the objects themselves are equal or not.
+ *
+ * @param object The object to add to the set.
+ * @return {@code true} if this set changed as a result of this call.
+ *
+ * @see #getAuthorityCode(IdentifiedObject)
+ */
+ @Override
+ public boolean add(final T object) {
+ final String code = getAuthorityCode(object);
+ final T previous;
+ synchronized (objects) {
+ codes = null;
+ previous = objects.put(code, object);
+ }
+ return !Objects.equals(previous, object);
+ }
+
+ /**
+ * Returns the identified object for the specified value, creating it if needed.
+ *
+ * @throws BackingStoreException if the object creation failed.
+ *
+ * @see #createObject(String)
+ */
+ final T get(final String code) throws BackingStoreException {
+ T object;
+ boolean success;
+ synchronized (objects) {
+ object = objects.get(code);
+ success = (object != null || !objects.containsKey(code));
+ }
+ /*
+ * If we need to create the object, it should be done outside synchronized block.
+ * There is a risk that the same object is created twice in concurrent threads.
+ * If this happen, we will discard the duplicated value.
+ */
+ if (!success) {
+ try {
+ object = createObject(code);
+ success = true; // Shall be set only after above line succeed.
+ } catch (FactoryException exception) {
+ if (!isRecoverableFailure(exception)) {
+ throw new BackingStoreException(exception);
+ }
+ LogRecord record = Errors.getResources((Locale) null).getLogRecord(
+ Level.WARNING, Errors.Keys.CanNotInstantiateForIdentifier_2, type, code);
+ record.setThrown(exception);
+ record.setLoggerName(Loggers.CRS_FACTORY);
+ Logging.log(IdentifiedObjectSet.class, "createObject", record);
+ }
+ synchronized (objects) {
+ if (success) {
+ /*
+ * The check for 'containsKey' is a paranoiac check in case the element has been removed
+ * in another thread while we were creating the object. This is likely to be unnecessary
+ * in the vast majority of cases where the set of codes is never modified after this set
+ * has been published. However, if someone decided to do such concurrent modifications,
+ * not checking for concurrent removal could be a subtle and hard-to-find bug, so we are
+ * better to be safe. Note that if a concurrent removal happened, we still return the non-null
+ * object but we do not put it in this IdentifiedObjectSet. This behavior is as if this method
+ * has been invoked before the concurrent removal happened.
+ */
+ if (objects.containsKey(code)) {
+ final T c = objects.putIfAbsent(code, object);
+ if (c != null) {
+ object = c; // The object has been created concurrently.
+ } else {
+ codes = null;
+ }
+ }
+ } else if (objects.remove(code, null)) { // Do not remove if a concurrent thread succeeded.
+ codes = null;
+ }
+ }
+ }
+ return object;
+ }
+
+ /**
+ * Returns {@code true} if this collection contains the specified {@code IdentifiedObject}.
+ *
+ * @param object The {@code IdentifiedObject} to test for presence in this set.
+ * @return {@code true} if the given object is presents in this set.
+ */
+ @Override
+ public boolean contains(final Object object) {
+ return (object != null) && object.equals(get(getAuthorityCode(type.cast(object))));
+ }
+
+ /**
+ * Removes the object for the given code.
+ *
+ * @param code The code of the object to remove.
+ */
+ final void removeAuthorityCode(final String code) {
+ synchronized (objects) {
+ objects.remove(code);
+ codes = null;
+ }
+ }
+
+ /**
+ * Removes the specified {@code IdentifiedObject} from this collection, if it is present.
+ *
+ * @param object The {@code IdentifiedObject} to remove from this set.
+ * @return {@code true} if this set changed as a result of this call.
+ */
+ @Override
+ public boolean remove(final Object object) {
+ if (object != null) {
+ final String code = getAuthorityCode(type.cast(object));
+ final T current = get(code);
+ if (object.equals(current)) {
+ synchronized (objects) {
+ objects.remove(code);
+ codes = null;
+ }
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Removes from this collection all of its elements that are contained in the specified collection.
+ *
+ * @param collection The {@code IdentifiedObject}s to remove from this set.
+ * @return {@code true} if this set changed as a result of this call.
+ */
+ @Override
+ public boolean removeAll(final Collection<?> collection) {
+ boolean modified = false;
+ for (final Object object : collection) {
+ modified |= remove(object);
+ }
+ return modified;
+ }
+
+ /**
+ * Returns an iterator over the objects in this set. If the iteration encounter any kind of
+ * {@link FactoryException} other than {@link NoSuchIdentifierException}, then the exception
+ * will be re-thrown as an unchecked {@link BackingStoreException}.
+ *
+ * @return An iterator over all {@code IdentifiedObject} instances in this set, in insertion order.
+ * @throws BackingStoreException if an error occurred while creating the iterator.
+ */
+ @Override
+ public Iterator<T> iterator() throws BackingStoreException {
+ return new Iterator<T>() {
+ /**
+ * The keys from the underlying map, as a snapshot taken at the time the iterator has been created.
+ * We need to take a snapshot because the underlying {@link IdentifiedObjectSet#objects} map may be
+ * modified concurrently in other threads.
+ */
+ private final String[] keys = getAuthorityCodes();
+
+ /**
+ * Index of the next element to obtain by a call to {@link IdentifiedObjectSet#get(String)}.
+ */
+ private int index;
+
+ /**
+ * The next element to return, or {@code null} if not yet determined.
+ */
+ private T next;
+
+ /**
+ * {@code true} if {@link #remove()} can remove the element identified by {@code keys[index - 1]}.
+ */
+ private boolean canRemove;
+
+ /**
+ * Returns {@code true} if there is more elements.
+ *
+ * @throws BackingStoreException if the underlying factory failed to creates the {@code IdentifiedObject}.
+ */
+ @Override
+ public boolean hasNext() throws BackingStoreException {
+ while (next == null) {
+ if (index >= keys.length) {
+ return false;
+ }
+ next = get(keys[index++]);
+ }
+ return true;
+ }
+
+ /**
+ * Returns the next element.
+ *
+ * @throws NoSuchElementException if there is no more {@code IdentifiedObject} to iterate.
+ */
+ @Override
+ public T next() throws NoSuchElementException {
+ if (canRemove = hasNext()) {
+ final T e = next;
+ next = null;
+ return e;
+ }
+ throw new NoSuchElementException();
+ }
+
+ /**
+ * Removes the previous element from the underlying set.
+ */
+ @Override
+ public void remove() {
+ if (!canRemove) {
+ throw new IllegalStateException();
+ }
+ removeAuthorityCode(keys[index - 1]);
+ canRemove = false;
+ }
+ };
+ }
+
+ /**
+ * Ensures that the <var>n</var> first objects in this set are created. This method can be invoked for
+ * making sure that the underlying {@linkplain #factory} is really capable to create at least one object.
+ * {@link FactoryException} (except the ones accepted as {@linkplain #isRecoverableFailure recoverable failures})
+ * are thrown as if they were never wrapped into {@link BackingStoreException}.
+ *
+ * @param n The number of object to resolve. If this number is equals or greater than {@link #size()}, then
+ * this method ensures that all {@code IdentifiedObject} instances in this collection are created.
+ * @throws FactoryException if an {@linkplain #createObject(String) object creation} failed.
+ */
+ public void resolve(int n) throws FactoryException {
+ if (n > 0) try {
+ for (final Iterator<T> it=iterator(); it.hasNext(); it.next()) {
+ if (--n == 0) {
+ break;
+ }
+ }
+ } catch (BackingStoreException exception) {
+ throw exception.unwrapOrRethrow(FactoryException.class);
+ }
+ }
+
+ /**
+ * Returns the identifier for the specified object.
+ * The default implementation takes the first of the following identifier which is found:
+ *
+ * <ol>
+ * <li>An identifier allocated by the authority given by
+ * <code>{@linkplain #factory}.{@linkplain GeodeticAuthorityFactory#getAuthority() getAuthority()}</code>.</li>
+ * <li>The first {@linkplain org.apache.sis.referencing.AbstractIdentifiedObject#getIdentifiers() object identifier},
+ * regardless its authority.</li>
+ * <li>The first {@linkplain org.apache.sis.referencing.AbstractIdentifiedObject#getName() object name},
+ * regardless its authority.</li>
+ * </ol>
+ *
+ * Subclasses may override this method if they want to use a different identifiers.
+ *
+ * @param object The object for which to get the authority code.
+ * @return The authority code of the given identified object.
+ */
+ protected String getAuthorityCode(final T object) {
+ final Identifier id = IdentifiedObjects.getIdentifier(object, factory.getAuthority());
+ return (id != null) ? id.getCode() : IdentifiedObjects.getIdentifierOrName(object);
+ }
+
+ /**
+ * Creates an object for the specified authority code.
+ * This method is invoked during the iteration process if an object was not already created.
+ *
+ * @param code The code for which to create the identified object.
+ * @return The identified object created from the given code.
+ * @throws FactoryException If the object creation failed.
+ */
+ protected T createObject(final String code) throws FactoryException {
+ return type.cast(proxy.createFromAPI(factory, code));
+ }
+
+ /**
+ * Returns {@code true} if the specified exception should be handled as a recoverable failure.
+ * This method is invoked during the iteration process if the factory failed to create some objects.
+ * If this method returns {@code true} for the given exception, then the exception will be logged
+ * at {@link Level#WARNING}. If this method returns {@code false}, then the exception will be re-thrown
+ * as a {@link BackingStoreException}.
+ *
+ * <p>The default implementation returns applies the following rules:</p>
+ * <ul>
+ * <li>If {@link NoSuchAuthorityCodeException}, returns {@code false} since failure to find a code declared
+ * in the collection would be an inconsistency. Note that this exception is a subtype of
+ * {@code NoSuchIdentifierException}, so it must be tested before the last case below.</li>
+ * <li>If {@link NoSuchIdentifierException}, returns {@code true} since this exception is caused by an attempt to
+ * {@linkplain org.opengis.referencing.operation.MathTransformFactory#createParameterizedTransform
+ * create a parameterized transform} for an unimplemented operation.</li>
+ * </ul>
+ *
+ * @param exception The exception that occurred while creating an object.
+ * @return {@code true} if the given exception should be considered recoverable,
+ * or {@code false} if it should be considered fatal.
+ */
+ protected boolean isRecoverableFailure(final FactoryException exception) {
+ return (exception instanceof NoSuchIdentifierException) && !(exception instanceof NoSuchAuthorityCodeException);
+ }
+}
Propchange: sis/branches/JDK8/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/IdentifiedObjectSet.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: sis/branches/JDK8/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/IdentifiedObjectSet.java
------------------------------------------------------------------------------
svn:mime-type = text/plain;charset=UTF-8
Added: sis/branches/JDK8/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/sql/CoordinateOperationSet.java
URL: http://svn.apache.org/viewvc/sis/branches/JDK8/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/sql/CoordinateOperationSet.java?rev=1720947&view=auto
==============================================================================
--- sis/branches/JDK8/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/sql/CoordinateOperationSet.java (added)
+++ sis/branches/JDK8/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/sql/CoordinateOperationSet.java [UTF-8] Sat Dec 19 17:09:32 2015
@@ -0,0 +1,90 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.referencing.factory.sql;
+
+import java.util.Map;
+import java.util.HashMap;
+import org.opengis.metadata.Identifier;
+import org.opengis.util.FactoryException;
+import org.opengis.referencing.AuthorityFactory;
+import org.opengis.referencing.crs.CRSAuthorityFactory;
+import org.opengis.referencing.operation.CoordinateOperation;
+import org.opengis.referencing.operation.CoordinateOperationAuthorityFactory;
+import org.apache.sis.metadata.iso.citation.Citations;
+import org.apache.sis.referencing.IdentifiedObjects;
+import org.apache.sis.referencing.factory.IdentifiedObjectSet;
+
+
+/**
+ * A lazy set of {@link CoordinateOperation} objects to be returned by the
+ * {@link EPSGFactory#createFromCoordinateReferenceSystemCodes(String, String)} method.
+ *
+ * @author Martin Desruisseaux (IRD)
+ * @since 0.7
+ * @version 0.7
+ * @module
+ */
+final class CoordinateOperationSet extends IdentifiedObjectSet<CoordinateOperation> {
+ /**
+ * The codes of {@link ProjectedCRS} objects for the specified {@link Conversion} codes.
+ */
+ private final Map<String,String> projections;
+
+ /**
+ * Creates a new instance of this lazy set.
+ */
+ CoordinateOperationSet(final AuthorityFactory factory) {
+ super(factory, CoordinateOperation.class);
+ projections = new HashMap<>();
+ }
+
+ /**
+ * Adds the specified authority code.
+ *
+ * @param code The code for the {@link CoordinateOperation} to add.
+ * @param crs The code for the CRS to create instead of the operation, or {@code null} if none.
+ */
+ final void addAuthorityCode(final String code, final String crs) {
+ if (crs != null) {
+ projections.put(code, crs);
+ }
+ addAuthorityCode(code);
+ }
+
+ /**
+ * Same as the default implementation in parent class,
+ * but avoid to call the costly {@link EPSGFactory#getAuthority()} method.
+ */
+ @Override
+ protected String getAuthorityCode(final CoordinateOperation object) {
+ final Identifier id = IdentifiedObjects.getIdentifier(object, Citations.EPSG);
+ return (id != null) ? id.getCode() : IdentifiedObjects.getIdentifierOrName(object);
+ }
+
+ /**
+ * Creates an object for the specified code.
+ */
+ @Override
+ protected CoordinateOperation createObject(final String code) throws FactoryException {
+ final String crs = projections.get(code);
+ if (crs != null) {
+ return ((CRSAuthorityFactory) factory).createProjectedCRS(crs).getConversionFromBase();
+ } else {
+ return ((CoordinateOperationAuthorityFactory) factory).createCoordinateOperation(code);
+ }
+ }
+}
Propchange: sis/branches/JDK8/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/sql/CoordinateOperationSet.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: sis/branches/JDK8/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/sql/CoordinateOperationSet.java
------------------------------------------------------------------------------
svn:mime-type = text/plain;charset=UTF-8
Modified: sis/branches/JDK8/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/sql/EPSGFactory.java
URL: http://svn.apache.org/viewvc/sis/branches/JDK8/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/sql/EPSGFactory.java?rev=1720947&r1=1720946&r2=1720947&view=diff
==============================================================================
--- sis/branches/JDK8/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/sql/EPSGFactory.java [UTF-8] (original)
+++ sis/branches/JDK8/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/sql/EPSGFactory.java [UTF-8] Sat Dec 19 17:09:32 2015
@@ -259,16 +259,18 @@ public abstract class EPSGFactory extend
private final Map<String,Object> properties = new HashMap<>();
/**
- * A safety guard for preventing never-ending loops in recursive calls to {@link #createDatum(String)}.
- * This is used by {@link #createBursaWolfParameters(Integer)}, which need to create a target datum.
+ * A safety guard for preventing never-ending loops in recursive calls to some {@code createFoo(String)} methods.
+ * Recursivity may happen while creating Bursa-Wolf parameters, projected CRS if the database has erroneous data,
+ * compound CRS if there is cycles, or coordinate operations.
+ *
+ * <div class="note"><b>Example:</b>
+ * {@link #createDatum(String)} invokes {@link #createBursaWolfParameters(Integer)}, which creates a target datum.
* The target datum could have its own Bursa-Wolf parameters, with one of them pointing again to the source datum.
+ * </div>
+ *
+ * Keys are EPSG codes and values are the type of object being constructed (but those values are not yet used).
*/
- private boolean isCreatingBWP;
-
- /**
- * A safety guard for preventing never-ending loops in recursive calls to {@link #createCoordinateSystem(String)}.
- */
- private boolean isCreatingGeographicCRS, isCreatingProjectedCRS, isCreatingCompoundCRS;
+ private final Map<Integer,Class<?>> safetyGuard = new HashMap<>();
/**
* The {@link ConcurrentAuthorityFactory} that supply caching for all {@code createFoo(String)} methods,
@@ -993,6 +995,34 @@ addURIs: for (int i=0; ; i++) {
}
/**
+ * Ensures that this factory is not already building an object of the given code.
+ * This method shall be followed by a {@code try ... finally} block like below:
+ *
+ * {@preformat java
+ * ensureNoCycle(type, code);
+ * try {
+ * ...
+ * } finally {
+ * endOfRecursive(type, code);
+ * }
+ * }
+ */
+ private void ensureNoCycle(final Class<?> type, final Integer code) throws FactoryException {
+ if (safetyGuard.putIfAbsent(code, type) != null) {
+ throw new FactoryException(error().getString(Errors.Keys.RecursiveCreateCallForCode_2, type, code));
+ }
+ }
+
+ /**
+ * Invoked after the block protected against infinite recursivity.
+ */
+ private void endOfRecursivity(final Class<?> type, final Integer code) throws FactoryException {
+ if (safetyGuard.remove(code) != type) {
+ throw new FactoryException(String.valueOf(code)); // Would be an EPSGFactory bug if it happen.
+ }
+ }
+
+ /**
* Returns {@code true} if the given table {@code name} matches the {@code expected} name.
* The given {@code name} may be prefixed by {@code "epsg_"} and may contain abbreviations of the full name.
* For example {@code "epsg_coordoperation"} is considered as a match for {@code "Coordinate_Operation"}.
@@ -1362,16 +1392,15 @@ addURIs: for (int i=0; ; i++) {
final GeodeticDatum datum;
if (datumCode != null) {
datum = buffered.createGeodeticDatum(datumCode);
- } else if (isCreatingGeographicCRS) {
- throw recursiveCall(GeographicCRS.class, code);
- } else try {
- isCreatingGeographicCRS = true;
+ } else {
final String geoCode = getString(code, result, 10, 9);
- result.close(); // Must be close before call to createGeographicCRS(String)
- final GeographicCRS baseCRS = buffered.createGeographicCRS(geoCode);
- datum = baseCRS.getDatum();
- } finally {
- isCreatingGeographicCRS = false;
+ result.close(); // Must be closed before call to createGeographicCRS(String)
+ ensureNoCycle(GeographicCRS.class, epsg);
+ try {
+ datum = buffered.createGeographicCRS(geoCode).getDatum();
+ } finally {
+ endOfRecursivity(GeographicCRS.class, epsg);
+ }
}
crs = crsFactory.createGeographicCRS(createProperties("[Coordinate Reference System]",
name, epsg, area, scope, remarks, deprecated), datum, cs);
@@ -1387,11 +1416,9 @@ addURIs: for (int i=0; ; i++) {
final String csCode = getString(code, result, 8);
final String geoCode = getString(code, result, 10);
final String opCode = getString(code, result, 11);
- result.close(); // Must be close before call to createFoo(String)
- if (isCreatingProjectedCRS) {
- throw recursiveCall(ProjectedCRS.class, code);
- } else try {
- isCreatingProjectedCRS = true;
+ result.close(); // Must be closed before call to createFoo(String)
+ ensureNoCycle(ProjectedCRS.class, epsg);
+ try {
final CartesianCS cs = buffered.createCartesianCS(csCode);
final GeographicCRS baseCRS = buffered.createGeographicCRS(geoCode);
final CoordinateOperation op = buffered.createCoordinateOperation(opCode);
@@ -1402,7 +1429,7 @@ addURIs: for (int i=0; ; i++) {
throw noSuchAuthorityCode(Projection.class, opCode);
}
} finally {
- isCreatingProjectedCRS = false;
+ endOfRecursivity(ProjectedCRS.class, epsg);
}
break;
}
@@ -1441,14 +1468,12 @@ addURIs: for (int i=0; ; i++) {
final String code2 = getString(code, result, 13);
result.close();
final CoordinateReferenceSystem crs1, crs2;
- if (isCreatingCompoundCRS) {
- throw recursiveCall(CompoundCRS.class, code);
- } else try {
- isCreatingCompoundCRS = true;
+ ensureNoCycle(CompoundCRS.class, epsg);
+ try {
crs1 = buffered.createCoordinateReferenceSystem(code1);
crs2 = buffered.createCoordinateReferenceSystem(code2);
} finally {
- isCreatingCompoundCRS = false;
+ endOfRecursivity(CompoundCRS.class, epsg);
}
// Note: Do not invoke 'createProperties' sooner.
crs = crsFactory.createCompoundCRS(createProperties("[Coordinate Reference System]",
@@ -1658,16 +1683,12 @@ addURIs: for (int i=0; ; i++) {
private BursaWolfParameters[] createBursaWolfParameters(final Integer code) throws SQLException, FactoryException {
/*
* We do not provide TOWGS84 information for WGS84 itself or for any other datum on our list of target datum,
- * in order to avoid infinite recursivity. The 'isCreatingBWP' boolean is an extra safety check which should
+ * in order to avoid infinite recursivity. The 'ensureNonRecursive' call is an extra safety check which should
* never fail, unless TARGET_CRS and TARGET_DATUM values do not agree with database content.
*/
if (code == BursaWolfInfo.TARGET_DATUM) {
return null;
}
- if (isCreatingBWP) {
- throw recursiveCall(BursaWolfParameters.class, String.valueOf(code)); // See above comment.
- }
-
PreparedStatement stmt = prepareStatement("BursaWolfParametersSet",
"SELECT COORD_OP_CODE," +
" COORD_OP_METHOD_CODE," +
@@ -1728,11 +1749,11 @@ addURIs: for (int i=0; ; i++) {
for (int i=0; i<size; i++) {
final BursaWolfInfo info = bwInfos.get(i);
final GeodeticDatum datum;
+ ensureNoCycle(BursaWolfParameters.class, code); // See comment at the begining of this method.
try {
- isCreatingBWP = true;
datum = buffered.createGeodeticDatum(String.valueOf(info.target));
} finally {
- isCreatingBWP = false;
+ endOfRecursivity(BursaWolfParameters.class, code);
}
final BursaWolfParameters bwp = new BursaWolfParameters(datum, null);
stmt.setInt(1, info.operation);
@@ -2816,8 +2837,13 @@ addURIs: for (int i=0; ; i++) {
}
}
final CoordinateOperation[] operations = new CoordinateOperation[codes.size()];
- for (int i=0; i<operations.length; i++) {
- operations[i] = buffered.createCoordinateOperation(codes.get(i));
+ ensureNoCycle(CoordinateOperation.class, epsg);
+ try {
+ for (int i=0; i<operations.length; i++) {
+ operations[i] = buffered.createCoordinateOperation(codes.get(i));
+ }
+ } finally {
+ endOfRecursivity(CoordinateOperation.class, epsg);
}
return copFactory.createConcatenatedOperation(opProperties, operations);
} else {
@@ -2877,6 +2903,91 @@ addURIs: for (int i=0; ; i++) {
}
/**
+ * Creates operations from source and target coordinate reference system codes.
+ * This method only extract the information explicitely declared in the EPSG database;
+ * it does not attempt to infer by itself operations that are not explicitely recorded in the database.
+ *
+ * <p>The returned set is ordered with the most accurate operations first.</p>
+ *
+ * @param sourceCRS Coded value of source coordinate reference system.
+ * @param targetCRS Coded value of target coordinate reference system.
+ * @return The operations from {@code sourceCRS} to {@code targetCRS}.
+ * @throws NoSuchAuthorityCodeException if a specified code was not found.
+ * @throws FactoryException if the object creation failed for some other reason.
+ *
+ * @todo The ordering is not consistent among all database software, because the "accuracy" column may contain null
+ * values. When used in an "ORDER BY" clause, PostgreSQL put null values last, while Access and HSQL put them
+ * first. The PostgreSQL's behavior is better for what we want (put operations with unknown accuracy last).
+ */
+ @Override
+ public synchronized Set<CoordinateOperation> createFromCoordinateReferenceSystemCodes(
+ final String sourceCRS, final String targetCRS) throws FactoryException
+ {
+ ArgumentChecks.ensureNonNull("sourceCRS", sourceCRS);
+ ArgumentChecks.ensureNonNull("targetCRS", targetCRS);
+ final String pair = sourceCRS + " ⇨ " + targetCRS;
+ final CoordinateOperationSet set = new CoordinateOperationSet(buffered);
+ try {
+ final String sourceKey = toPrimaryKeyForCRS(sourceCRS);
+ final String targetKey = toPrimaryKeyForCRS(targetCRS);
+ boolean searchTransformations = false;
+ do {
+ /*
+ * This 'do' loop is executed twice: the first time for searching defining conversions, and the second
+ * time for searching all other kind of operations. Defining conversions are searched first because
+ * they are, by definition, the most accurate operations.
+ *
+ * TODO: Remove the "area" and "accuracy" ordering since they should be replaced by Java code
+ * (because we need to compute intersections while supporting anti-meridian spanning).
+ * Also need to resolve ordering problem (see method javadoc)
+ */
+ final String key, sql;
+ if (searchTransformations) {
+ key = "TransformationFromCRS";
+ sql = "SELECT COORD_OP_CODE" +
+ " FROM [Coordinate_Operation] AS CO" +
+ " JOIN [Area] ON AREA_OF_USE_CODE = AREA_CODE" +
+ " WHERE SOURCE_CRS_CODE = ?" +
+ " AND TARGET_CRS_CODE = ?" +
+ " ORDER BY ABS(CO.DEPRECATED), COORD_OP_ACCURACY, " +
+ " ABS((AREA_EAST_BOUND_LON - AREA_WEST_BOUND_LON) *" +
+ " (AREA_NORTH_BOUND_LAT - AREA_SOUTH_BOUND_LAT) * COS(0.5*RADIANS" +
+ "(AREA_NORTH_BOUND_LAT + AREA_SOUTH_BOUND_LAT))) DESC";
+ } else {
+ key = "ConversionFromCRS";
+ sql = "SELECT PROJECTION_CONV_CODE" +
+ " FROM [Coordinate Reference System]" +
+ " WHERE SOURCE_GEOGCRS_CODE = ?" +
+ " AND COORD_REF_SYS_CODE = ?";
+ }
+ final PreparedStatement stmt = prepareStatement(key, sql);
+ try (ResultSet result = executeQuery(stmt, sourceKey, targetKey)) {
+ while (result.next()) {
+ final String code = getString(pair, result, 1);
+ set.addAuthorityCode(code, searchTransformations ? null : targetKey);
+ }
+ }
+ } while ((searchTransformations = !searchTransformations) == true);
+ /*
+ * Search finished. We may have a lot of coordinate operations
+ * (e.g. about 40 for "ED50" (EPSG::4230) to "WGS 84" (EPSG::4326)).
+ * Alter the ordering using the information supplied in the supersession table.
+ */
+ final String[] codes = set.getAuthorityCodes();
+ sort(codes);
+ set.setAuthorityCodes(codes);
+ } catch (SQLException exception) {
+ throw databaseFailure(CoordinateOperation.class, pair, exception);
+ }
+ /*
+ * Before to return the set, tests the creation of 1 object in order to report early (i.e. now)
+ * any problems with SQL statements. Remaining operations will be created only when first needed.
+ */
+ set.resolve(1);
+ return set;
+ }
+
+ /**
* Returns {@code true} if the {@link CoordinateOperation} for the specified code is a {@link Projection}.
* The caller must have verified that the designed operation is a {@link Conversion} before to invoke this method.
*
@@ -3032,13 +3143,6 @@ addURIs: for (int i=0; ; i++) {
}
/**
- * Constructs an exception for recursive method calls.
- */
- private FactoryException recursiveCall(final Class<?> type, final String code) {
- return new FactoryException(error().getString(Errors.Keys.RecursiveCreateCallForCode_2, type, code));
- }
-
- /**
* Constructs an exception for a database failure.
*/
private FactoryException databaseFailure(Class<?> type, Comparable<?> code, SQLException cause) {
Modified: sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.java
URL: http://svn.apache.org/viewvc/sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.java?rev=1720947&r1=1720946&r2=1720947&view=diff
==============================================================================
--- sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.java [UTF-8] (original)
+++ sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.java [UTF-8] Sat Dec 19 17:09:32 2015
@@ -121,6 +121,11 @@ public final class Errors extends Indexe
public static final short CanNotConvertValue_2 = 4;
/**
+ * Can not instantiate the object of type ‘{0}’ identified by “{1}”.
+ */
+ public static final short CanNotInstantiateForIdentifier_2 = 215;
+
+ /**
* Can not instantiate an object of type ‘{0}’.
*/
public static final short CanNotInstantiate_1 = 5;
Modified: sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.properties
URL: http://svn.apache.org/viewvc/sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.properties?rev=1720947&r1=1720946&r2=1720947&view=diff
==============================================================================
--- sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.properties [ISO-8859-1] (original)
+++ sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.properties [ISO-8859-1] Sat Dec 19 17:09:32 2015
@@ -36,6 +36,7 @@ CanNotConvertValue_2 = Can
CanNotCompute_1 = Can not compute \u201c{0}\u201d.
CanNotComputeDerivative = Can not compute the derivative.
CanNotInstantiate_1 = Can not instantiate an object of type \u2018{0}\u2019.
+CanNotInstantiateForIdentifier_2 = Can not instantiate the object of type \u2018{0}\u2019 identified by \u201c{1}\u201d.
CanNotMapAxisToDirection_2 = Can not map an axis from \u201c{0}\u201d to direction \u201c{1}\u201d.
CanNotOpen_1 = Can not open \u201c{0}\u201d.
CanNotParseFile_2 = Can not parse \u201c{1}\u201d as a file in the {0} format.
Modified: sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors_fr.properties
URL: http://svn.apache.org/viewvc/sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors_fr.properties?rev=1720947&r1=1720946&r2=1720947&view=diff
==============================================================================
--- sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors_fr.properties [ISO-8859-1] (original)
+++ sis/branches/JDK8/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors_fr.properties [ISO-8859-1] Sat Dec 19 17:09:32 2015
@@ -33,6 +33,7 @@ CanNotConvertValue_2 = La v
CanNotCompute_1 = Ne peut pas calculer \u00ab\u202f{0}\u202f\u00bb.
CanNotComputeDerivative = La d\u00e9riv\u00e9 ne peut pas \u00eatre calcul\u00e9e.
CanNotInstantiate_1 = Ne peut pas cr\u00e9er un objet de type \u2018{0}\u2019.
+CanNotInstantiateForIdentifier_2 = Ne peut pas cr\u00e9er l\u2019objet de type \u2018{0}\u2019 identifi\u00e9 par \u00ab\u202f{1}\u202f\u00bb.
CanNotMapAxisToDirection_2 = Aucun axe de \u00ab\u202f{0}\u202f\u00bb n\u2019a pu \u00eatre associ\u00e9 \u00e0 la direction \u00ab\u202f{1}\u202f\u00bb.
CanNotOpen_1 = Ne peut pas ouvrir \u00ab\u202f{0}\u202f\u00bb.
CanNotParseFile_2 = Ne peut pas lire \u00ab\u202f{1}\u202f\u00bb comme un fichier au format {0}.