001package org.gbif.utils.file;
002
003import java.io.BufferedReader;
004import java.io.IOException;
005import java.io.InputStream;
006import java.io.InputStreamReader;
007import java.io.UnsupportedEncodingException;
008import java.net.URL;
009
010import org.slf4j.Logger;
011import org.slf4j.LoggerFactory;
012
013public class InputStreamUtils {
014
015  private static final Logger LOG = LoggerFactory.getLogger(InputStreamUtils.class);
016
017  public InputStream classpathStream(String path) {
018    InputStream in = null;
019    // relative path. Use classpath instead
020    URL url = getClass().getClassLoader().getResource(path);
021    if (url != null) {
022      try {
023        in = url.openStream();
024      } catch (IOException e) {
025        LOG.warn("Cant open classpath input stream " + path, e);
026      }
027    }
028    return in;
029  }
030
031  /**
032   * Converts an entire InputStream to a single String with UTF8 as the character encoding.
033   *
034   * @param source source input stream to convert
035   *
036   * @return the string representing the entire input stream
037   */
038  public String readEntireStream(InputStream source) {
039    return readEntireStream(source, FileUtils.UTF8);
040  }
041
042  /**
043   * Converts an entire InputStream to a single String with explicitly provided character encoding.
044   * <p/>
045   * To convert the InputStream to String we use the BufferedReader.readLine()
046   * method. We iterate until the BufferedReader return null which means
047   * there's no more data to read. Each line will appended to a StringBuilder
048   * and returned as String.
049   *
050   * @param source   source input stream to convert
051   * @param encoding the streams character encoding
052   *
053   * @return the string representing the entire input stream
054   */
055  public String readEntireStream(InputStream source, String encoding) {
056    BufferedReader reader;
057    try {
058      reader = new BufferedReader(new InputStreamReader(source, encoding));
059    } catch (UnsupportedEncodingException e1) {
060      throw new IllegalArgumentException("Unsupported encoding" + encoding, e1);
061    }
062    StringBuilder sb = new StringBuilder();
063
064    try {
065      String line;
066      while ((line = reader.readLine()) != null) {
067        sb.append(line).append('\n');
068      }
069    } catch (IOException e) {
070      LOG.warn("Caught exception", e);
071    } finally {
072      try {
073        source.close();
074      } catch (IOException e) {
075        LOG.warn("Caught exception", e);
076      }
077    }
078    return sb.toString();
079  }
080}