001package io.ebean.migration.util;
002
003import java.io.ByteArrayOutputStream;
004import java.io.IOException;
005import java.io.InputStream;
006import java.io.OutputStream;
007import java.io.UnsupportedEncodingException;
008import java.net.URL;
009import java.net.URLConnection;
010
011/**
012 * Utilities for IO.
013 */
014public class IOUtils {
015
016  /**
017   * Reads the entire contents of the specified URL and return them as UTF-8 string.
018   */
019  public static String readUtf8(URL url) throws IOException {
020    URLConnection urlConnection = url.openConnection();
021    urlConnection.setUseCaches(false);
022    return readUtf8(urlConnection.getInputStream());
023  }
024
025  /**
026   * Reads the entire contents of the specified input stream and return them as UTF-8 string.
027   */
028  public static String readUtf8(InputStream in) throws IOException {
029    return bytesToUtf8(read(in));
030  }
031
032  /**
033   * Reads the entire contents of the specified input stream and returns them as a byte array.
034   */
035  private static byte[] read(InputStream in) throws IOException {
036    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
037    pump(in, buffer);
038    return buffer.toByteArray();
039  }
040
041  /**
042   * Returns the UTF-8 string corresponding to the specified bytes.
043   */
044  private static String bytesToUtf8(byte[] data) {
045    try {
046      return new String(data, "UTF-8");
047    } catch (UnsupportedEncodingException e) {
048      throw new IllegalStateException("Support for UTF-8 is mandated by the Java spec", e);
049    }
050  }
051
052  /**
053   * Reads data from the specified input stream and copies it to the specified
054   * output stream, until the input stream is at EOF. Both streams are then
055   * closed.
056   */
057  private static void pump(InputStream in, OutputStream out) throws IOException {
058
059    if (in == null) throw new IOException("Input stream is null");
060    if (out == null) throw new IOException("Output stream is null");
061    try {
062      try {
063        byte[] buffer = new byte[4096];
064        for (; ; ) {
065          int bytes = in.read(buffer);
066          if (bytes < 0) {
067            break;
068          }
069          out.write(buffer, 0, bytes);
070        }
071      } finally {
072        in.close();
073      }
074    } finally {
075      out.close();
076    }
077  }
078}