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 2013/08/08 12:50:58 UTC

svn commit: r1511687 - in /sis/trunk: ./ core/sis-build-helper/src/main/java/org/apache/sis/internal/maven/ core/sis-build-helper/src/site/apt/ core/sis-metadata/src/main/java/org/apache/sis/internal/jaxb/gml/ core/sis-metadata/src/main/java/org/apache...

Author: desruisseaux
Date: Thu Aug  8 10:50:57 2013
New Revision: 1511687

URL: http://svn.apache.org/r1511687
Log:
Merge from the JDK6 branch.

Added:
    sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/internal/storage/xml/
      - copied from r1511685, sis/branches/JDK6/storage/sis-storage/src/main/java/org/apache/sis/internal/storage/xml/
    sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/storage/InputStreamAdapter.java
      - copied unchanged from r1511685, sis/branches/JDK6/storage/sis-storage/src/main/java/org/apache/sis/storage/InputStreamAdapter.java
    sis/trunk/storage/sis-storage/src/main/resources/
      - copied from r1511685, sis/branches/JDK6/storage/sis-storage/src/main/resources/
    sis/trunk/storage/sis-storage/src/test/java/org/apache/sis/internal/storage/DripByteChannel.java
      - copied unchanged from r1511685, sis/branches/JDK6/storage/sis-storage/src/test/java/org/apache/sis/internal/storage/DripByteChannel.java
    sis/trunk/storage/sis-storage/src/test/java/org/apache/sis/internal/storage/xml/
      - copied from r1511685, sis/branches/JDK6/storage/sis-storage/src/test/java/org/apache/sis/internal/storage/xml/
Modified:
    sis/trunk/   (props changed)
    sis/trunk/core/sis-build-helper/src/main/java/org/apache/sis/internal/maven/BundleCreator.java
    sis/trunk/core/sis-build-helper/src/site/apt/index.apt
    sis/trunk/core/sis-metadata/src/main/java/org/apache/sis/internal/jaxb/gml/GMLAdapter.java
    sis/trunk/core/sis-metadata/src/main/java/org/apache/sis/metadata/iso/ISOMetadata.java
    sis/trunk/core/sis-utility/src/main/java/org/apache/sis/internal/jaxb/PrimitiveTypeProperties.java
    sis/trunk/core/sis-utility/src/main/java/org/apache/sis/internal/system/DefaultFactories.java
    sis/trunk/core/sis-utility/src/main/java/org/apache/sis/setup/OptionKey.java
    sis/trunk/core/sis-utility/src/main/java/org/apache/sis/util/Static.java
    sis/trunk/core/sis-utility/src/main/java/org/apache/sis/util/logging/WarningListeners.java
    sis/trunk/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.java
    sis/trunk/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.properties
    sis/trunk/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors_fr.properties
    sis/trunk/core/sis-utility/src/main/java/org/apache/sis/xml/MarshallerPool.java
    sis/trunk/core/sis-utility/src/main/java/org/apache/sis/xml/XML.java
    sis/trunk/storage/sis-netcdf/src/main/java/org/apache/sis/storage/netcdf/NetcdfStoreProvider.java
    sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/internal/storage/ChannelDataInput.java
    sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/storage/DataStoreProvider.java
    sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/storage/DataStoreRegistry.java
    sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/storage/DataStores.java
    sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/storage/ProbeResult.java
    sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/storage/StorageConnector.java
    sis/trunk/storage/sis-storage/src/test/java/org/apache/sis/internal/storage/ChannelDataInputTest.java
    sis/trunk/storage/sis-storage/src/test/java/org/apache/sis/storage/StorageConnectorTest.java
    sis/trunk/storage/sis-storage/src/test/java/org/apache/sis/test/suite/StorageTestSuite.java

Propchange: sis/trunk/
------------------------------------------------------------------------------
  Merged /sis/branches/JDK7:r1510379-1511646
  Merged /sis/branches/JDK6:r1510392-1511685

Modified: sis/trunk/core/sis-build-helper/src/main/java/org/apache/sis/internal/maven/BundleCreator.java
URL: http://svn.apache.org/viewvc/sis/trunk/core/sis-build-helper/src/main/java/org/apache/sis/internal/maven/BundleCreator.java?rev=1511687&r1=1511686&r2=1511687&view=diff
==============================================================================
--- sis/trunk/core/sis-build-helper/src/main/java/org/apache/sis/internal/maven/BundleCreator.java [UTF-8] (original)
+++ sis/trunk/core/sis-build-helper/src/main/java/org/apache/sis/internal/maven/BundleCreator.java [UTF-8] Thu Aug  8 10:50:57 2013
@@ -27,7 +27,7 @@ import org.apache.maven.plugin.MojoExecu
  * This mojo delegates the work to <code>Packer</code>, which can be invoked from the command
  * line without Maven. Maven invocation syntax is:
  *
- * <blockquote><code>mvn org.apache.sis:sis-build-helper:pack --non-recursive</code></blockquote>
+ * <blockquote><code>mvn org.apache.sis.core:sis-build-helper:pack --non-recursive</code></blockquote>
  *
  * Do not forget the <code>--non-recursive</code> option, otherwise the Mojo will be executed many time.
  *

Modified: sis/trunk/core/sis-build-helper/src/site/apt/index.apt
URL: http://svn.apache.org/viewvc/sis/trunk/core/sis-build-helper/src/site/apt/index.apt?rev=1511687&r1=1511686&r2=1511687&view=diff
==============================================================================
--- sis/trunk/core/sis-build-helper/src/site/apt/index.apt [UTF-8] (original)
+++ sis/trunk/core/sis-build-helper/src/site/apt/index.apt [UTF-8] Thu Aug  8 10:50:57 2013
@@ -105,9 +105,9 @@ Building Apache SIS
   in the module containing the resources to recompile. This is sometime useful for regenerating
   the constants in the <<<Keys>>> inner class in a feaster way than building the project.
 
------------------------------------------------------------
-   mvn org.apache.sis:sis-build-helper:compile-resources
------------------------------------------------------------
+----------------------------------------------------------------
+   mvn org.apache.sis.core:sis-build-helper:compile-resources
+----------------------------------------------------------------
 
 
 * JAR files collector
@@ -153,9 +153,9 @@ Building Apache SIS
   invoke the following from the command line. Do not forget the <<<--non-recursive>>>
   option, otherwise the Mojo will waste CPU by executing itself many time.
 
-----------------------------------------------------------------
-   mvn org.apache.sis:sis-build-helper:pack --non-recursive
-----------------------------------------------------------------
+-------------------------------------------------------------------
+   mvn org.apache.sis.core:sis-build-helper:pack --non-recursive
+-------------------------------------------------------------------
 
   The above command should create a <<<target/binaries/sis-\<version\>.pack.gz>>> file.
   To uncompress that file, use the following command:

Modified: sis/trunk/core/sis-metadata/src/main/java/org/apache/sis/internal/jaxb/gml/GMLAdapter.java
URL: http://svn.apache.org/viewvc/sis/trunk/core/sis-metadata/src/main/java/org/apache/sis/internal/jaxb/gml/GMLAdapter.java?rev=1511687&r1=1511686&r2=1511687&view=diff
==============================================================================
--- sis/trunk/core/sis-metadata/src/main/java/org/apache/sis/internal/jaxb/gml/GMLAdapter.java [UTF-8] (original)
+++ sis/trunk/core/sis-metadata/src/main/java/org/apache/sis/internal/jaxb/gml/GMLAdapter.java [UTF-8] Thu Aug  8 10:50:57 2013
@@ -19,6 +19,7 @@ package org.apache.sis.internal.jaxb.gml
 import javax.xml.bind.annotation.XmlID;
 import javax.xml.bind.annotation.XmlAttribute;
 import org.apache.sis.util.Version;
+import org.apache.sis.xml.Namespaces;
 import org.apache.sis.xml.IdentifierMap;
 import org.apache.sis.xml.IdentifierSpace;
 import org.apache.sis.xml.IdentifiedObject;
@@ -35,7 +36,7 @@ import org.apache.sis.xml.IdentifiedObje
  * @author  Guilhem Legal (Geomatys)
  * @author  Martin Desruisseaux (Geomatys)
  * @since   0.3 (derived from geotk-3.18)
- * @version 0.3
+ * @version 0.4
  * @module
  */
 public abstract class GMLAdapter {
@@ -65,7 +66,7 @@ public abstract class GMLAdapter {
      * @see org.apache.sis.internal.jaxb.gco.ObjectReference#getUUIDREF()
      */
     @XmlID
-    @XmlAttribute(required = true)
+    @XmlAttribute(namespace = Namespaces.GML, required = true)
     private String id;
 
     /**

Modified: sis/trunk/core/sis-metadata/src/main/java/org/apache/sis/metadata/iso/ISOMetadata.java
URL: http://svn.apache.org/viewvc/sis/trunk/core/sis-metadata/src/main/java/org/apache/sis/metadata/iso/ISOMetadata.java?rev=1511687&r1=1511686&r2=1511687&view=diff
==============================================================================
--- sis/trunk/core/sis-metadata/src/main/java/org/apache/sis/metadata/iso/ISOMetadata.java [UTF-8] (original)
+++ sis/trunk/core/sis-metadata/src/main/java/org/apache/sis/metadata/iso/ISOMetadata.java [UTF-8] Thu Aug  8 10:50:57 2013
@@ -125,7 +125,7 @@ public class ISOMetadata extends Modifia
             return IdentifierMapWithSpecialCases.EMPTY;
         }
         /*
-         * We do not cache (for now) the IdentifierMap because it is cheap to create, and if were
+         * We do not cache (for now) the IdentifierMap because it is cheap to create, and if we were
          * caching it we would need anyway to check if 'identifiers' still references the same list.
          */
         return new IdentifierMapWithSpecialCases(identifiers);

Modified: sis/trunk/core/sis-utility/src/main/java/org/apache/sis/internal/jaxb/PrimitiveTypeProperties.java
URL: http://svn.apache.org/viewvc/sis/trunk/core/sis-utility/src/main/java/org/apache/sis/internal/jaxb/PrimitiveTypeProperties.java?rev=1511687&r1=1511686&r2=1511687&view=diff
==============================================================================
--- sis/trunk/core/sis-utility/src/main/java/org/apache/sis/internal/jaxb/PrimitiveTypeProperties.java [UTF-8] (original)
+++ sis/trunk/core/sis-utility/src/main/java/org/apache/sis/internal/jaxb/PrimitiveTypeProperties.java [UTF-8] Thu Aug  8 10:50:57 2013
@@ -102,7 +102,8 @@ public final class PrimitiveTypeProperti
      * @return The property associated to the given instance, or {@code null} if none.
      */
     public static Object property(final Object primitive) {
-        assert isValidKey(primitive) : primitive;
+        // No 'assert isValidKey(primitive)' because this method is sometime invoked
+        // only after a brief inspection (e.g. 'NilReason.mayBeNil(Object)' method).
         synchronized (SENTINEL_VALUES) {
             return SENTINEL_VALUES.get(primitive);
         }

Modified: sis/trunk/core/sis-utility/src/main/java/org/apache/sis/internal/system/DefaultFactories.java
URL: http://svn.apache.org/viewvc/sis/trunk/core/sis-utility/src/main/java/org/apache/sis/internal/system/DefaultFactories.java?rev=1511687&r1=1511686&r2=1511687&view=diff
==============================================================================
--- sis/trunk/core/sis-utility/src/main/java/org/apache/sis/internal/system/DefaultFactories.java [UTF-8] (original)
+++ sis/trunk/core/sis-utility/src/main/java/org/apache/sis/internal/system/DefaultFactories.java [UTF-8] Thu Aug  8 10:50:57 2013
@@ -86,11 +86,17 @@ public final class DefaultFactories exte
         T factory = type.cast(FACTORIES.get(type));
         if (factory == null && !FACTORIES.containsKey(type)) {
             for (final T candidate : ServiceLoader.load(type)) {
-                if (candidate.getClass().getName().startsWith("org.apache.sis.")) {
+                final Class<?> ct = candidate.getClass();
+                if (ct.getName().startsWith("org.apache.sis.")) {
                     factory = candidate;
                     break;
                 }
-                if (factory == null) {
+                /*
+                 * Select the first provider found in the iteration. If more than one provider is found,
+                 * select the most specialized type. This is okay only for relatively simple configurations,
+                 * while we are waiting for a real dependency injection mechanism.
+                 */
+                if (factory == null || factory.getClass().isAssignableFrom(ct)) {
                     factory = candidate;
                 }
             }

Modified: sis/trunk/core/sis-utility/src/main/java/org/apache/sis/setup/OptionKey.java
URL: http://svn.apache.org/viewvc/sis/trunk/core/sis-utility/src/main/java/org/apache/sis/setup/OptionKey.java?rev=1511687&r1=1511686&r2=1511687&view=diff
==============================================================================
--- sis/trunk/core/sis-utility/src/main/java/org/apache/sis/setup/OptionKey.java [UTF-8] (original)
+++ sis/trunk/core/sis-utility/src/main/java/org/apache/sis/setup/OptionKey.java [UTF-8] Thu Aug  8 10:50:57 2013
@@ -19,6 +19,7 @@ package org.apache.sis.setup;
 import java.util.Map;
 import java.util.HashMap;
 import java.nio.ByteBuffer;
+import java.nio.charset.Charset;
 import java.io.Serializable;
 import java.io.ObjectStreamException;
 import org.apache.sis.util.ArgumentChecks;
@@ -26,8 +27,33 @@ import org.apache.sis.util.logging.Loggi
 
 
 /**
- * Keys in a map of options, together with static constants for commonly-used options.
- * Developers can subclass this class for defining their own options.
+ * Keys in a map of options for configuring various services
+ * ({@link org.apache.sis.storage.DataStore}, <i>etc</i>).
+ * {@code OptionKey}s are used for aspects that usually do not need to be configured, except in a few specialized cases.
+ * For example most data file formats read by SIS do not require the user to specify the character encoding, since the
+ * encoding it is often given in the file header or in the format specification. However if SIS may have to read plain
+ * text files <em>and</em> the default platform encoding is not suitable, then the user can specify the desired encoding
+ * explicitely using the {@link #ENCODING} option.
+ *
+ * <p>All options are <em>hints</em> and may be silently ignored. For example most {@code DataStore}s will ignore the
+ * {@code ENCODING} option if irrelevant to their format, or if the encoding is specified in the data file header.</p>
+ *
+ * <p>Options are <em>transitive</em>: if a service uses others services for its internal working, the given options
+ * may also be given to those dependencies, at implementation choice.</p>
+ *
+ * {@section Defining new options}
+ * Developers who wish to define their own options can define static constants in a subclass,
+ * as in the following example:
+ *
+ * {@preformat java
+ *     public final class MyOptionKey<T> extends OptionKey<T> {
+ *         public static final OptionKey<String> MY_OPTION = new MyOptionKey<>("MY_OPTION", String.class);
+ *
+ *         private MyOptionKey(final String name, final Class<T> type) {
+ *             super(name, type);
+ *         }
+ *     }
+ * }
  *
  * @param <T> The type of option values.
  *
@@ -43,6 +69,19 @@ public class OptionKey<T> implements Ser
     private static final long serialVersionUID = -7580514229639750246L;
 
     /**
+     * The character encoding of document content.
+     * This option can be used when the file to read does not describe itself its encoding.
+     * For example this option can be used when reading plain text files, but is ignored when
+     * reading XML files having a {@code <?xml version="1.0" encoding="…"?>} declaration.
+     *
+     * <p>If this option is not provided, then the default value is the
+     * {@link Charset#defaultCharset() platform default}.</p>
+     *
+     * @since 0.4
+     */
+    public static final OptionKey<Charset> ENCODING = new OptionKey<Charset>("ENCODING", Charset.class);
+
+    /**
      * The encoding of a URL (<strong>not</strong> the encoding of the document content).
      * This option may be used when converting a {@link String} or a {@link java.net.URL}
      * to a {@link java.net.URI} or a {@link java.io.File}. The following rules apply:

Modified: sis/trunk/core/sis-utility/src/main/java/org/apache/sis/util/Static.java
URL: http://svn.apache.org/viewvc/sis/trunk/core/sis-utility/src/main/java/org/apache/sis/util/Static.java?rev=1511687&r1=1511686&r2=1511687&view=diff
==============================================================================
--- sis/trunk/core/sis-utility/src/main/java/org/apache/sis/util/Static.java [UTF-8] (original)
+++ sis/trunk/core/sis-utility/src/main/java/org/apache/sis/util/Static.java [UTF-8] Thu Aug  8 10:50:57 2013
@@ -58,6 +58,8 @@ package org.apache.sis.util;
  * <tr><th colspan="2" class="hsep">Input / Output (including CRS, XML, images)</th></tr>
  * <tr><td>{@link org.apache.sis.io.IO}</td>
  *     <td>Methods working on {@link Appendable} instances.</td></tr>
+ * <tr><td>{@link org.apache.sis.storage.DataStores}</td>
+ *     <td>Read or write geospatial data in various backends.</td></tr>
  * <tr><td>{@link org.apache.sis.xml.XML}</td>
  *     <td>Marshal or unmarshal ISO 19115 objects.</td></tr>
  * <tr><td>{@link org.apache.sis.xml.Namespaces}</td>

Modified: sis/trunk/core/sis-utility/src/main/java/org/apache/sis/util/logging/WarningListeners.java
URL: http://svn.apache.org/viewvc/sis/trunk/core/sis-utility/src/main/java/org/apache/sis/util/logging/WarningListeners.java?rev=1511687&r1=1511686&r2=1511687&view=diff
==============================================================================
--- sis/trunk/core/sis-utility/src/main/java/org/apache/sis/util/logging/WarningListeners.java [UTF-8] (original)
+++ sis/trunk/core/sis-utility/src/main/java/org/apache/sis/util/logging/WarningListeners.java [UTF-8] Thu Aug  8 10:50:57 2013
@@ -46,7 +46,7 @@ import org.apache.sis.util.resources.Err
  *
  * @author  Martin Desruisseaux (Geomatys)
  * @since   0.3
- * @version 0.3
+ * @version 0.4
  * @module
  *
  * @see WarningListener
@@ -257,4 +257,15 @@ public class WarningListeners<S> impleme
         }
         throw new NoSuchElementException(Errors.format(Errors.Keys.NoSuchElement_1, listener));
     }
+
+    /**
+     * Returns {@code true} if this object contains at least one listener.
+     *
+     * @return {@code true} if this object contains at least one listener, {@code false} otherwise.
+     *
+     * @since 0.4
+     */
+    public synchronized boolean hasListeners() {
+        return listeners != null;
+    }
 }

Modified: sis/trunk/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.java
URL: http://svn.apache.org/viewvc/sis/trunk/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.java?rev=1511687&r1=1511686&r2=1511687&view=diff
==============================================================================
--- sis/trunk/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.java [UTF-8] (original)
+++ sis/trunk/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.java [UTF-8] Thu Aug  8 10:50:57 2013
@@ -99,6 +99,11 @@ public final class Errors extends Indexe
         public static final int CanNotParseFile_2 = 79;
 
         /**
+         * Can not read “{0}”.
+         */
+        public static final int CanNotRead_1 = 108;
+
+        /**
          * Can not set a value for property “{0}”.
          */
         public static final int CanNotSetPropertyValue_1 = 75;

Modified: sis/trunk/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.properties
URL: http://svn.apache.org/viewvc/sis/trunk/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.properties?rev=1511687&r1=1511686&r2=1511687&view=diff
==============================================================================
--- sis/trunk/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.properties [ISO-8859-1] (original)
+++ sis/trunk/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.properties [ISO-8859-1] Thu Aug  8 10:50:57 2013
@@ -31,6 +31,7 @@ CanNotComputeDerivative         = Can no
 CanNotInstantiate_1             = Can not instantiate an object of type \u2018{0}\u2019.
 CanNotOpen_1                    = Can not open \u201c{0}\u201d.
 CanNotParseFile_2               = Can not parse \u201c{1}\u201d as a file in the {0} format.
+CanNotRead_1                    = Can not read \u201c{0}\u201d.
 CanNotSetPropertyValue_1        = Can not set a value for property \u201c{0}\u201d.
 ClassNotFinal_1                 = Class \u2018{0}\u2019 is not final.
 CloneNotSupported_1             = Can not clone an object of type \u2018{0}\u2019.

Modified: sis/trunk/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors_fr.properties
URL: http://svn.apache.org/viewvc/sis/trunk/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors_fr.properties?rev=1511687&r1=1511686&r2=1511687&view=diff
==============================================================================
--- sis/trunk/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors_fr.properties [ISO-8859-1] (original)
+++ sis/trunk/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors_fr.properties [ISO-8859-1] Thu Aug  8 10:50:57 2013
@@ -21,6 +21,7 @@ CanNotComputeDerivative         = La d\u
 CanNotInstantiate_1             = Ne peut pas cr\u00e9er un objet de type \u2018{0}\u2019.
 CanNotOpen_1                    = Ne peut pas ouvrir \u201c{0}\u201d.
 CanNotParseFile_2               = Ne peut pas lire \u201c{1}\u201d comme un fichier au format {0}.
+CanNotRead_1                    = Ne peut pas lire \u201c{0}\u201d.
 CanNotSetPropertyValue_1        = Ne peut pas d\u00e9finir une valeur pour la propri\u00e9t\u00e9 \u201c{0}\u201d.
 ClassNotFinal_1                 = La classe \u2018{0}\u2019 n\u2019est pas finale.
 CloneNotSupported_1             = Un objet de type \u2018{0}\u2019 ne peut pas \u00eatre clon\u00e9.

Modified: sis/trunk/core/sis-utility/src/main/java/org/apache/sis/xml/MarshallerPool.java
URL: http://svn.apache.org/viewvc/sis/trunk/core/sis-utility/src/main/java/org/apache/sis/xml/MarshallerPool.java?rev=1511687&r1=1511686&r2=1511687&view=diff
==============================================================================
--- sis/trunk/core/sis-utility/src/main/java/org/apache/sis/xml/MarshallerPool.java [UTF-8] (original)
+++ sis/trunk/core/sis-utility/src/main/java/org/apache/sis/xml/MarshallerPool.java [UTF-8] Thu Aug  8 10:50:57 2013
@@ -413,7 +413,7 @@ public class MarshallerPool {
     }
 
     /**
-     * Creates an configure a new JAXB marshaller.
+     * Creates an configures a new JAXB marshaller.
      * This method is invoked only when no existing marshaller is available in the pool.
      * Subclasses can override this method if they need to change the marshaller configuration.
      *
@@ -446,7 +446,7 @@ public class MarshallerPool {
     }
 
     /**
-     * Creates an configure a new JAXB unmarshaller.
+     * Creates an configures a new JAXB unmarshaller.
      * This method is invoked only when no existing unmarshaller is available in the pool.
      * Subclasses can override this method if they need to change the unmarshaller configuration.
      *

Modified: sis/trunk/core/sis-utility/src/main/java/org/apache/sis/xml/XML.java
URL: http://svn.apache.org/viewvc/sis/trunk/core/sis-utility/src/main/java/org/apache/sis/xml/XML.java?rev=1511687&r1=1511686&r2=1511687&view=diff
==============================================================================
--- sis/trunk/core/sis-utility/src/main/java/org/apache/sis/xml/XML.java [UTF-8] (original)
+++ sis/trunk/core/sis-utility/src/main/java/org/apache/sis/xml/XML.java [UTF-8] Thu Aug  8 10:50:57 2013
@@ -29,6 +29,8 @@ import java.io.StringWriter;
 import javax.xml.bind.Marshaller;
 import javax.xml.bind.Unmarshaller;
 import javax.xml.bind.JAXBException;
+import javax.xml.transform.Source;
+import javax.xml.transform.Result;
 import org.apache.sis.util.Static;
 import org.apache.sis.util.Version;
 import org.apache.sis.util.logging.WarningListener;
@@ -60,7 +62,7 @@ import static org.apache.sis.util.Argume
  * @author  Cédric Briançon (Geomatys)
  * @author  Martin Desruisseaux (Geomatys)
  * @since   0.3 (derived from geotk-3.00)
- * @version 0.3
+ * @version 0.4
  * @module
  */
 public final class XML extends Static {
@@ -376,6 +378,36 @@ public final class XML extends Static {
     }
 
     /**
+     * Marshall the given object to a stream, DOM or other destinations.
+     * This is the most flexible marshalling method provided in this {@code XML} class.
+     * The destination is specified by the {@code output} argument implementation, for example
+     * {@link javax.xml.transform.stream.StreamResult} for writing to a file or output stream.
+     * The optional {@code properties} map can contain any key documented in this {@code XML} class,
+     * together with the keys documented in the <cite>supported properties</cite> section of the the
+     * {@link Marshaller} class.
+     *
+     * @param  object The root of content tree to be marshalled.
+     * @param  output The file to be written.
+     * @param  properties An optional map of properties to give to the marshaller, or {@code null} if none.
+     * @throws JAXBException If a property has an illegal value, or if an error occurred during the marshalling.
+     *
+     * @since 0.4
+     */
+    public static void marshal(final Object object, final Result output, final Map<String,?> properties) throws JAXBException {
+        ensureNonNull("object", object);
+        ensureNonNull("output", output);
+        final MarshallerPool pool = getPool();
+        final Marshaller marshaller = pool.acquireMarshaller();
+        if (properties != null) {
+            for (final Map.Entry<String,?> entry : properties.entrySet()) {
+                marshaller.setProperty(entry.getKey(), entry.getValue());
+            }
+        }
+        marshaller.marshal(object, output);
+        pool.recycle(marshaller);
+    }
+
+    /**
      * Unmarshall an object from the given string.
      *
      * @param  input The XML representation of an object.
@@ -439,4 +471,36 @@ public final class XML extends Static {
         pool.recycle(unmarshaller);
         return object;
     }
+
+    /**
+     * Unmarshall an object from the given stream, DOM or other sources.
+     * This is the most flexible unmarshalling method provided in this {@code XML} class.
+     * The source is specified by the {@code input} argument implementation, for example
+     * {@link javax.xml.transform.stream.StreamSource} for reading from a file or input stream.
+     * The optional {@code properties} map can contain any key documented in this {@code XML} class,
+     * together with the keys documented in the <cite>supported properties</cite> section of the the
+     * {@link Unmarshaller} class.
+     *
+     * @param  input The file from which to read a XML representation.
+     * @param  properties An optional map of properties to give to the unmarshaller, or {@code null} if none.
+     * @return The object unmarshalled from the given input.
+     * @throws JAXBException If a property has an illegal value, or if an error occurred during the unmarshalling.
+     *
+     * @since 0.4
+     *
+     * @see org.apache.sis.storage.xml.XMLStore
+     */
+    public static Object unmarshal(final Source input, final Map<String,?> properties) throws JAXBException {
+        ensureNonNull("input", input);
+        final MarshallerPool pool = getPool();
+        final Unmarshaller unmarshaller = pool.acquireUnmarshaller();
+        if (properties != null) {
+            for (final Map.Entry<String,?> entry : properties.entrySet()) {
+                unmarshaller.setProperty(entry.getKey(), entry.getValue());
+            }
+        }
+        final Object object = unmarshaller.unmarshal(input);
+        pool.recycle(unmarshaller);
+        return object;
+    }
 }

Modified: sis/trunk/storage/sis-netcdf/src/main/java/org/apache/sis/storage/netcdf/NetcdfStoreProvider.java
URL: http://svn.apache.org/viewvc/sis/trunk/storage/sis-netcdf/src/main/java/org/apache/sis/storage/netcdf/NetcdfStoreProvider.java?rev=1511687&r1=1511686&r2=1511687&view=diff
==============================================================================
--- sis/trunk/storage/sis-netcdf/src/main/java/org/apache/sis/storage/netcdf/NetcdfStoreProvider.java [UTF-8] (original)
+++ sis/trunk/storage/sis-netcdf/src/main/java/org/apache/sis/storage/netcdf/NetcdfStoreProvider.java [UTF-8] Thu Aug  8 10:50:57 2013
@@ -116,7 +116,7 @@ public class NetcdfStoreProvider extends
         final ByteBuffer buffer = storage.getStorageAs(ByteBuffer.class);
         if (buffer != null) {
             if (buffer.remaining() < Integer.SIZE / Byte.SIZE) {
-                return ProbeResult.UNDETERMINED;
+                return ProbeResult.INSUFFICIENT_BYTES;
             }
             final int header = buffer.getInt(buffer.position());
             if ((header & 0xFFFFFF00) == ChannelDecoder.MAGIC_NUMBER) {
@@ -131,7 +131,7 @@ public class NetcdfStoreProvider extends
             ensureInitialized();
             final Method method = canOpenFromPath;
             if (method != null) try {
-                return ((Boolean) method.invoke(null, path)) ? ProbeResult.SUPPORTED : ProbeResult.UNKNOWN_FORMAT;
+                return ((Boolean) method.invoke(null, path)) ? ProbeResult.SUPPORTED : ProbeResult.UNSUPPORTED_STORAGE;
             } catch (IllegalAccessException e) {
                 throw new AssertionError(e); // Should never happen, since the method is public.
             } catch (InvocationTargetException e) {
@@ -152,7 +152,7 @@ public class NetcdfStoreProvider extends
                 return ProbeResult.SUPPORTED;
             }
         }
-        return ProbeResult.UNKNOWN_FORMAT;
+        return ProbeResult.UNSUPPORTED_STORAGE;
     }
 
     /**

Modified: sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/internal/storage/ChannelDataInput.java
URL: http://svn.apache.org/viewvc/sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/internal/storage/ChannelDataInput.java?rev=1511687&r1=1511686&r2=1511687&view=diff
==============================================================================
--- sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/internal/storage/ChannelDataInput.java [UTF-8] (original)
+++ sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/internal/storage/ChannelDataInput.java [UTF-8] Thu Aug  8 10:50:57 2013
@@ -59,7 +59,7 @@ import java.nio.channels.FileChannel;
  *
  * @author  Martin Desruisseaux (Geomatys)
  * @since   0.3 (derived from geotk-3.07)
- * @version 0.3
+ * @version 0.4
  * @module
  */
 public class ChannelDataInput {
@@ -150,6 +150,34 @@ public class ChannelDataInput {
     }
 
     /**
+     * Tries to read more bytes from the channel without changing the buffer position.
+     * This method returns a negative number if the buffer is already full or if the channel reached the
+     * <cite>end of stream</cite>. Otherwise this method reads an arbitrary amount of bytes not greater
+     * than the space available in the buffer, and returns the amount bytes actually read.
+     *
+     * @return The number of bytes read, or -2 if the buffer is full, or -1 on <cite>end of stream</cite>.
+     * @throws IOException If an error occurred while reading the bytes.
+     *
+     * @since 0.4
+     */
+    public final int prefetch() throws IOException {
+        final int limit    = buffer.limit();
+        final int capacity = buffer.capacity();
+        if (limit == capacity) {
+            return -2;
+        }
+        final int position = buffer.position();
+        buffer.limit(capacity).position(limit);
+        int c = channel.read(buffer);
+        while (c == 0) {
+            onEmptyChannelBuffer();
+            c = channel.read(buffer);
+        }
+        buffer.limit(buffer.position()).position(position);
+        return c;
+    }
+
+    /**
      * Returns {@code true} if the buffer or the channel has at least one byte remaining.
      * If the {@linkplain #buffer} has no remaining bytes, then this method will attempts
      * to read at least one byte from the {@linkplain #channel}. If no bytes can be read
@@ -708,8 +736,9 @@ public class ChannelDataInput {
                     }
                     onEmptyChannelBuffer();
                 }
+                buffer.flip();
             } while (p > buffer.limit());
-            buffer.flip().position((int) p);
+            buffer.position((int) p);
         } else {
             /*
              * Requested position is before the current buffer limits

Modified: sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/storage/DataStoreProvider.java
URL: http://svn.apache.org/viewvc/sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/storage/DataStoreProvider.java?rev=1511687&r1=1511686&r2=1511687&view=diff
==============================================================================
--- sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/storage/DataStoreProvider.java [UTF-8] (original)
+++ sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/storage/DataStoreProvider.java [UTF-8] Thu Aug  8 10:50:57 2013
@@ -67,7 +67,7 @@ public abstract class DataStoreProvider 
      * <ul>
      *   <li>{@link ProbeResult#SUPPORTED} if the {@code DataStore}s created by this provider
      *       can open the given storage.</li>
-     *   <li>{@link ProbeResult#UNKNOWN_STORAGE} if the given storage does not appear to be in a format
+     *   <li>{@link ProbeResult#UNSUPPORTED_STORAGE} if the given storage does not appear to be in a format
      *       supported by this {@code DataStoreProvider}.</li>
      * </ul>
      *
@@ -90,18 +90,18 @@ public abstract class DataStoreProvider 
      *         if (buffer == null) {
      *             // If StorageConnector can not provide a ByteBuffer, then the storage is
      *             // probably not a File, URL, URI, InputStream neither a ReadableChannel.
-     *             return ProbeResult.UNKNOWN_STORAGE;
+     *             return ProbeResult.UNSUPPORTED_STORAGE;
      *         }
      *         if (buffer.remaining() < Integer.SIZE / Byte.SIZE) {
      *             // If the buffer does not contain enough bytes for the integer type, this is not
      *             // necessarily because the file is truncated. It may be because the data were not
      *             // yet available at the time this method has been invoked.
-     *             return ProbeResult.UNDETERMINED;
+     *             return ProbeResult.INSUFFICIENT_BYTES;
      *         }
      *         if (buffer.getInt(buffer.position()) != MAGIC_NUMBER) {
      *             // We used ByteBuffer.getInt(int) instead than ByteBuffer.getInt() above
      *             // in order to keep the buffer position unchanged after this method call.
-     *             return ProbeResult.UNKNOWN_FORMAT;
+     *             return ProbeResult.UNSUPPORTED_STORAGE;
      *         }
      *         return ProbeResult.SUPPORTED;
      *     }

Modified: sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/storage/DataStoreRegistry.java
URL: http://svn.apache.org/viewvc/sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/storage/DataStoreRegistry.java?rev=1511687&r1=1511686&r2=1511687&view=diff
==============================================================================
--- sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/storage/DataStoreRegistry.java [UTF-8] (original)
+++ sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/storage/DataStoreRegistry.java [UTF-8] Thu Aug  8 10:50:57 2013
@@ -16,6 +16,9 @@
  */
 package org.apache.sis.storage;
 
+import java.util.List;
+import java.util.LinkedList;
+import java.util.Iterator;
 import java.util.ServiceLoader;
 import org.apache.sis.util.ThreadSafe;
 import org.apache.sis.util.ArgumentChecks;
@@ -70,7 +73,7 @@ final class DataStoreRegistry {
      *   <li>A {@link java.nio.file.Path} or a {@link java.io.File} for a file or a directory.</li>
      *   <li>A {@link java.net.URI} or a {@link java.net.URL} to a distant resource.</li>
      *   <li>A {@link java.lang.CharSequence} interpreted as a filename or a URL.</li>
-     *   <li>A {@link java.nio.channels.Channel} or a {@link java.io.DataInput}.</li>
+     *   <li>A {@link java.nio.channels.Channel}, {@link java.io.DataInput}, {@link java.io.InputStream} or {@link java.io.Reader}.</li>
      *   <li>A {@link javax.sql.DataSource} or a {@link java.sql.Connection} to a JDBC database.</li>
      *   <li>Any other {@code DataStore}-specific object, for example {@link ucar.nc2.NetcdfFile}.</li>
      *   <li>An existing {@link StorageConnector} instance.</li>
@@ -89,22 +92,85 @@ final class DataStoreRegistry {
         } else {
             connector = new StorageConnector(storage);
         }
+        DataStoreProvider provider = null;
+        List<DataStoreProvider> deferred = null;
         try {
-            DataStoreProvider provider = null;
+            /*
+             * All usages of 'loader' and its 'providers' iterator must be protected in a synchronized block,
+             * because ServiceLoader is not thread-safe. We try to keep the synhronization block as small as
+             * possible for less contention. In particular, the canOpen(connector) method call may be costly.
+             */
+            final Iterator<DataStoreProvider> providers;
+            DataStoreProvider candidate;
             synchronized (loader) {
-search:         for (final DataStoreProvider candidate : loader) {
-                    switch (candidate.canOpen(connector)) {
-                        case SUPPORTED: {
-                            provider = candidate;
-                            break search;
+                providers = loader.iterator();
+                candidate = providers.hasNext() ? providers.next() : null;
+            }
+search:     while (candidate != null) {
+                switch (candidate.canOpen(connector)) {
+                    /*
+                     * Stop at the first provider claiming to be able to read the storage.
+                     * Do not iterate over the list of deferred providers (if any).
+                     */
+                    case SUPPORTED: {
+                        provider = candidate;
+                        deferred = null;
+                        break search;
+                    }
+                    /*
+                     * If a provider doesn't have enough bytes for answering the question,
+                     * try again after this loop with more bytes in the buffer, unless we
+                     * found an other provider.
+                     */
+                    case INSUFFICIENT_BYTES: {
+                        if (deferred == null) {
+                            deferred = new LinkedList<DataStoreProvider>();
                         }
-                        case UNDETERMINED: {
-                            // TODO: not enough information.
-                            break;
+                        deferred.add(candidate);
+                        break;
+                    }
+                    /*
+                     * If a provider doesn't know whether it can open the given storage,
+                     * we will try it only if we find no provider retuning SUPPORTED.
+                     *
+                     * TODO: What to do if we find more than one provider here? We can not invoke
+                     *       provider.open(connector) in a try … catch block because it may leave
+                     *       the StorageConnector in an invalid state in case of failure.
+                     */
+                    case UNDETERMINED: {
+                        provider = candidate;
+                        break;
+                    }
+                }
+                synchronized (loader) {
+                    candidate = providers.hasNext() ? providers.next() : null;
+                }
+            }
+            /*
+             * If any provider did not had enough bytes for answering the 'canOpen(…)' question,
+             * get more bytes and try again. We try to prefetch more bytes only if we have no choice
+             * in order to avoid latency on network connection.
+             */
+            if (deferred != null) {
+search:         while (!deferred.isEmpty() && connector.prefetch()) {
+                    for (final Iterator<DataStoreProvider> it=deferred.iterator(); it.hasNext();) {
+                        candidate = it.next();
+                        switch (candidate.canOpen(connector)) {
+                            case SUPPORTED:          provider = candidate; break search;
+                            case UNDETERMINED:       provider = candidate; break;
+                            case INSUFFICIENT_BYTES: continue; // Will try again in next iteration.
                         }
+                        it.remove(); // UNSUPPORTED_* or UNDETERMINED: do not try again those providers.
                     }
                 }
             }
+            /*
+             * If a provider has been found, or if a provider returned UNDETERMINED, use that one
+             * for opening a DataStore. Note that if more than one provider returned UNDETERMINED,
+             * the selected one is arbitrary and may change in different execution. Implementors
+             * shall avoid the UNDETERMINED value as much as possible (this value should be used
+             * only for RAW image format).
+             */
             if (provider != null) {
                 final DataStore data = provider.open(connector);
                 connector = null; // For preventing it to be closed.

Modified: sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/storage/DataStores.java
URL: http://svn.apache.org/viewvc/sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/storage/DataStores.java?rev=1511687&r1=1511686&r2=1511687&view=diff
==============================================================================
--- sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/storage/DataStores.java [UTF-8] (original)
+++ sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/storage/DataStores.java [UTF-8] Thu Aug  8 10:50:57 2013
@@ -69,7 +69,7 @@ public final class DataStores extends St
      *   <li>A {@link java.nio.file.Path} or a {@link java.io.File} for a file or a directory.</li>
      *   <li>A {@link java.net.URI} or a {@link java.net.URL} to a distant resource.</li>
      *   <li>A {@link java.lang.CharSequence} interpreted as a filename or a URL.</li>
-     *   <li>A {@link java.nio.channels.Channel} or a {@link java.io.DataInput}.</li>
+     *   <li>A {@link java.nio.channels.Channel}, {@link java.io.DataInput}, {@link java.io.InputStream} or {@link java.io.Reader}.</li>
      *   <li>A {@link javax.sql.DataSource} or a {@link java.sql.Connection} to a JDBC database.</li>
      *   <li>Any other {@code DataStore}-specific object, for example {@link ucar.nc2.NetcdfFile}.</li>
      *   <li>An existing {@link StorageConnector} instance.</li>

Modified: sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/storage/ProbeResult.java
URL: http://svn.apache.org/viewvc/sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/storage/ProbeResult.java?rev=1511687&r1=1511686&r2=1511687&view=diff
==============================================================================
--- sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/storage/ProbeResult.java [UTF-8] (original)
+++ sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/storage/ProbeResult.java [UTF-8] Thu Aug  8 10:50:57 2013
@@ -23,12 +23,11 @@ package org.apache.sis.storage;
  *
  * <ul>
  *   <li>{@link #SUPPORTED} indicates that the storage can be read and eventually written.</li>
- *   <li>{@link #UNDETERMINED} indicates that the provider does not have enough information for telling
- *       whether the storage can be opened. SIS will try to use such provider last, if no better suited
- *       provider is found.</li>
- *   <li>All other values indicate that the storage can not be opened. The actual enumeration value gives
- *       the reason (e.g. {@linkplain #UNKNOWN_FORMAT unknown format}, or
- *       {@linkplain #UNSUPPORTED_VERSION unsupported version}).</li>
+ *   <li>{@code UNSUPPORTED_*} indicate that the storage can not be opened. The actual enumeration value gives
+ *       the reason (e.g. unsupported format or {@linkplain #UNSUPPORTED_VERSION unsupported version}).</li>
+ *   <li>{@link #INSUFFICIENT_BYTES} or {@link #UNDETERMINED} indicate that the provider does not have enough
+ *       information for telling whether the storage can be opened. SIS will try to use such provider last,
+ *       if no better suited provider is found.</li>
  * </ul>
  *
  * When a {@link DataStores#open DataStores.open(…)} method is invoked, SIS will iterate over the list of known
@@ -52,34 +51,56 @@ public enum ProbeResult {
     SUPPORTED,
 
     /**
-     * The open capability can not be determined.
-     * This value may be returned in two kinds of situation:
+     * The {@code DataStoreProvider} does not recognize the given storage object, file format or database schema.
+     * Examples:
      *
      * <ul>
-     *   <li>The method can not look ahead far enough in the file header,
-     *       for example because the buffer has not fetched enough bytes.</li>
-     *   <li>The {@code DataStore} could potentially open anything.
-     *       This is the case for example of the RAW image format.</li>
+     *   <li>The storage is a file while the provider expected a database connection (or conversely).</li>
+     *   <li>The file does not contains the expected magic number.</li>
+     *   <li>The database schema does not contain the expected tables.</li>
      * </ul>
      */
-    UNDETERMINED,
+    UNSUPPORTED_STORAGE,
 
     /**
-     * The {@code DataStoreProvider} does not recognize the given storage object.
-     * For example the storage may be a file while the provider expected a database connection, or conversely.
+     * The {@code DataStoreProvider} recognizes the given storage, but the data are structured
+     * according a file or schema version not yet supported by the current implementation.
      */
-    UNKNOWN_STORAGE,
+    UNSUPPORTED_VERSION,
 
     /**
-     * The {@code DataStoreProvider} does not recognize the file format or schema.
-     * For example the file does not contains the expected magic number,
-     * or the database schema does not contain the expected tables.
+     * The open capability can not be determined because the {@link ByteBuffer} contains an insufficient
+     * amount of bytes. This value may be returned by {@link DataStoreProvider#canOpen(StorageConnector)}
+     * implementations similar to the following:
+     *
+     * {@preformat java
+     *     public ProbeResult canOpen(StorageConnector storage) throws DataStoreException {
+     *         final ByteBuffer buffer = storage.getStorageAs(ByteBuffer.class);
+     *         if (buffer == null) {
+     *             return ProbeResult.UNSUPPORTED_STORAGE;
+     *         }
+     *         if (buffer.remaining() < Integer.SIZE / Byte.SIZE) {
+     *             return ProbeResult.INSUFFICIENT_BYTES;
+     *         }
+     *         // Other verifications here.
+     *     }
+     * }
+     *
+     * When some {@code DataStoreProvider} return this value, SIS will first continue the search for a provider that
+     * can answer the {@code canOpen(…)} question using only the available bytes. Only if no provider is found,
+     * then SIS will fetch more bytes and try again the providers that returned {@code INSUFFICIENT_BYTES}.
+     * SIS tries to work with available bytes before to ask more in order to reduce latencies on network connections.
      */
-    UNKNOWN_FORMAT,
+    INSUFFICIENT_BYTES,
 
     /**
-     * The {@code DataStoreProvider} recognizes the given storage, but the data are structured
-     * according a file or schema version not yet supported by the current implementation.
+     * The open capability can not be determined.
+     * This value may be returned by {@code DataStore} implementations that could potentially open anything,
+     * as for example of the RAW image format.
+     *
+     * <p><strong>This is a last resort value!</strong> {@code canOpen(…)} implementations are strongly encouraged
+     * to return a more accurate enumeration value for allowing {@link DataStores#open(Object)} to perform a better
+     * choice. Generally, this value should be used only by the RAW image format.</p>
      */
-    UNSUPPORTED_VERSION
+    UNDETERMINED
 }

Modified: sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/storage/StorageConnector.java
URL: http://svn.apache.org/viewvc/sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/storage/StorageConnector.java?rev=1511687&r1=1511686&r2=1511687&view=diff
==============================================================================
--- sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/storage/StorageConnector.java [UTF-8] (original)
+++ sis/trunk/storage/sis-storage/src/main/java/org/apache/sis/storage/StorageConnector.java [UTF-8] Thu Aug  8 10:50:57 2013
@@ -17,13 +17,20 @@
 package org.apache.sis.storage;
 
 import java.util.Map;
+import java.util.Queue;
+import java.util.Iterator;
 import java.util.Collections;
+import java.util.LinkedList;
 import java.util.IdentityHashMap;
 import java.util.ConcurrentModificationException;
+import java.io.Reader;
 import java.io.DataInput;
+import java.io.InputStream;
 import java.io.IOException;
+import java.io.InputStreamReader;
 import java.io.Serializable;
 import java.nio.ByteBuffer;
+import java.nio.charset.Charset;
 import java.nio.channels.ReadableByteChannel;
 import javax.imageio.ImageIO;
 import javax.imageio.stream.ImageInputStream;
@@ -31,7 +38,6 @@ import java.sql.Connection;
 import javax.sql.DataSource;
 import org.apache.sis.util.Debug;
 import org.apache.sis.util.Classes;
-import org.apache.sis.util.ArraysExt;
 import org.apache.sis.util.ArgumentChecks;
 import org.apache.sis.util.resources.Errors;
 import org.apache.sis.internal.storage.IOUtilities;
@@ -51,7 +57,7 @@ import org.apache.sis.internal.jdk7.JDK7
  *   <li>A {@link java.nio.file.Path} or a {@link java.io.File} for a file or a directory.</li>
  *   <li>A {@link java.net.URI} or a {@link java.net.URL} to a distant resource.</li>
  *   <li>A {@link CharSequence} interpreted as a filename or a URL.</li>
- *   <li>A {@link java.nio.channels.Channel} or a {@link DataInput}.</li>
+ *   <li>A {@link java.nio.channels.Channel}, {@link DataInput}, {@link InputStream} or {@link Reader}.</li>
  *   <li>A {@link DataSource} or a {@link Connection} to a JDBC database.</li>
  *   <li>Any other {@code DataStore}-specific object, for example {@link ucar.nc2.NetcdfFile}.</li>
  * </ul>
@@ -85,6 +91,12 @@ public class StorageConnector implements
     static final int DEFAULT_BUFFER_SIZE = 4096;
 
     /**
+     * The minimal size of the {@link ByteBuffer} to be created. This size is used only
+     * for temporary buffers that are unlikely to be used for the actual reading process.
+     */
+    static final int MINIMAL_BUFFER_SIZE = 256;
+
+    /**
      * The input/output object given at construction time.
      *
      * @see #getStorage()
@@ -119,6 +131,12 @@ public class StorageConnector implements
      *   <li>{@link ImageInputStream}:
      *       Same as {@code DataInput} if it can be casted, or {@code null} otherwise.</li>
      *
+     *   <li>{@link InputStream}:
+     *       If not explicitely provided, this is a wrapper around the above {@link ImageInputStream}.</li>
+     *
+     *   <li>{@link Reader}:
+     *       If not explicitely provided, this is a wrapper around the above {@link InputStream}.</li>
+     *
      *   <li>{@link Connection}:
      *       The storage object as a JDBC connection.</li>
      * </ul>
@@ -132,6 +150,17 @@ public class StorageConnector implements
     private transient Map<Class<?>, Object> views;
 
     /**
+     * Objects which will need to be closed by the {@link #closeAllExcept(Object)} method.
+     * For each (<var>key</var>, <var>value</var>) entry, if the object to close (the key)
+     * is a wrapper around an other object (e.g. an {@link InputStreamReader} wrapping an
+     * {@link InputStream}), then the value is the other object.
+     *
+     * @see #addViewToClose(Object, Object)
+     * @see #closeAllExcept(Object)
+     */
+    private transient Map<Object, Object> viewsToClose;
+
+    /**
      * The options, created only when first needed.
      *
      * @see #getOption(OptionKey)
@@ -163,12 +192,13 @@ public class StorageConnector implements
     }
 
     /**
-     * Sets the option value for the given key. The default implementation recognizes the given options:
+     * Sets the option value for the given key. The default implementation recognizes the following options:
      *
      * <ul>
+     *   <li>{@link OptionKey#ENCODING}     for decoding characters in an input stream, if needed.</li>
      *   <li>{@link OptionKey#URL_ENCODING} for converting URL to URI or filename, if needed.</li>
      *   <li>{@link OptionKey#OPEN_OPTIONS} for specifying whether the data store shall be read only or read/write.</li>
-     *   <li>{@link OptionKey#BYTE_BUFFER} for allowing users to control the byte buffer to be created.</li>
+     *   <li>{@link OptionKey#BYTE_BUFFER}  for allowing users to control the byte buffer to be created.</li>
      * </ul>
      *
      * @param <T>   The type of option value.
@@ -263,12 +293,12 @@ public class StorageConnector implements
      *   </li>
      *   <li>{@link DataInput}:
      *     <ul>
-     *       <li>If the {@linkplain #getStorage() storage} object is already an instance of {@link DataInput}
+     *       <li>If the {@linkplain #getStorage() storage} object is already an instance of {@code DataInput}
      *           (including the {@link ImageInputStream} and {@link javax.imageio.stream.ImageOutputStream} types),
      *           then it is returned unchanged.</li>
      *
      *       <li>Otherwise if the input is an instance of {@link java.nio.file.Path}, {@link java.io.File},
-     *           {@link java.net.URI}, {@link java.net.URL}, {@link CharSequence}, {@link java.io.InputStream} or
+     *           {@link java.net.URI}, {@link java.net.URL}, {@link CharSequence}, {@link InputStream} or
      *           {@link java.nio.channels.ReadableByteChannel}, then an {@link ImageInputStream} backed by a
      *           {@link ByteBuffer} is created when first needed and returned.</li>
      *
@@ -280,7 +310,30 @@ public class StorageConnector implements
      *   </li>
      *   <li>{@link ImageInputStream}:
      *     <ul>
-     *       <li>If the {@code DataInput} computed above can be casted to {@code null}, returns it.</li>
+     *       <li>If the above {@code DataInput} can be created and casted to {@code ImageInputStream}, returns it.</li>
+     *
+     *       <li>Otherwise this method returns {@code null}.</li>
+     *     </ul>
+     *   </li>
+     *   <li>{@link InputStream}:
+     *     <ul>
+     *       <li>If the {@linkplain #getStorage() storage} object is already an instance of {@link InputStream},
+     *           then it is returned unchanged.</li>
+     *
+     *       <li>Otherwise if the above {@code ImageInputStream} can be created,
+     *           returns a wrapper around that stream.</li>
+     *
+     *       <li>Otherwise this method returns {@code null}.</li>
+     *     </ul>
+     *   </li>
+     *   <li>{@link Reader}:
+     *     <ul>
+     *       <li>If the {@linkplain #getStorage() storage} object is already an instance of {@link Reader},
+     *           then it is returned unchanged.</li>
+     *
+     *       <li>Otherwise if the above {@code InputStream} can be created, returns an {@link InputStreamReader}
+     *           using the encoding specified by {@link OptionKey#ENCODING} if any, or using the system default
+     *           encoding otherwise.</li>
      *
      *       <li>Otherwise this method returns {@code null}.</li>
      *     </ul>
@@ -367,6 +420,7 @@ public class StorageConnector implements
 
     /**
      * Creates a view for the input as a {@link ChannelDataInput} if possible.
+     * If the view can not be created, remember that fact in order to avoid new attempts.
      *
      * @param  asImageInputStream If the {@code ChannelDataInput} needs to be {@link ChannelImageInputStream} subclass.
      * @throws IOException If an error occurred while opening a channel for the input.
@@ -376,6 +430,7 @@ public class StorageConnector implements
                 getOption(OptionKey.URL_ENCODING), getOption(OptionKey.OPEN_OPTIONS));
         ChannelDataInput asDataInput = null;
         if (channel != null) {
+            addViewToClose(channel, storage);
             ByteBuffer buffer = getOption(OptionKey.BYTE_BUFFER);
             if (buffer == null) {
                 buffer = ByteBuffer.allocate(DEFAULT_BUFFER_SIZE);
@@ -388,6 +443,7 @@ public class StorageConnector implements
             } else {
                 asDataInput = new ChannelDataInput(name, channel, buffer, false);
             }
+            addViewToClose(asDataInput, channel);
         }
         addView(ChannelDataInput.class, asDataInput);
     }
@@ -416,27 +472,34 @@ public class StorageConnector implements
             final ChannelDataInput c = getView(ChannelDataInput.class);
             if (c == null) {
                 asDataInput = ImageIO.createImageInputStream(storage);
+                addViewToClose(asDataInput, storage);
             } else if (c instanceof DataInput) {
                 asDataInput = (DataInput) c;
+                // No call to 'addViewToClose' because the instance already exists.
             } else {
                 asDataInput = new ChannelImageInputStream(c);
-                if (views.put(ChannelDataInput.class, asDataInput) != c) {
+                if (views.put(ChannelDataInput.class, asDataInput) != c) { // Replace the previous instance.
                     throw new ConcurrentModificationException();
                 }
+                addViewToClose(asDataInput, c.channel);
             }
         }
         addView(DataInput.class, asDataInput);
     }
 
     /**
-     * If an {@link ImageInputStream} has been created without buffer, read an arbitrary amount of bytes now so
-     * we can provide a {@link ByteBuffer} for users who want it. We read only a small amount of bytes because,
-     * at the contrary of the buffer created in {@link #createChannelAndBuffer(boolean)}, the buffer created
-     * here is unlikely to be used for the reading process after the recognition of the file format.
+     * Creates a {@link ByteBuffer} from the {@link ChannelDataInput} if possible, or from the
+     * {@link ImageInputStream} otherwise. The buffer will be initialized with an arbitrary amount
+     * of bytes read from the input. This amount is not sufficient, it can be increased by a call
+     * to {@link #prefetch()}.
      *
      * @throws IOException If an error occurred while opening a stream for the input.
      */
     private void createByteBuffer() throws IOException, DataStoreException {
+        /*
+         * First, try to create the ChannelDataInput if it does not already exists.
+         * If successful, this will create a ByteBuffer companion as a side effect.
+         */
         if (!views.containsKey(ChannelDataInput.class)) {
             createChannelDataInput(false);
         }
@@ -445,15 +508,22 @@ public class StorageConnector implements
         if (c != null) {
             asByteBuffer = c.buffer.asReadOnlyBuffer();
         } else {
+            /*
+             * If no ChannelDataInput has been create by the above code, get the input as an ImageInputStream and
+             * read an arbitrary amount of bytes. Read only a small amount of bytes because, at the contrary of the
+             * buffer created in createChannelDataInput(boolean), the buffer created here is unlikely to be used for
+             * the reading process after the recognition of the file format.
+             */
             final ImageInputStream in = getStorageAs(ImageInputStream.class);
             if (in != null) {
                 in.mark();
-                final byte[] buffer = new byte[256];
+                final byte[] buffer = new byte[MINIMAL_BUFFER_SIZE];
                 final int n = in.read(buffer);
                 in.reset();
                 if (n >= 1) {
-                    asByteBuffer = ByteBuffer.wrap(ArraysExt.resize(buffer, n))
-                            .asReadOnlyBuffer().order(in.getByteOrder());
+                    asByteBuffer = ByteBuffer.wrap(buffer).order(in.getByteOrder());
+                    asByteBuffer.limit(n);
+                    // Can't invoke asReadOnly() because 'prefetch()' need to be able to write in it.
                 }
             }
         }
@@ -461,6 +531,46 @@ public class StorageConnector implements
     }
 
     /**
+     * Transfers more bytes from the {@link DataInput} to the {@link ByteBuffer}, if possible.
+     * This method returns {@code true} on success, or {@code false} if input is not a readable
+     * channel or stream, we have reached the end of stream, or the buffer is full.
+     *
+     * <p>This method is invoked when the amount of bytes in the buffer appears to be insufficient
+     * for {@link DataStoreProvider#canOpen(StorageConnector)} purpose.</p>
+     *
+     * @return {@code true} on success.
+     * @throws DataStoreException If an error occurred while reading more bytes.
+     */
+    final boolean prefetch() throws DataStoreException {
+        try {
+            final ChannelDataInput c = getView(ChannelDataInput.class);
+            if (c != null) {
+                return c.prefetch() >= 0;
+            }
+            /*
+             * The above code is the usual case. The code below this point is the fallback used when only
+             * an ImageInputStream was available. In such case, the ByteBuffer can only be the one created
+             * by the above createByteBuffer() method, which is known to be backed by a writable array.
+             */
+            final ImageInputStream input = getView(ImageInputStream.class);
+            if (input != null) {
+                final ByteBuffer buffer = getView(ByteBuffer.class);
+                if (buffer != null) {
+                    final int p = buffer.limit();
+                    final int n = input.read(buffer.array(), p, buffer.capacity() - p);
+                    if (n >= 0) {
+                        buffer.limit(p + n);
+                        return true;
+                    }
+                }
+            }
+        } catch (IOException e) {
+            throw new DataStoreException(Errors.format(Errors.Keys.CanNotRead_1, getStorageName()), e);
+        }
+        return false;
+    }
+
+    /**
      * Creates a storage view of the given type if possible, or returns {@code null} otherwise.
      * This method is invoked by {@link #getStorageAs(Class)} when first needed, and the result is cached.
      *
@@ -477,14 +587,47 @@ public class StorageConnector implements
         if (type == Connection.class) {
             if (storage instanceof Connection) {
                 return storage;
-            } else if (storage instanceof DataSource) {
-                return ((DataSource) storage).getConnection();
             }
+            if (storage instanceof DataSource) {
+                final Connection c = ((DataSource) storage).getConnection();
+                addViewToClose(c, storage);
+                return c;
+            }
+            return null;
         }
         if (type == ImageInputStream.class) {
             final DataInput input = getStorageAs(DataInput.class);
             return (input instanceof ImageInputStream) ? input : null;
         }
+        if (type == InputStream.class) {
+            if (storage instanceof InputStream) {
+                return storage;
+            }
+            final DataInput input = getStorageAs(DataInput.class);
+            if (input instanceof InputStream) {
+                return (InputStream) input;
+            }
+            if (input instanceof ImageInputStream) {
+                final InputStream c = new InputStreamAdapter((ImageInputStream) input);
+                addViewToClose(c, input);
+                return c;
+            }
+            return null;
+        }
+        if (type == Reader.class) {
+            if (storage instanceof Reader) {
+                return storage;
+            }
+            final InputStream input = getStorageAs(InputStream.class);
+            if (input != null) {
+                final Charset encoding = getOption(OptionKey.ENCODING);
+                final Reader c = (encoding != null) ? new InputStreamReader(input, encoding)
+                                                    : new InputStreamReader(input);
+                addViewToClose(c, input);
+                return c;
+            }
+            return null;
+        }
         throw new IllegalArgumentException(Errors.format(Errors.Keys.UnknownType_1, type));
     }
 
@@ -514,6 +657,23 @@ public class StorageConnector implements
     }
 
     /**
+     * Declares that the given {@code input} will need to be closed by the {@link #closeAllExcept(Object)} method.
+     * The {@code input} argument is always a new instance wrapping, directly or indirectly, the {@link #storage}.
+     * Callers must specify the wrapped object in the {@code delegate} argument.
+     *
+     * @param input    The newly created object which will need to be closed.
+     * @param delegate The object wrapped by the given {@code input}.
+     */
+    private void addViewToClose(final Object input, final Object delegate) {
+        if (viewsToClose == null) {
+            viewsToClose = new IdentityHashMap<Object,Object>(4);
+        }
+        if (viewsToClose.put(input, delegate) != null) {
+            throw new AssertionError(input);
+        }
+    }
+
+    /**
      * Closes all streams and connections created by this {@code StorageConnector} except the given view.
      * This method closes all objects created by the {@link #getStorageAs(Class)} method except the given {@code view}.
      * If {@code view} is {@code null}, then this method closes everything including the {@linkplain #getStorage()
@@ -532,37 +692,86 @@ public class StorageConnector implements
      * @see DataStoreProvider#open(StorageConnector)
      */
     public void closeAllExcept(final Object view) throws DataStoreException {
+        final Map<Object,Object> toClose = viewsToClose;
+        viewsToClose = Collections.emptyMap();
+        views        = Collections.emptyMap();
+        if (toClose == null) {
+            if (storage != view && JDK7.isAutoCloseable(storage)) try {
+                JDK7.close(storage);
+            } catch (Exception e) {
+                throw new DataStoreException(e);
+            }
+            return;
+        }
         /*
-         * Need a set of objects to close without duplicated values. In particular, the value for
-         * DataInput and ImageInputStream are often the same instance. We must avoid duplicated
-         * values because ImageInputStream.close() is not indempotent.
+         * The "AutoCloseable.close() is not indempotent" problem
+         * ------------------------------------------------------
+         * We will need a set of objects to close without duplicated values. For example the values associated to the
+         * 'ImageInputStream.class' and 'DataInput.class' keys are often the same instance.  We must avoid duplicated
+         * values because 'ImageInputStream.close()' is not indempotent,  i.e.  invoking their 'close()' method twice
+         * will thrown an IOException.
+         *
+         * Generally speaking, all AutoCloseable instances are not guaranteed to be indempotent because this is not
+         * required by the interface contract. Consequently we must be careful to not invoke the close() method on
+         * the same instance twice (indirectly or indirectly).
+         *
+         * The set of objects to close will be the keys of the 'viewsToClose' map. It can not be the values of the
+         * 'views' map.
          */
-        final Map<Object,Object> toClose = new IdentityHashMap<Object,Object>(4);
-        for (final Object value : views.values()) {
-            if (JDK7.isAutoCloseable(value)) {
-                toClose.put(value, null);
-            }
+        toClose.put(storage, null);
+        if (view != null) {
+            /*
+             * If there is a view to not close, search for all views that are wrapper for the given view.
+             * Those wrappers shall not be closed. For example if the caller does not want to close the
+             * InputStream view, then we shall not close the InputStreamReader wrapper neither.
+             */
+            final Queue<Object> deferred = new LinkedList<Object>();
+            Object doNotClose = view;
+            do {
+                final Iterator<Map.Entry<Object,Object>> it = toClose.entrySet().iterator();
+                while (it.hasNext()) {
+                    final Map.Entry<Object,Object> entry = it.next();
+                    if (entry.getValue() == doNotClose) {
+                        deferred.add(entry.getKey());
+                        it.remove();
+                    }
+                }
+                doNotClose = deferred.poll();
+            } while (doNotClose != null);
         }
-        toClose.remove(view);
-        toClose.remove(storage);
-        try {
-            if (!toClose.isEmpty()) {
-                for (final Object value : toClose.keySet()) {
-                    JDK7.close(value);
+        /*
+         * Remove the view to not close. If that view is a wrapper for an other object, do not close the
+         * wrapped object neither. Proceed the dependency chain up to the original 'storage' object.
+         */
+        for (Object doNotClose = view; doNotClose != null;) {
+            doNotClose = toClose.remove(doNotClose);
+        }
+        /*
+         * Remove all wrapped objects. After this loop, only the "top level" objects should remain
+         * (typically only one object). This block is needed because of the "AutoCloseable.close()
+         * is not idempotent" issue, otherwise we could have omitted it.
+         */
+        for (final Object delegate : toClose.values().toArray()) { // 'toArray()' is for avoiding ConcurrentModificationException.
+            toClose.remove(delegate);
+        }
+        /*
+         * Now close all remaining items. If an exception occurs, we will propagate it only after we are
+         * done closing all items.
+         */
+        DataStoreException failure = null;
+        for (final Object c : toClose.keySet()) {
+            if (JDK7.isAutoCloseable(c)) try {
+                JDK7.close(c);
+            } catch (Exception e) {
+                if (failure == null) {
+                    failure = new DataStoreException(e);
+                } else {
+                    // failure.addSuppressed(e) on the JDK7 branch.
                 }
-            } else if (view == null && JDK7.isAutoCloseable(storage)) {
-                /*
-                 * Close only if we didn't closed a view because closing an input stream view
-                 * automatically close the 'storage' if the former is a wrapper for the later.
-                 * Since AutoCloseable.close() is not guaranteed to be indempotent, we should
-                 * avoid to call it (indirectly) twice.
-                 */
-                JDK7.close(storage);
             }
-        } catch (Exception e) {
-            throw new DataStoreException(e);
-        } finally {
-            views = Collections.emptyMap();
+        }
+        if (failure != null) {
+            throw failure;
         }
     }
 

Modified: sis/trunk/storage/sis-storage/src/test/java/org/apache/sis/internal/storage/ChannelDataInputTest.java
URL: http://svn.apache.org/viewvc/sis/trunk/storage/sis-storage/src/test/java/org/apache/sis/internal/storage/ChannelDataInputTest.java?rev=1511687&r1=1511686&r2=1511687&view=diff
==============================================================================
--- sis/trunk/storage/sis-storage/src/test/java/org/apache/sis/internal/storage/ChannelDataInputTest.java [UTF-8] (original)
+++ sis/trunk/storage/sis-storage/src/test/java/org/apache/sis/internal/storage/ChannelDataInputTest.java [UTF-8] Thu Aug  8 10:50:57 2013
@@ -22,7 +22,6 @@ import java.io.DataInputStream;
 import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.nio.ByteBuffer;
-import java.nio.channels.Channels;
 import org.apache.sis.test.TestUtilities;
 import org.apache.sis.test.TestCase;
 import org.junit.Test;
@@ -36,7 +35,7 @@ import static org.junit.Assert.*;
  *
  * @author  Martin Desruisseaux (Geomatys)
  * @since   0.3 (derived from geotk-3.07)
- * @version 0.3
+ * @version 0.4
  * @module
  */
 public final strictfp class ChannelDataInputTest extends TestCase {
@@ -46,6 +45,20 @@ public final strictfp class ChannelDataI
     private static final int ARRAY_MAX_SIZE = 256;
 
     /**
+     * Creates an array filled with random values.
+     *
+     * @param length The length of the array to create.
+     * @param random The random number generator to use.
+     */
+    static byte[] createRandomArray(final int length, final Random random) {
+        final byte[] array = new byte[length];
+        for (int i=0; i<length; i++) {
+            array[i] = (byte) random.nextInt(256);
+        }
+        return array;
+    }
+
+    /**
      * Fills a buffer with random data and compare the result with a standard image input stream.
      * We allocate a small buffer for the {@code ChannelDataInput} in order to force frequent
      * interactions between the buffer and the channel.
@@ -59,7 +72,7 @@ public final strictfp class ChannelDataI
         compareStreamToBuffer(random, array.length,
                 new DataInputStream(new ByteArrayInputStream(array)),
                 new ChannelDataInput("testAllReadMethods",
-                    Channels.newChannel(new ByteArrayInputStream(array)),
+                    new DripByteChannel(array, random, 1, 1024),
                     ByteBuffer.allocate(random.nextInt(ARRAY_MAX_SIZE / 4) + (Double.SIZE / Byte.SIZE)), false));
     }
 
@@ -149,11 +162,12 @@ public final strictfp class ChannelDataI
      */
     @Test
     public void testReadString() throws IOException {
+        final Random random   = TestUtilities.createRandomNumberGenerator("testReadString");
         final String expected = "お元気ですか";
-        final byte[] array = expected.getBytes("UTF-8");
+        final byte[] array    = expected.getBytes("UTF-8");
         assertEquals(expected.length()*3, array.length); // Sanity check.
         final ChannelDataInput input = new ChannelDataInput("testReadString",
-                Channels.newChannel(new ByteArrayInputStream(array)),
+                new DripByteChannel(array, random, 1, 32),
                 ByteBuffer.allocate(array.length + 4), false);
         assertEquals(expected, input.readString(array.length, "UTF-8"));
         assertFalse(input.buffer.hasRemaining());
@@ -173,7 +187,7 @@ public final strictfp class ChannelDataI
         length -= (Long.SIZE / Byte.SIZE); // Safety against buffer underflow.
         final ByteBuffer buffer = ByteBuffer.wrap(array);
         final ChannelDataInput input = new ChannelDataInput("testSeekOnForwardOnlyChannel",
-                Channels.newChannel(new ByteArrayInputStream(array)),
+                new DripByteChannel(array, random, 1, 2048),
                 ByteBuffer.allocate(random.nextInt(64) + 16), false);
         int position = 0;
         while (position < length) {
@@ -185,16 +199,46 @@ public final strictfp class ChannelDataI
     }
 
     /**
-     * Creates an array filled with random values.
+     * Tests {@link ChannelDataInput#prefetch()}.
      *
-     * @param length The length of the array to create.
-     * @param random The random number generator to use.
+     * @throws IOException Should never happen.
      */
-    static byte[] createRandomArray(final int length, final Random random) {
-        final byte[] array = new byte[length];
-        for (int i=0; i<length; i++) {
-            array[i] = (byte) random.nextInt(256);
+    @Test
+    public void testPrefetch() throws IOException {
+        final Random     random = TestUtilities.createRandomNumberGenerator("testPrefetch");
+        final int        length = random.nextInt(256) + 128;
+        final byte[]     array  = createRandomArray(length, random);
+        final ByteBuffer buffer = ByteBuffer.allocate(random.nextInt(64) + 16);
+        final ChannelDataInput input = new ChannelDataInput("testPrefetch",
+                new DripByteChannel(array, random, 1, 64), buffer, false);
+        int position = 0;
+        while (position != length) {
+            if (random.nextBoolean()) {
+                assertEquals(array[position++], input.readByte());
+            }
+            /*
+             * Prefetch a random amount of bytes and verifies the buffer status.
+             */
+            final int p = buffer.position();
+            final int m = buffer.limit();
+            final int n = input.prefetch();
+            assertEquals("Position shall be unchanged.", p, buffer.position());
+            final int limit = buffer.limit();
+            if (n >= 0) {
+                // Usual case.
+                assertTrue("Limit shall be increased.", limit > m);
+            } else {
+                // Buffer is full or channel reached the end of stream.
+                assertEquals("Limit shall be unchanged", m, limit);
+            }
+            /*
+             * Compare the buffer content with the original data array. The comparison starts
+             * from the buffer begining, in order to ensure that previous data are unchanged.
+             */
+            final int offset = position - buffer.position();
+            for (int i=0; i<limit; i++) {
+                assertEquals(array[offset + i], buffer.get(i));
+            }
         }
-        return array;
     }
 }

Modified: sis/trunk/storage/sis-storage/src/test/java/org/apache/sis/storage/StorageConnectorTest.java
URL: http://svn.apache.org/viewvc/sis/trunk/storage/sis-storage/src/test/java/org/apache/sis/storage/StorageConnectorTest.java?rev=1511687&r1=1511686&r2=1511687&view=diff
==============================================================================
--- sis/trunk/storage/sis-storage/src/test/java/org/apache/sis/storage/StorageConnectorTest.java [UTF-8] (original)
+++ sis/trunk/storage/sis-storage/src/test/java/org/apache/sis/storage/StorageConnectorTest.java [UTF-8] Thu Aug  8 10:50:57 2013
@@ -17,11 +17,15 @@
 package org.apache.sis.storage;
 
 import java.io.DataInput;
+import java.io.InputStream;
+import java.io.Reader;
 import java.io.IOException;
 import java.nio.ByteBuffer;
 import java.nio.channels.ReadableByteChannel;
 import javax.imageio.ImageIO;
 import javax.imageio.stream.ImageInputStream;
+import java.sql.Connection;
+import org.apache.sis.setup.OptionKey;
 import org.apache.sis.internal.storage.ChannelDataInput;
 import org.apache.sis.internal.storage.ChannelImageInputStream;
 import org.apache.sis.test.DependsOnMethod;
@@ -37,7 +41,7 @@ import static org.opengis.test.Assert.*;
  *
  * @author  Martin Desruisseaux (Geomatys)
  * @since   0.3
- * @version 0.3
+ * @version 0.4
  * @module
  */
 @DependsOn(org.apache.sis.internal.storage.ChannelImageInputStreamTest.class)
@@ -56,7 +60,9 @@ public final strictfp class StorageConne
         final String name = c.getSimpleName() + ".class";
         final Object storage = asStream ? c.getResourceAsStream(name) : c.getResource(name);
         assertNotNull(storage);
-        return new StorageConnector(storage);
+        final StorageConnector connector = new StorageConnector(storage);
+        connector.setOption(OptionKey.URL_ENCODING, "UTF-8");
+        return connector;
     }
 
     /**
@@ -149,6 +155,50 @@ public final strictfp class StorageConne
     }
 
     /**
+     * Tests the {@link StorageConnector#getStorageAs(Class)} method for the {@link InputStream} type.
+     *
+     * @throws DataStoreException Should never happen.
+     * @throws IOException If an error occurred while reading the test file.
+     */
+    @Test
+    @DependsOnMethod("testGetAsImageInputStream")
+    public void testGetAsInputStream() throws DataStoreException, IOException {
+        StorageConnector connection = create(true);
+        InputStream in = connection.getStorageAs(InputStream.class);
+        assertSame(connection.getStorage(), in);
+        connection.closeAllExcept(null);
+
+        connection = create(false);
+        in = connection.getStorageAs(InputStream.class);
+        assertNotSame(connection.getStorage(), in);
+        assertSame("Expected cached value.", in, connection.getStorageAs(InputStream.class));
+        assertInstanceOf("Expected Channel backend", InputStreamAdapter.class, in);
+        assertInstanceOf("Expected Channel backend", ChannelImageInputStream.class, ((InputStreamAdapter) in).input);
+        assertSame(((InputStreamAdapter) in).input, connection.getStorageAs(DataInput.class));
+        assertSame(((InputStreamAdapter) in).input, connection.getStorageAs(ImageInputStream.class));
+
+        final ReadableByteChannel channel = ((ChannelImageInputStream) ((InputStreamAdapter) in).input).channel;
+        assertTrue(channel.isOpen());
+        connection.closeAllExcept(null);
+        assertFalse(channel.isOpen());
+    }
+
+    /**
+     * Tests the {@link StorageConnector#getStorageAs(Class)} method for the {@link Reader} type.
+     *
+     * @throws DataStoreException Should never happen.
+     * @throws IOException If an error occurred while reading the test file.
+     */
+    @Test
+    @DependsOnMethod("testGetAsInputStream")
+    public void testGetAsReader() throws DataStoreException, IOException {
+        StorageConnector connection = create(true);
+        final Reader in = connection.getStorageAs(Reader.class);
+        assertSame("Expected cached value.", in, connection.getStorageAs(Reader.class));
+        connection.closeAllExcept(null);
+    }
+
+    /**
      * Tests the {@link StorageConnector#getStorageAs(Class)} method for the {@link ChannelDataInput} type.
      * The initial value should not be an instance of {@link ChannelImageInputStream} in order to avoid initializing
      * the Image I/O classes. However after a call to {@code getStorageAt(ChannelImageInputStream.class)}, the type
@@ -213,12 +263,24 @@ public final strictfp class StorageConne
 
         final ByteBuffer buffer = connection.getStorageAs(ByteBuffer.class);
         assertNotNull("getStorageAs(ByteBuffer.class)", buffer);
-        assertTrue(buffer.capacity() < StorageConnector.DEFAULT_BUFFER_SIZE);
+        assertEquals(StorageConnector.MINIMAL_BUFFER_SIZE, buffer.capacity());
         assertEquals(MAGIC_NUMBER, buffer.getInt());
         connection.closeAllExcept(null);
     }
 
     /**
+     * Tests the {@link StorageConnector#getStorageAs(Class)} method for the {@link Connection} type.
+     *
+     * @throws DataStoreException Should never happen.
+     * @throws IOException Should never happen.
+     */
+    public void testGetAsConnection() throws DataStoreException, IOException {
+        final StorageConnector connection = create(false);
+        assertNull(connection.getStorageAs(Connection.class));
+        connection.closeAllExcept(null);
+    }
+
+    /**
      * Tests the {@link StorageConnector#closeAllExcept(Object)} method.
      *
      * @throws DataStoreException Should never happen.

Modified: sis/trunk/storage/sis-storage/src/test/java/org/apache/sis/test/suite/StorageTestSuite.java
URL: http://svn.apache.org/viewvc/sis/trunk/storage/sis-storage/src/test/java/org/apache/sis/test/suite/StorageTestSuite.java?rev=1511687&r1=1511686&r2=1511687&view=diff
==============================================================================
--- sis/trunk/storage/sis-storage/src/test/java/org/apache/sis/test/suite/StorageTestSuite.java [UTF-8] (original)
+++ sis/trunk/storage/sis-storage/src/test/java/org/apache/sis/test/suite/StorageTestSuite.java [UTF-8] Thu Aug  8 10:50:57 2013
@@ -26,7 +26,7 @@ import org.junit.BeforeClass;
  *
  * @author  Martin Desruisseaux (Geomatys)
  * @since   0.3
- * @version 0.3
+ * @version 0.4
  * @module
  */
 @Suite.SuiteClasses({
@@ -34,6 +34,8 @@ import org.junit.BeforeClass;
     org.apache.sis.internal.storage.ChannelDataInputTest.class,
     org.apache.sis.internal.storage.ChannelImageInputStreamTest.class,
     org.apache.sis.storage.StorageConnectorTest.class,
+    org.apache.sis.internal.storage.xml.XMLStoreProviderTest.class,
+    org.apache.sis.internal.storage.xml.XMLStoreTest.class,
     org.apache.sis.index.GeoHashCoderTest.class
 })
 public final strictfp class StorageTestSuite extends TestSuite {