package net.northking.cctp.scriptcase.tools;

import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.scriptcase.enums.ErrorMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class StreamUtils {
    /**
     * 日志
     */
    private final static Logger logger = LoggerFactory.getLogger(StreamUtils.class);

    /**
     * 将输入流写入到响应中
     *
     * @param response
     * @param in
     */
    public static void toResponse(HttpServletResponse response, InputStream in) {
        if (null == in) {
            throw new PlatformRuntimeException(new ErrorMessage("写入文件失败"));
        }
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int read = 0;
            while ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }
            out.flush();
        } catch (IOException e) {
            throw new PlatformRuntimeException(new ErrorMessage("转换流失败"), e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    logger.error("关闭输入流失败", e);
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    logger.error("关闭输出流失败", e);
                }
            }
        }
    }
}
