Package ca.pgon.st.light

Source Code of ca.pgon.st.light.StreamsUtils

/*
    Small Tools - Some basic libraries for developing and testing http://www.pgon.ca/st
    Copyright (C) 2013 Small Tools (info@pgon.ca)

    Licensed 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 ca.pgon.st.light;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.util.logging.Level;
import java.util.logging.Logger;

import ca.pgon.st.light.exception.StLightException;

/**
* Some simple methods to play with streams.
*
* @author Simon Levesque
*
*/
public final class StreamsUtils {

    private static final Logger logger = Logger.getLogger(StreamsUtils.class.getName());

    private static final int BUFFER_SIZE = 1024;

    /**
     * Take a stream and get it as a String. The stream is closed at the end.
     *
     * @param input
     *            the input
     * @return the string
     */
    public static String consumeAsString(InputStream input) {

        Assert.assertNotNull(input, "The input cannot be null");

        try {
            Reader reader = new InputStreamReader(input);
            StringBuilder sb = new StringBuilder();

            char[] chars = new char[BUFFER_SIZE];
            int len;
            while ((len = reader.read(chars)) != -1) {
                sb.append(chars, 0, len);
            }
            return sb.toString();
        } catch (Exception e) {
            throw new StLightException("Issue reading the stream", e);
        } finally {
            try {
                input.close();
            } catch (Exception e) {
            }
        }
    }

    /**
     * Consumes the content of the source, adds it to the destination and closes the source.
     *
     * @param source
     * @param destination
     */
    public static void flowStream(InputStream source, OutputStream destination) {

        Assert.assertNotNull(source, "The source cannot be null");
        Assert.assertNotNull(destination, "The destination cannot be null");

        try {
            byte[] bytes = new byte[BUFFER_SIZE];
            int len;

            logger.log(Level.FINE, "Starting to copy the stream");
            while ((len = source.read(bytes)) != -1) {
                destination.write(bytes, 0, len);
            }

            logger.log(Level.FINE, "Copy completed");

        } catch (Exception e) {

            logger.log(Level.SEVERE, "Issue copying the stream", e);
            throw new StLightException("Issue copying the stream", e);

        } finally {

            // Close the source
            try {
                source.close();
            } catch (Exception e) {
            }

        }
    }

    /**
     * Creates a separate thread to consume the content of the source, add it to the destination and close the source.
     *
     * @param source
     * @param destination
     */
    public static void flowStreamNonBlocking(final InputStream source, final OutputStream destination) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                flowStream(source, destination);
            }
        });
        thread.start();
    }

    private StreamsUtils() {
    }
}
TOP

Related Classes of ca.pgon.st.light.StreamsUtils

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.