sis-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From desruisse...@apache.org
Subject svn commit: r1487611 - in /sis/branches/JDK7: core/sis-utility/src/main/java/org/apache/sis/util/ storage/sis-storage/src/main/java/org/apache/sis/internal/storage/ storage/sis-storage/src/test/java/org/apache/sis/internal/storage/ storage/sis-storage/...
Date Wed, 29 May 2013 19:41:46 GMT
Author: desruisseaux
Date: Wed May 29 19:41:45 2013
New Revision: 1487611

URL: http://svn.apache.org/r1487611
Log:
Ported IOUtilities internal methods.

Added:
    sis/branches/JDK7/storage/sis-storage/src/main/java/org/apache/sis/internal/storage/IOUtilities.java
  (with props)
    sis/branches/JDK7/storage/sis-storage/src/test/java/org/apache/sis/internal/storage/IOUtilitiesTest.java
  (with props)
Modified:
    sis/branches/JDK7/core/sis-utility/src/main/java/org/apache/sis/util/Exceptions.java
    sis/branches/JDK7/storage/sis-storage/src/test/java/org/apache/sis/test/suite/StorageTestSuite.java

Modified: sis/branches/JDK7/core/sis-utility/src/main/java/org/apache/sis/util/Exceptions.java
URL: http://svn.apache.org/viewvc/sis/branches/JDK7/core/sis-utility/src/main/java/org/apache/sis/util/Exceptions.java?rev=1487611&r1=1487610&r2=1487611&view=diff
==============================================================================
--- sis/branches/JDK7/core/sis-utility/src/main/java/org/apache/sis/util/Exceptions.java [UTF-8]
(original)
+++ sis/branches/JDK7/core/sis-utility/src/main/java/org/apache/sis/util/Exceptions.java [UTF-8]
Wed May 29 19:41:45 2013
@@ -110,7 +110,7 @@ public final class Exceptions extends St
      * {@linkplain Throwable#getLocalizedMessage() localized message} of the given exception
      * on the next line. If the exception has a {@linkplain Throwable#getCause() causes},
then
      * the localized message of the cause is formatted on the next line and the process is
-     * repeated for the whole cause chain.
+     * repeated for the whole cause chain, omitting duplicated messages.
      *
      * <p>{@link SQLException} is handled especially in order to process the
      * {@linkplain SQLException#getNextException() next exception} instead than the cause.</p>

Added: sis/branches/JDK7/storage/sis-storage/src/main/java/org/apache/sis/internal/storage/IOUtilities.java
URL: http://svn.apache.org/viewvc/sis/branches/JDK7/storage/sis-storage/src/main/java/org/apache/sis/internal/storage/IOUtilities.java?rev=1487611&view=auto
==============================================================================
--- sis/branches/JDK7/storage/sis-storage/src/main/java/org/apache/sis/internal/storage/IOUtilities.java
(added)
+++ sis/branches/JDK7/storage/sis-storage/src/main/java/org/apache/sis/internal/storage/IOUtilities.java
[UTF-8] Wed May 29 19:41:45 2013
@@ -0,0 +1,404 @@
+/*
+ * 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.internal.storage;
+
+import java.util.Locale;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStream;
+import java.io.IOException;
+import java.net.URI;
+import java.net.URL;
+import java.net.URLDecoder;
+import java.net.URISyntaxException;
+import java.net.MalformedURLException;
+import java.nio.file.Path;
+import java.nio.file.Files;
+import java.nio.channels.Channels;
+import java.nio.channels.ReadableByteChannel;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.FileSystemNotFoundException;
+import java.nio.file.Paths;
+import org.apache.sis.util.CharSequences;
+import org.apache.sis.util.Exceptions;
+import org.apache.sis.util.Static;
+import org.apache.sis.util.resources.Errors;
+
+
+/**
+ * Utility methods related to I/O operations. Many methods in this class accept arbitrary
{@link Object} argument
+ * and perform a sequence of {@code instanceof} checks. Since this approach provides no type
safety and since the
+ * sequence of {@code instanceof} checks is somewhat arbitrary, those methods can not be
in public API.
+ *
+ * <p>Unless otherwise specified, giving an instance of unknown type or a {@code null}
value cause the methods to
+ * return {@code null}. No exception is thrown for unknown type - callers must check that
the return value is not
+ * null. However exceptions may be thrown for malformed URI or URL.</p>
+ *
+ * @author  Martin Desruisseaux (Geomatys)
+ * @author  Johann Sorel (Geomatys)
+ * @since   0.3 (derived from geotk-3.00)
+ * @version 0.3
+ * @module
+ */
+public final class IOUtilities extends Static {
+    /**
+     * Do not allow instantiation of this class.
+     */
+    private IOUtilities() {
+    }
+
+    /**
+     * Returns the filename from a {@link Path}, {@link File}, {@link URL}, {@link URI} or
{@link CharSequence}
+     * instance. If the given argument is specialized type like {@code Path} or {@code File},
then this method uses
+     * dedicated API like {@link Path#getFileName()}. Otherwise this method gets a string
representation of the path
+     * and returns the part after the last {@code '/'} or platform-dependent name separator
character, if any.
+     *
+     * @param  path The path as an instance of one of the above-cited types, or {@code null}.
+     * @return The filename in the given path, or {@code null} if the given object is null
or of unknown type.
+     */
+    public static String filename(final Object path) {
+        return part(path, false);
+    }
+
+    /**
+     * Returns the filename extension from a {@link Path}, {@link File}, {@link URL}, {@link
URI} or
+     * {@link CharSequence} instance. If no extension is found, returns an empty string.
If the given
+     * object is of unknown type, return {@code null}.
+     *
+     * @param  path The path as an instance of one of the above-cited types, or {@code null}.
+     * @return The extension in the given path, or an empty string if none, or {@code null}
+     *         if the given object is null or of unknown type.
+     */
+    public static String extension(final Object path) {
+        return part(path, true);
+    }
+
+    /**
+     * Implementation of {@link #filename(Object)} and {@link #extension(Object)} methods.
+     */
+    private static String part(final Object path, final boolean extension) {
+        int fromIndex = 0;
+        final String name;
+        if (path instanceof File) {
+            name = ((File) path).getName();
+        } else if (path instanceof Path) {
+            name = ((Path) path).getFileName().toString();
+        } else {
+            char separator = '/';
+            if (path instanceof URL) {
+                name = ((URL) path).getPath();
+            } else if (path instanceof URI) {
+                name = ((URI) path).getPath();
+            } else if (path instanceof CharSequence) {
+                name = path.toString();
+                separator = File.separatorChar;
+            } else {
+                return null;
+            }
+            fromIndex = name.lastIndexOf('/') + 1;
+            if (separator != '/') {
+                // Search for platform-specific character only if the object is neither a
URL or a URI.
+                fromIndex = Math.max(fromIndex, CharSequences.lastIndexOf(name, separator,
fromIndex, name.length()) + 1);
+            }
+        }
+        if (extension) {
+            fromIndex = CharSequences.lastIndexOf(name, '.', fromIndex, name.length()) +
1;
+            if (fromIndex <= 1) { // If the dot is the first character, do not consider
as a filename extension.
+                return "";
+            }
+        }
+        return name.substring(fromIndex);
+    }
+
+    /**
+     * Encodes the characters that are not legal for the {@link URI#URI(String)} constructor.
+     * Note that in addition to unreserved characters ("{@code _-!.~'()*}"), the reserved
+     * characters ("{@code ?/[]@}") and the punctuation characters ("{@code ,;:$&+=}")
+     * are left unchanged, so they will be processed with their special meaning by the
+     * URI constructor.
+     *
+     * <p>The current implementations replaces only the space characters, control characters
+     * and the {@code %} character. Future versions may replace more characters as we learn
+     * from experience.</p>
+     *
+     * @param  path The path to encode, or {@code null}.
+     * @return The encoded path, or {@code null} if and only if the given path was null.
+     */
+    public static String encodeURI(final String path) {
+        if (path == null) {
+            return null;
+        }
+        StringBuilder buffer = null;
+        final int length = path.length();
+        for (int i=0; i<length;) {
+            final int c = path.codePointAt(i);
+            final int n = Character.charCount(c);
+            if (!Character.isSpaceChar(c) && !Character.isISOControl(c) &&
c != '%') {
+                /*
+                 * The character is valid, or is punction character, or is a reserved character.
+                 * All those characters should be handled properly by the URI(String) constructor.
+                 */
+                if (buffer != null) {
+                    buffer.appendCodePoint(c);
+                }
+            } else {
+                /*
+                 * The character is invalid, so we need to escape it. Note that the encoding
+                 * is fixed to UTF-8 as of java.net.URI specification (see its class javadoc).
+                 */
+                if (buffer == null) {
+                    buffer = new StringBuilder(path);
+                    buffer.setLength(i);
+                }
+                for (final byte b : path.substring(i, i+n).getBytes(StandardCharsets.UTF_8))
{
+                    buffer.append('%');
+                    final String hex = Integer.toHexString(b & 0xFF).toUpperCase(Locale.ROOT);
+                    if (hex.length() < 2) {
+                        buffer.append('0');
+                    }
+                    buffer.append(hex);
+                }
+            }
+            i += n;
+        }
+        return (buffer != null) ? buffer.toString() : path;
+    }
+
+    /**
+     * Converts a {@link URL} to a {@link URI}. This is equivalent to a call to the standard
{@link URL#toURI()}
+     * method, except for the following functionalities:
+     *
+     * <ul>
+     *   <li>Optionally decodes the {@code "%XX"} sequences, where {@code "XX"} is
a number.</li>
+     *   <li>Converts various exceptions into subclasses of {@link IOException}.</li>
+     * </ul>
+     *
+     * @param  url The URL to convert, or {@code null}.
+     * @param  encoding If the URL is encoded in a {@code application/x-www-form-urlencoded}
+     *         MIME format, the character encoding (normally {@code "UTF-8"}). If the URL
is
+     *         not encoded, then {@code null}.
+     * @return The URI for the given URL, or {@code null} if the given URL was null.
+     * @throws IOException if the URL can not be converted to a URI.
+     *
+     * @see URI#URI(String)
+     */
+    public static URI toURI(final URL url, final String encoding) throws IOException {
+        if (url == null) {
+            return null;
+        }
+        /*
+         * Convert the URL to an URI, taking in account the encoding if any.
+         *
+         * Note: URL.toURI() is implemented as new URI(URL.toString()) where toString()
+         * delegates to toExternalForm(), and all those methods are final. So we really
+         * don't lost anything by doing those steps ourself.
+         */
+        String path = url.toExternalForm();
+        if (encoding != null) {
+            path = URLDecoder.decode(path, encoding);
+        }
+        path = encodeURI(path);
+        try {
+            return new URI(path);
+        } catch (URISyntaxException cause) {
+            /*
+             * Occurs only if the URL is not compliant with RFC 2396. Otherwise every URL
+             * should succeed, so a failure can actually be considered as a malformed URL.
+             */
+            final MalformedURLException e = new MalformedURLException(Exceptions.formatChainedMessages(
+                    null, Errors.format(Errors.Keys.IllegalArgumentValue_2, "URL", path),
cause));
+            e.initCause(cause);
+            throw e;
+        }
+    }
+
+    /**
+     * Converts a {@link URL} to a {@link File}. This is equivalent to a call to the standard
+     * {@link URL#toURI()} method followed by a call to the {@link File#File(URI)} constructor,
+     * except for the following functionalities:
+     *
+     * <ul>
+     *   <li>Optionally decodes the {@code "%XX"} sequences, where {@code "XX"} is
a number.</li>
+     *   <li>Converts various exceptions into subclasses of {@link IOException}.</li>
+     * </ul>
+     *
+     * @param  url The URL to convert, or {@code null}.
+     * @param  encoding If the URL is encoded in a {@code application/x-www-form-urlencoded}
+     *         MIME format, the character encoding (normally {@code "UTF-8"}). If the URL
is
+     *         not encoded, then {@code null}.
+     * @return The file for the given URL, or {@code null} if the given URL was null.
+     * @throws IOException if the URL can not be converted to a file.
+     *
+     * @see File#File(URI)
+     */
+    public static File toFile(final URL url, final String encoding) throws IOException {
+        if (url == null) {
+            return null;
+        }
+        final URI uri = toURI(url, encoding);
+        /*
+         * We really want to call the File constructor expecting a URI argument,
+         * not the constructor expecting a String argument, because the one for
+         * the URI argument performs additional platform-specific parsing.
+         */
+        try {
+            return new File(uri);
+        } catch (IllegalArgumentException cause) {
+            /*
+             * Typically happen when the URI contains fragment that can not be represented
+             * in a File (e.g. a Query part), so it could be considered as if the URI with
+             * the fragment part can not represent an existing file.
+             */
+            final MalformedURLException e = new MalformedURLException(Exceptions.formatChainedMessages(
+                    null, Errors.format(Errors.Keys.IllegalArgumentValue_2, "URL", url),
cause));
+            e.initCause(cause);
+            throw e;
+        }
+    }
+
+    /**
+     * Converts a {@link URL} to a {@link Path}. This is equivalent to a call to the standard
+     * {@link URL#toURI()} method followed by a call to the {@link Paths#get(URI)} static
method,
+     * except for the following functionalities:
+     *
+     * <ul>
+     *   <li>Optionally decodes the {@code "%XX"} sequences, where {@code "XX"} is
a number.</li>
+     *   <li>Converts various exceptions into subclasses of {@link IOException}.</li>
+     * </ul>
+     *
+     * @param  url The URL to convert, or {@code null}.
+     * @param  encoding If the URL is encoded in a {@code application/x-www-form-urlencoded}
+     *         MIME format, the character encoding (normally {@code "UTF-8"}). If the URL
is
+     *         not encoded, then {@code null}.
+     * @return The path for the given URL, or {@code null} if the given URL was null.
+     * @throws IOException if the URL can not be converted to a path.
+     *
+     * @see Paths#get(URI)
+     */
+    public static Path toPath(final URL url, final String encoding) throws IOException {
+        if (url == null) {
+            return null;
+        }
+        final URI uri = toURI(url, encoding);
+        try {
+            return Paths.get(uri);
+        } catch (IllegalArgumentException | FileSystemNotFoundException cause) {
+            final MalformedURLException e = new MalformedURLException(Exceptions.formatChainedMessages(
+                    null, Errors.format(Errors.Keys.IllegalArgumentValue_2, "URL", url),
cause));
+            e.initCause(cause);
+            throw e;
+        }
+    }
+
+    /**
+     * Parses the following path as a {@link File} if possible, or a {@link URL} otherwise.
+     * In the special case where the given {@code path} is a URL using the {@code "file"}
protocol,
+     * the URL is converted to a {@link File} object using the given {@code encoding} for
decoding
+     * the {@code "%XX"} sequences, if any.
+     *
+     * {@section Rational}
+     * A URL can represent a file, but {@link URL#openStream()} appears to return a {@code
BufferedInputStream}
+     * wrapping the {@link FileInputStream}, which is not a desirable feature when we want
to obtain a channel.
+     *
+     * <p>There is no {@code toPathOrURL} methods because {@link Path} can be associated
to various file systems.
+     * It would be possible (not necessarily desirable, but at least doable) do create {@code
Path} for HTTP or
+     * FTP protocols.</p>
+     *
+     * @param  path The path to convert, or {@code null}.
+     * @param  encoding If the URL is encoded in a {@code application/x-www-form-urlencoded}
+     *         MIME format, the character encoding (normally {@code "UTF-8"}). If the URL
is
+     *         not encoded, then {@code null}. This argument is ignored if the given path
does
+     *         not need to be converted from URL to {@code File}.
+     * @return The path as a {@link File} if possible, or a {@link URL} otherwise.
+     * @throws IOException If the given path is not a file and can't be parsed as a URL.
+     */
+    public static Object toFileOrURL(final String path, final String encoding) throws IOException
{
+        if (path == null) {
+            return null;
+        }
+        // Check if the path seems to be an ordinary file.
+        if (path.indexOf('?') < 0 && path.indexOf('#') < 0) {
+            final int s = path.indexOf(':');
+            /*
+             * If the ':' character is found, the part before it is probably a protocol in
a URL,
+             * except in the particular case where there is just one letter before ':'. In
such
+             * case, it may be the drive letter of a Windows file.
+             */
+            if (s<0 || (s==1 && Character.isLetter(path.charAt(0)) &&
!path.regionMatches(2, "//", 0, 2))) {
+                return new File(path);
+            }
+        }
+        final URL url = new URL(path);
+        if (url.getProtocol().equalsIgnoreCase("file")) {
+            return toFile(url, encoding);
+        }
+        return url;
+    }
+
+    /**
+     * Returns a byte channel from the given input, or {@code null} if the input is of unknown
type.
+     * More specifically:
+     *
+     * <ul>
+     *   <li>If the given input is {@code null}, then this method returns {@code null}.</li>
+     *   <li>If the given input is a {@link ReadableByteChannel} or an {@link InputStream},
+     *       then it is returned directly, or indirectly as a wrapper.</li>
+     *   <li>If the given input if a {@link Path}, {@link File}, {@link URL}, {@link
URI}
+     *       or {@link CharSequence}, then a new channel is opened.</li>
+     * </ul>
+     *
+     * @param  input The file to open, or {@code null}.
+     * @param  encoding If the URL is encoded in a {@code application/x-www-form-urlencoded}
+     *         MIME format, the character encoding (normally {@code "UTF-8"}). If the URL
is
+     *         not encoded, then {@code null}. This argument is ignored if the given path
does
+     *         not need to be converted from URL to {@code File}.
+     * @return The input stream for the given file, or {@code null} if the given type is
unknown.
+     * @throws IOException If an error occurred while opening the given file.
+     */
+    public static ReadableByteChannel open(Object input, final String encoding) throws IOException
{
+        if (input instanceof ReadableByteChannel) {
+            return (ReadableByteChannel) input;
+        }
+        if (input instanceof InputStream) {
+            /*
+             * Channels.newChannel(InputStream) checks for FileInputStream, but it requires
that exact class.
+             * Concequently we have to perform our own check if we want to allow any FileInputStream
subclass
+             * to have their 'getChannel()' method invoked.
+             */
+            if (input instanceof FileInputStream) {
+                return ((FileInputStream) input).getChannel();
+            }
+            return Channels.newChannel((InputStream) input);
+        }
+        if (input instanceof Path) {
+            return Files.newByteChannel((Path) input);
+        }
+        if (input instanceof CharSequence) { // Needs to be before the check for File or
URL.
+            input = toFileOrURL(input.toString(), encoding);
+        }
+        if (input instanceof File) {
+            return new FileInputStream((File) input).getChannel();
+        }
+        if (input instanceof URI) { // Needs to be before the check for URL.
+            input = ((URI) input).toURL();
+        }
+        if (input instanceof URL) {
+            return Channels.newChannel(((URL) input).openStream());
+        }
+        return null;
+    }
+}

Propchange: sis/branches/JDK7/storage/sis-storage/src/main/java/org/apache/sis/internal/storage/IOUtilities.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: sis/branches/JDK7/storage/sis-storage/src/main/java/org/apache/sis/internal/storage/IOUtilities.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain;charset=UTF-8

Added: sis/branches/JDK7/storage/sis-storage/src/test/java/org/apache/sis/internal/storage/IOUtilitiesTest.java
URL: http://svn.apache.org/viewvc/sis/branches/JDK7/storage/sis-storage/src/test/java/org/apache/sis/internal/storage/IOUtilitiesTest.java?rev=1487611&view=auto
==============================================================================
--- sis/branches/JDK7/storage/sis-storage/src/test/java/org/apache/sis/internal/storage/IOUtilitiesTest.java
(added)
+++ sis/branches/JDK7/storage/sis-storage/src/test/java/org/apache/sis/internal/storage/IOUtilitiesTest.java
[UTF-8] Wed May 29 19:41:45 2013
@@ -0,0 +1,160 @@
+/*
+ * 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.internal.storage;
+
+import java.net.URL;
+import java.io.File;
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import org.apache.sis.test.DependsOnMethod;
+import org.apache.sis.test.TestCase;
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+
+/**
+ * Tests the {@link IOUtilities} class.
+ *
+ * @author  Martin Desruisseaux (Geomatys)
+ * @author  Johann Sorel (Geomatys)
+ * @since   0.3 (derived from geotk-3.00)
+ * @version 0.3
+ * @module
+ */
+public final strictfp class IOUtilitiesTest extends TestCase {
+    /**
+     * Tests {@link IOUtilities#filename(Object)}.
+     *
+     * @throws URISyntaxException Should never happen.
+     * @throws MalformedURLException Should never happen.
+     */
+    @Test
+    public void testFilename() throws URISyntaxException, MalformedURLException {
+        assertEquals("Map.png", IOUtilities.filename(              "/Users/name/Map.png"));
+        assertEquals("Map.png", IOUtilities.filename(new File(     "/Users/name/Map.png")));
+        assertEquals("Map.png", IOUtilities.filename(new URI ("file:/Users/name/Map.png")));
+        assertEquals("Map.png", IOUtilities.filename(new URL ("file:/Users/name/Map.png")));
+        assertNull(IOUtilities.filename(Boolean.FALSE));
+        assertNull(IOUtilities.filename(null));
+    }
+
+    /**
+     * Tests {@link IOUtilities#extension(Object)}.
+     *
+     * @throws URISyntaxException Should never happen.
+     * @throws MalformedURLException Should never happen.
+     */
+    @Test
+    @DependsOnMethod("testFilename")
+    public void testExtension() throws URISyntaxException, MalformedURLException {
+        assertEquals("png", IOUtilities.extension(              "/Users/name/Map.png"));
+        assertEquals("png", IOUtilities.extension(new File(     "/Users/name/Map.png")));
+        assertEquals("png", IOUtilities.extension(new URI ("file:/Users/name/Map.png")));
+        assertEquals("png", IOUtilities.extension(new URL ("file:/Users/name/Map.png")));
+        assertEquals("",    IOUtilities.extension(new File(     "/Users/name/Map")));
+        assertEquals("",    IOUtilities.extension(new File(     "/Users/name/.png")));
+        assertNull(IOUtilities.extension(Boolean.FALSE));
+        assertNull(IOUtilities.extension(null));
+    }
+
+    /**
+     * Tests {@link IOUtilities#encodeURI(String)}.
+     */
+    @Test
+    public void testEncodeURI() {
+        assertEquals("/Users/name/Map%20with%20spaces.png", IOUtilities.encodeURI("/Users/name/Map
with spaces.png"));
+        assertNull(IOUtilities.encodeURI(null));
+    }
+
+    /**
+     * Tests {@link IOUtilities#toURI(URL, String)}.
+     *
+     * @throws IOException Should not happen.
+     * @throws URISyntaxException Should not happen.
+     */
+    @Test
+    @DependsOnMethod("testEncodeURI")
+    public void testToURI() throws IOException, URISyntaxException {
+        assertEquals(new URI("file:/Users/name/Map.png"),
+                IOUtilities.toURI(new URL("file:/Users/name/Map.png"), null));
+        assertEquals(new URI("file:/Users/name/Map%20with%20spaces.png"),
+                IOUtilities.toURI(new URL("file:/Users/name/Map with spaces.png"), null));
+        assertEquals(new URI("file:/Users/name/Map%20with%20spaces.png"),
+                IOUtilities.toURI(new URL("file:/Users/name/Map%20with%20spaces.png"), "UTF-8"));
+        assertEquals(new URI("file:/Users/name/Map%20with%20spaces.png"),
+                IOUtilities.toURI(new URL("file:/Users/name/Map%20with%20spaces.png"), "ISO-8859-1"));
+    }
+
+    /**
+     * Tests the {@link IOUtilities#toFile(URL, String)} method. Do not test a Windows-specific
path
+     * (e.g. {@code "file:///C:/some/path/Map.png"}), since the result is different on Windows
or
+     * Unix platforms.
+     *
+     * @throws IOException Should not happen.
+     */
+    @Test
+    @DependsOnMethod("testToURI")
+    public void testToFile() throws IOException {
+        testToFile(null, "+");
+    }
+
+    /**
+     * Same test than {@link #testToFile()}, but using the UTF-8 encoding.
+     *
+     * @throws IOException Should never happen.
+     */
+    @Test
+    @DependsOnMethod("testToFile")
+    public void testToFileFromUTF8() throws IOException {
+        testToFile("UTF-8", "%2B");
+    }
+
+    /**
+     * Implementation of {@link #testToFile()} using the given encoding.
+     * If the encoding is null, then the {@code URLDecoder} will not be used.
+     *
+     * @param  encoding The encoding, or {@code null} if none.
+     * @param  plus The representation for the {@code '+'} sign.
+     * @throws IOException Should not happen.
+     */
+    private void testToFile(final String encoding, final String plus) throws IOException
{
+        assertEquals("Unix absolute path.", new File("/Users/name/Map.png"),
+                IOUtilities.toFile(new URL("file:/Users/name/Map.png"), encoding));
+        assertEquals("Path with space.", new File("/Users/name/Map with spaces.png"),
+                IOUtilities.toFile(new URL("file:/Users/name/Map with spaces.png"), encoding));
+        assertEquals("Path with + sign.", new File("/Users/name/++t--++est.shp"),
+                IOUtilities.toFile(new URL("file:/Users/name/++t--++est.shp".replace("+",
plus)), encoding));
+    }
+
+    /**
+     * Tests {@link IOUtilities#toFileOrURL(String, String)}.
+     *
+     * @throws IOException Should not happen.
+     */
+    @Test
+    @DependsOnMethod("testToFileFromUTF8")
+    public void testToFileOrURL() throws IOException {
+        assertEquals(new File("/Users/name/Map.png"), IOUtilities.toFileOrURL("/Users/name/Map.png",
null));
+        assertEquals(new File("/Users/name/Map.png"), IOUtilities.toFileOrURL("file:/Users/name/Map.png",
null));
+        assertEquals(new URL("http://localhost"),     IOUtilities.toFileOrURL("http://localhost",
null));
+        assertEquals(new File("/Users/name/Map with spaces.png"),
+                IOUtilities.toFileOrURL("file:/Users/name/Map%20with%20spaces.png", "UTF-8"));
+    }
+}

Propchange: sis/branches/JDK7/storage/sis-storage/src/test/java/org/apache/sis/internal/storage/IOUtilitiesTest.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: sis/branches/JDK7/storage/sis-storage/src/test/java/org/apache/sis/internal/storage/IOUtilitiesTest.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain;charset=UTF-8

Modified: sis/branches/JDK7/storage/sis-storage/src/test/java/org/apache/sis/test/suite/StorageTestSuite.java
URL: http://svn.apache.org/viewvc/sis/branches/JDK7/storage/sis-storage/src/test/java/org/apache/sis/test/suite/StorageTestSuite.java?rev=1487611&r1=1487610&r2=1487611&view=diff
==============================================================================
--- sis/branches/JDK7/storage/sis-storage/src/test/java/org/apache/sis/test/suite/StorageTestSuite.java
[UTF-8] (original)
+++ sis/branches/JDK7/storage/sis-storage/src/test/java/org/apache/sis/test/suite/StorageTestSuite.java
[UTF-8] Wed May 29 19:41:45 2013
@@ -30,6 +30,7 @@ import org.junit.BeforeClass;
  * @module
  */
 @Suite.SuiteClasses({
+    org.apache.sis.internal.storage.IOUtilitiesTest.class,
     org.apache.sis.internal.storage.ChannelDataInputTest.class,
     org.apache.sis.internal.storage.ChannelImageInputStreamTest.class
 })



Mime
View raw message