package com.sinosoft.mis.service;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.servlet.http.HttpServletRequest;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.Session;
import com.sinosoft.cms.common.util.SFTPUtil;
import com.sinosoft.cms.common.util.SystemParameters;
import com.sinosoft.transverse.common.Data;
public class Jun implements JunService {
private static Workbook wb;
private static ChannelSftp sftp;
private static Session session;
/** SFTP 登錄用戶名*/
private static String username;
/** SFTP 登錄密碼*/
private static String password;
/** 私鑰 */
private static String privateKey;
/** SFTP 服務器地址IP地址*/
private static String host;
/** SFTP 端口*/
private static int port;
/**
* 下載文件
* @return
*/
public String downloadFile(){
Map params = Data.getParametersFromRequest(super.getRequest());
String ftpPathHead = SystemParameters.FTPpath;//FTP文件服務器基礎路徑
String ftpPathTail = (String) params.get("ftpPath");//FTP基礎路徑后路徑
String ftpPath = ftpPathHead+ftpPathTail;//
ftpPath = ftpPath.replaceAll("//", "/");//FTP儲存文件路徑
String rootPath = super.getRequest().getSession().getServletContext().getRealPath("/");//項目根目錄
String downloadPath = rootPath+"downloadFile/";
String returnPath = SFTPUtil.downloadFile(ftpPath,downloadPath);
returnPath = returnPath.substring(returnPath.lastIndexOf("vehiclesMIS"));
StringBuffer requestURL = super.getRequest().getRequestURL();
String url = requestURL.substring(0, requestURL.indexOf("vehiclesMIS"))+returnPath;
url = url.replaceAll("\\\\", "/");
StringBuffer sb = new StringBuffer();
sb.append("<script type=\"text/javascript\">\n");
sb.append("window.location.href='"+url+"';\n");
sb.append("</script>");
super.renderHtml(sb.toString());
return null;
}
public String editInsSubmit(Map params, File underFile, HttpServletRequest request) {
String underFileDown = "";//上傳后的下載路徑
if(underFile!=null){
String underFilePath = underFile.getAbsolutePath();//文件路徑
underFilePath = underFilePath.substring(0, underFilePath.lastIndexOf(".")+1);
underFile.renameTo(new File(underFilePath+"zip"));//修改文件后綴名
underFilePath = underFilePath.replaceAll("\\\\", "/");
String conContrZipPath = underFilePath.substring(0, underFilePath.lastIndexOf("."))+"/";
//解壓壓縮文件
String conUnZipPath = Jun.unZip(underFilePath+"zip", conContrZipPath);
//判斷壓縮文件里的個數,或知否保函什么文件(有無xls的文件)
// List<String> conUnZipPath = UnZip.unZip(uploadDataPath, conContrZipPath);
// int size = conUnZipPath.size();
String result = readFile(conContrZipPath);
if(result=="Y"){
}else{
StringBuffer sb = new StringBuffer();
sb.append("<script type=\"text/javascript\">\n");
sb.append("alert(\""+result+"\")\n");
sb.append("window.history.go(-1)\n");
sb.append("</script>");
return sb.toString();
}
//上傳文件,返回下載路徑
underFileDown = uploadFile(underFilePath+"zip",request);
if(underFileDown==null){
StringBuffer sb = new StringBuffer();
sb.append("<script type=\"text/javascript\">\n");
sb.append("alert(\"上傳安全責任險核保信息文件異常!請檢查路徑及文件類型是否正確!\")\n");
sb.append("window.history.go(-1)\n");
sb.append("</script>");
return sb.toString();
}else{
//下載路徑存庫
}
}
return null;
}
/**
* 解壓文件
* @param zipFile 目標文件
* @param descDir 指定解壓目錄
* @param urlList 存放解壓后的文件目錄(可選)
* @return
*/
public static String unZip(String zipPath, String descDir) {
File zipFile = new File(zipPath);
boolean flag = false;
File pathFile = new File(descDir);
if(!pathFile.exists()){
pathFile.mkdirs();
}
ZipFile zip = null;
try {
//指定編碼,否則壓縮包里面不能有中文目錄
zip = new ZipFile(zipFile, Charset.forName("gbk"));
String returnStr = "";
for(Enumeration entries = zip.entries(); entries.hasMoreElements();){
ZipEntry entry = (ZipEntry)entries.nextElement();
String zipEntryName = entry.getName();
InputStream in = zip.getInputStream(entry);
String outPath = (descDir+zipEntryName).replace("/", File.separator);
returnStr = zipEntryName;
//判斷路徑是否存在,不存在則創建文件路徑
File file = new File(outPath.substring(0, outPath.lastIndexOf(File.separator)));
if(!file.exists()){
file.mkdirs();
}
//判斷文件全路徑是否為文件夾,如果是上面已經上傳,不需要解壓
if(new File(outPath).isDirectory()){
continue;
}
//保存文件路徑信息
// urlList.add(outPath);
OutputStream out = new FileOutputStream(outPath);
byte[] buf1 = new byte[2048];
int len;
while((len=in.read(buf1))>0){
out.write(buf1,0,len);
}
in.close();
out.close();
}
//必須關閉,否則無法刪除該zip文件
zip.close();
if(returnStr.lastIndexOf("/")>-1){
returnStr = returnStr.substring(0,returnStr.lastIndexOf("/"));
}
return returnStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 上傳文件
* 返回null表示上傳異常
* @return
*/
public String uploadFile(String path, HttpServletRequest request){
//將上傳的文件寫到服務器上指定的文件。
String ftpPath = SFTPUtil.uploadFiles(path,"insins");
if(ftpPath==null){
return null;
}else{
ftpPath = ftpPath.substring(ftpPath.indexOf("ftpFile")+7);
StringBuffer requestURL = request.getRequestURL();
String url = requestURL.substring(0, requestURL.indexOf("項目名")+19);
url = url+"/ceshi/downloadFile.do?ftpPath=\""+ftpPath+"\"";
// super.renderText(url);
return url;
}
}
/**
* 上傳文件工具類方法
* @param path 上傳文件路徑
* @param FTPpathName 希望在文件服務器創建的文件夾名稱(可以為null)
*/
public static String uploadFiles(String path,String FTPpathName){
try {
String suffixName = path.substring(path.lastIndexOf(".") + 1);//獲取文件后綴名
String newName = randomTime()+"."+suffixName;//文件的新名字
host = "192.168.0.1";//服務器地址
port = 88;//端口
username = "root";//用戶名
password = "000000";//密碼
String FTPpath= "/PolicyManagement/ftpFile/";//FTP基礎路徑
SFTPUtil sftp = new SFTPUtil(username, password, host, port);
sftp.login();
File file = new File(path);
InputStream is = new FileInputStream(file);
Date date = new Date();
String str = "yyyMMdd";
SimpleDateFormat sdf = new SimpleDateFormat(str);
String timePath = sdf.format(date);
if(FTPpathName==null||"".equals(FTPpathName)){
FTPpathName = "/"+timePath+"/";
}else{
FTPpathName = "/"+timePath+"/"+FTPpathName+"/";
}
sftp.upload(FTPpath,FTPpathName, newName, is);
sftp.logout();
String returnPath = FTPpath+FTPpathName+newName;
returnPath = returnPath.replace("//", "/");
return returnPath;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String randomTime() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyMMdd");
String timePath = sdf.format(new Date());
long r = 0;
int i = 0;
while(true) {
r = System.currentTimeMillis();
//取模 也就是1----99的隨機數
i = (int)(r % 100);
if(0 != i) {
break;
}
}
// System.out.println(r);
// System.out.printf("%d \n",i);
return String.valueOf(timePath+r);
}
public static List<String> unZipTest(String zipPath, String descDir) {
File zipFile = new File(zipPath);
boolean flag = false;
File pathFile = new File(descDir);
if(!pathFile.exists()){
pathFile.mkdirs();
}
ZipFile zip = null;
try {
//指定編碼,否則壓縮包里面不能有中文目錄
zip = new ZipFile(zipFile, Charset.forName("gbk"));
String returnStr = "";
List<String> entrys = new ArrayList<>();
for(Enumeration entries = zip.entries(); entries.hasMoreElements();){
ZipEntry entry = (ZipEntry)entries.nextElement();
String zipEntryName = entry.getName();
entrys.add(zipEntryName);
InputStream in = zip.getInputStream(entry);
String outPath = (descDir+zipEntryName).replace("/", File.separator);
returnStr = zipEntryName;
//判斷路徑是否存在,不存在則創建文件路徑
File file = new File(outPath.substring(0, outPath.lastIndexOf(File.separator)));
if(!file.exists()){
file.mkdirs();
}
//判斷文件全路徑是否為文件夾,如果是上面已經上傳,不需要解壓
if(new File(outPath).isDirectory()){
continue;
}
//保存文件路徑信息
// urlList.add(outPath);
OutputStream out = new FileOutputStream(outPath);
byte[] buf1 = new byte[2048];
int len;
while((len=in.read(buf1))>0){
out.write(buf1,0,len);
}
in.close();
out.close();
}
//必須關閉,否則無法刪除該zip文件
zip.close();
if(returnStr.lastIndexOf("/")>-1){
returnStr = returnStr.substring(0,returnStr.lastIndexOf("/"));
}
return entrys;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public String readFile(String filePath) {
File file = new File(filePath);
if (file.isDirectory()) {
String[] fileList = file.list();
for (int i = 0, len = fileList.length; i < len; i++) {
File readFile = new File(filePath + fileList[i]);
if (readFile.isDirectory()) {
return "請不要包含多層文件夾!";
} else if (!readFile.isDirectory()) {
// 這里不用判斷文件類型,只要是文件就行,在下面這個方法里面判斷文件
String fileName = readFile.getName();
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
if("xls".equals(suffix)||"xlsx".equals(suffix)){
return parsingFile(readFile);
}
}
}
}else if(!file.isDirectory()){
String fileName = file.getName();
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
if("xls".equals(suffix)||"xlsx".equals(suffix)){
return parsingFile(file);
}else {
return "請上傳含有Excel的文件!";
}
}
return "請上傳含有Excel的文件!";
}
public String parsingFile(File fileExcel) {
try{
int position = fileExcel.getName().lastIndexOf(".");
if (position < 0){
return "只能上傳含后綴的文件!";
}
InputStream is = new FileInputStream(fileExcel.getPath());
if(fileExcel.getName().endsWith(".xls")){
wb = new HSSFWorkbook(is);
}else if(fileExcel.getName().endsWith(".xlsx")){
wb = new XSSFWorkbook(is);
}
//執行循環表行
}catch(Exception e){
e.printStackTrace();
return"上傳文件數據有誤";
}
return null;
}
}