package org.jerrymouse.cc.site.web.upload;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.SocketException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.jerrymouse.cc.site.bean.Resource;

public class UploadToFtp {
	Log log = LogFactory.getLog(UploadToFtp.class);

	private String host = "jerrmouse.net16.net";
	private String username = "a3339639";
	private String password = "kaiyannju1248163264";
	private String path = "/public_html/cc";

	private String creatFilename(Resource resource) {
		return resource.getOrgType().addSuffix(resource.getFilename());
	}

	public String putResource(Resource resource) {
		String filename = creatFilename(resource);
		FTPClient ftpClient = new FTPClient();
		try {
			ftpClient.connect(host);
			ftpClient.login(username, password);
			ftpClient.changeWorkingDirectory(path);
			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
			if (ftpClient.storeFile(filename, new ByteArrayInputStream(resource
					.getOrgBytes()))) {
				log.info("Was uploaded");
			} else {
				log.info("Not uploaded");
			}
			ftpClient.logout();
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				ftpClient.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "http://jerrymouse.org.cn/cc/" + filename;
	}
}
