package org.apache.slide.projector.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.i18n.LocalizedError;
import org.apache.slide.projector.repository.RepositoryException;
import org.apache.slide.projector.value.Streamable;

public class StreamHelper {
    public static String streamToString(Streamable resource) throws RepositoryException {
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            copy(resource.getInputStream(), outputStream);
            return outputStream.toString(resource.getCharacterEncoding());
        } catch ( IOException exception ) {
            throw new RepositoryException(new LocalizedError("IOException"), exception);
        }
    }

    public static void copy(InputStream inputStream, OutputStream outputStream) throws RepositoryException {
        try {
            byte buffer[] = new byte[1024];
            int len = buffer.length;
            while (true) {
                len = inputStream.read(buffer);
                if (len == -1) break;
                outputStream.write(buffer, 0, len);
            }
            inputStream.close();
            outputStream.close();
        } catch ( IOException exception ) {
            throw new RepositoryException(new LocalizedError("IOException"), exception);
        }
    }
}