/**
 * 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.core.test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.compressors.CompressorInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

/**
 * @author 田平 create 2018年6月12日下午5:44:25
 */
public class FtpTest {
	public static void main(String[] args) throws Exception {
		FTPClient client = new FTPClient();
		client.connect("219.153.7.14", 61321);
		boolean result = client.login("kaoshi", "Ks!@#123");

		if (result) {
			client.enterLocalPassiveMode();
			client.setFileType(FTP.BINARY_FILE_TYPE);
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024);
			boolean success = client.retrieveFile("/exam.txt", outputStream);
			if (success) {
				System.out.println(outputStream.toString());
			}
			ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream(1024);
			boolean success1 = client.retrieveFile("/exam001.zip", outputStream1);
			if (success1) {
				ByteArrayInputStream inputStream1 = new ByteArrayInputStream(outputStream1.toByteArray());
				ZipArchiveInputStream zInputStream = new ZipArchiveInputStream(inputStream1);
				ArchiveEntry entry = zInputStream.getNextEntry();
				byte[] data = new byte[(int) entry.getSize()];
				zInputStream.read(data);
				zInputStream.close();
				System.out.println(new String(data));
			}

			ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream(1024);
			boolean success2 = client.retrieveFile("/exam002.tar.gz", outputStream2);

			if (success2) {
				ByteArrayInputStream inputStream2 = new ByteArrayInputStream(outputStream2.toByteArray());
				CompressorInputStream gInputStream = new GzipCompressorInputStream(inputStream2, true);
				TarArchiveInputStream tInputStream = new TarArchiveInputStream(gInputStream);
				TarArchiveEntry entry = tInputStream.getNextTarEntry();
				byte[] data = new byte[(int) entry.getSize()];
				tInputStream.read(data);
				tInputStream.close();
				gInputStream.close();
				System.out.println(new String(data));
			}

		}
	}
}
