/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved. <a>http://www.crunii.com</a>
 */
package com.crunii.micro.common.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.ResourceUtils;

/**
 * @author 田平 create 2018年10月11日下午7:14:04
 */
public class ResUtil {
	protected static final Logger log = LoggerFactory.getLogger(ResUtil.class);

	public static String getContent(InputStream input) {
		String result = "";
		BufferedReader bufferedReader = null;
		try {
			bufferedReader = new BufferedReader(new InputStreamReader(input));
			result = bufferedReader.lines().collect(Collectors.joining(System.lineSeparator()));
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					log.warn("bufferedReader.close() error！", e);
				}
			}
		}
		return result;
	}

	/**
	 * 注意关闭流
	 * 
	 * @param path
	 * @return
	 */
	public static InputStream getResInputStream(String path) {
		InputStream input = null;
		try {
			ResourceLoader resourceLoader = new DefaultResourceLoader();
			Resource fileRource = resourceLoader.getResource(path);
			input = fileRource.getInputStream();
		} catch (Exception e) {
			log.warn("resource:" + path + " not in jar!");
			File refFile;
			try {
				refFile = ResourceUtils.getFile(path);
				input = new FileInputStream(refFile);
			} catch (FileNotFoundException e1) {
				log.warn("resource:" + path + " not find!", e);
				throw new RuntimeException(e);
			}
		}
		return input;
	}
	
	/**
	 * 获取资源文件本地测试或者发布兼容
	 * 
	 * @param path classpath:xml/soap.xml
	 * @return
	 */
	public static String getResContent(String path) {
		InputStream input = getResInputStream(path);
		return getContent(input);
	}
}
