package com.bocloud.ims.service.utils;

import com.ice.tar.TarEntry;
import com.ice.tar.TarInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class TarUtil {

	private static Logger logger = LoggerFactory.getLogger(TarUtil.class);

	/**
	 * 解压tar包
	 * 
	 * @param tarSrcPath
	 *            要解压的tar包的绝对路径
	 * @return list tar里的文件集合
	 */
	public static String unTar(String tarSrcPath) {
		StringBuffer buffer = new StringBuffer();
		InputStream inputstream = null;
		TarInputStream zis = null;
		try {
			File file = new File(tarSrcPath);
			inputstream = new FileInputStream(file);
			zis = new TarInputStream(inputstream);
			TarEntry tarEntry = null;
			String tarFileName = "";
			while ((tarEntry = zis.getNextEntry()) != null) {
				tarFileName = getTarFileName(tarEntry.getName());
				if ("repositories".equalsIgnoreCase(tarFileName)) {
					int count;
					byte[] data = new byte[1024];
					while ((count = zis.read(data, 0, 1024)) != -1) {
						String str = new String(data, 0, count);
						buffer.append(str);
					}
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		} finally {
			try {
				inputstream.close();
				zis.close();
			} catch (Exception e) {
				logger.error(e.getMessage());
			}

		}
		return buffer.toString();

	}

	/**
	 * 
	 * @param name
	 * @return
	 */
	private static String getTarFileName(String name) {
		try {
			// 先转换成char,再还原成字节
			char[] cs = name.toCharArray();
			byte[] bs = new byte[cs.length];
			for (int i = 0; i < cs.length; i++) {
				bs[i] = (byte) cs[i];
			}
			return new String(bs);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "";
	}

}
