UrlUtil.java

  1. /*******************************************************************************
  2.  * Copyright 2012 André Rouél
  3.  *
  4.  * Licensed under the Apache License, Version 2.0 (the "License");
  5.  * you may not use this file except in compliance with the License.
  6.  * You may obtain a copy of the License at
  7.  *
  8.  *   http://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  * Unless required by applicable law or agreed to in writing, software
  11.  * distributed under the License is distributed on an "AS IS" BASIS,
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  * See the License for the specific language governing permissions and
  14.  * limitations under the License.
  15.  ******************************************************************************/
  16. package net.sf.uadetector.internal.util;

  17. import java.io.BufferedReader;
  18. import java.io.File;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.io.InputStreamReader;
  22. import java.io.Reader;
  23. import java.net.MalformedURLException;
  24. import java.net.URL;
  25. import java.nio.charset.Charset;

  26. import javax.annotation.Nonnull;

  27. import net.sf.qualitycheck.Check;
  28. import net.sf.qualitycheck.exception.IllegalStateOfArgumentException;
  29. import net.sf.uadetector.exception.CanNotOpenStreamException;

  30. /**
  31.  * This class is intended to provide URL utility functions that encapsulate the checked exceptions like
  32.  * {@link MalformedURLException} during the construction of an URL or the {@link IOException} while opening a stream to
  33.  * an {@code URL}.
  34.  *
  35.  * @author André Rouél
  36.  */
  37. public final class UrlUtil {

  38.     /**
  39.      * Creates an {@code URL} instance from the given {@code String} representation.<br>
  40.      * <br>
  41.      * This method tunnels a {@link MalformedURLException} by an {@link IllegalStateOfArgumentException}.
  42.      *
  43.      * @param url
  44.      *            {@code String} representation of an {@code URL}
  45.      * @return new {@code URL} instance
  46.      * @throws net.sf.qualitycheck.exception.IllegalNullArgumentException
  47.      *             if the given argument is {@code null}
  48.      * @throws IllegalStateOfArgumentException
  49.      *             if the string representation of the given URL is invalid and a {@link MalformedURLException} occurs
  50.      */
  51.     public static URL build(@Nonnull final String url) {
  52.         Check.notNull(url, "url");

  53.         URL ret = null;
  54.         try {
  55.             ret = new URL(url);
  56.         } catch (final MalformedURLException e) {
  57.             throw new IllegalStateOfArgumentException("The given string is not a valid URL: " + url, e);
  58.         }
  59.         return ret;
  60.     }

  61.     /**
  62.      * Tries to open an {@link InputStream} to the given {@link URL}.
  63.      *
  64.      * @param url
  65.      *            URL which should be opened
  66.      * @return opened stream
  67.      * @throws net.sf.qualitycheck.exception.IllegalNullArgumentException
  68.      *             if the given argument is {@code null}
  69.      * @throws CanNotOpenStreamException
  70.      *             if no stream to the given {@code URL} can be established
  71.      */
  72.     public static InputStream open(@Nonnull final URL url) {
  73.         Check.notNull(url, "url");

  74.         final InputStream ret;
  75.         try {
  76.             ret = url.openStream();
  77.         } catch (final IOException e) {
  78.             throw new CanNotOpenStreamException(url.toString(), e);
  79.         }
  80.         return ret;
  81.     }

  82.     /**
  83.      * Reads the content of the passed {@link URL} as string representation.
  84.      *
  85.      * @param url
  86.      *            URL to <em>UAS data</em>
  87.      * @param charset
  88.      *            the character set in which the data should be read
  89.      * @return content as {@code String}
  90.      * @throws net.sf.qualitycheck.exception.IllegalNullArgumentException
  91.      *             if any of the given arguments is {@code null}
  92.      * @throws CanNotOpenStreamException
  93.      *             if no stream to the given {@code URL} can be established
  94.      * @throws IOException
  95.      *             if an I/O error occurs
  96.      */
  97.     public static String read(@Nonnull final URL url, @Nonnull final Charset charset) throws IOException {
  98.         Check.notNull(url, "url");
  99.         Check.notNull(charset, "charset");

  100.         final InputStream inputStream = open(url);
  101.         BufferedReader reader = null;
  102.         final StringBuilder buffer = new StringBuilder();
  103.         boolean threw = true;
  104.         try {
  105.             reader = new BufferedReader(new InputStreamReader(inputStream, charset));
  106.             buffer.append(readAll(reader));
  107.             threw = false;
  108.         } finally {
  109.             Closeables.close(reader, threw);
  110.             Closeables.close(inputStream, false);
  111.         }
  112.         return buffer.toString();
  113.     }

  114.     /**
  115.      * Reads the entire contents via the given {@link Reader} as string.
  116.      *
  117.      * @param reader
  118.      *            {@code Reader} to read the entire contents
  119.      * @return the read contents as string
  120.      * @throws IOException
  121.      *             If an I/O error occurs
  122.      */
  123.     private static String readAll(@Nonnull final Reader reader) throws IOException {
  124.         final StringBuilder buffer = new StringBuilder();
  125.         int cp;
  126.         while ((cp = reader.read()) != -1) {
  127.             buffer.append((char) cp);
  128.         }
  129.         return buffer.toString();
  130.     }

  131.     /**
  132.      * Gets the URL to a given {@code File}.
  133.      *
  134.      * @param file
  135.      *            file to be converted to a URL
  136.      * @return an URL to the passed file
  137.      * @throws IllegalStateException
  138.      *             if no URL can be resolved to the given file
  139.      */
  140.     public static URL toUrl(@Nonnull final File file) {
  141.         Check.notNull(file, "file");

  142.         URL url = null;
  143.         try {
  144.             url = file.toURI().toURL();
  145.         } catch (final MalformedURLException e) {
  146.             throw new IllegalStateException("Can not construct an URL for passed file.", e);
  147.         }
  148.         return url;
  149.     }

  150.     /**
  151.      * <strong>Attention:</strong> This class is not intended to create objects from it.
  152.      */
  153.     private UrlUtil() {
  154.         // This class is not intended to create objects from it.
  155.     }

  156. }