package com.cftech.core.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

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

/**
 * Created by liuling on 2017/5/5.
 */
@Slf4j
public class InputStreamCache {
    private ByteArrayOutputStream byteArrayOutputStream;

    public InputStreamCache(InputStream inputStream) {
        if (ObjectUtils.isEmpty(inputStream)) {
            log.error("InputStreamCache constructor arg is empty");
            return;
        }

        byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        try {
            while ((len = inputStream.read(buffer)) > -1 ) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
            byteArrayOutputStream.flush();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    public InputStream getInputStream() {
        if (ObjectUtils.isEmpty(byteArrayOutputStream))
            return null;

        return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    }
}
