读取压缩包,解析压缩包,解析压缩包里的xml文件

一、 代码如下:


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.pde.base.PdeBusinessException;
import com.pde.base.R;
import com.pde.d7.common.core.service.CommonSqlService;
import com.pde.d7.dak.core.dao.model.DamlModel;
import com.pde.d7.dak.core.dao.model.YwModel;
import com.pde.d7.dak.core.service.DakBuilderService;
import com.pde.d7.dak.core.service.DasjService;
import com.pde.d7.jk.core.OaJkConfig;
import com.pde.util.FileUtil;
import com.pde.util.ZipUtil;

@Component("OaBulider")
public class OaJkBuliderImpl implements OaJkBulider {

	protected String shareFloder;
	protected String tempFloder;
	protected String backFloder;
	protected String tableId;
	protected String fileEncoding;
	
	private String datestr;

	protected OaJkConfig oaJkConfig = null;
	@Resource(name = "OaJkConfig")
	public void setOaJkConfig(OaJkConfig oaJkConfig) {
		this.oaJkConfig = oaJkConfig;
	}

	protected Map qzdygx = null;
	@Resource(name = "Qzdygx")
	public void setQzdygx(Map qzdygx) {
		this.qzdygx = qzdygx;
	}

	@Autowired
	protected DakBuilderService dakBuilderService;

	@Autowired
	protected CommonSqlService commonSqlService;

	public void initData(){
		shareFloder = oaJkConfig.getShareFloder();
		backFloder = oaJkConfig.getBackFloder();
		tempFloder = oaJkConfig.getTempFloder();
		fileEncoding = oaJkConfig.getFileEncoding();
		//设置tableId的值
		String sql = "select ID from S_DAK WHERE WLBM = '"+oaJkConfig.getTablename()+"'";
		Map idMap;
		try {
			idMap = commonSqlService.exeQueryOneSql(sql);
			if(null != idMap) {
				tableId = (String) idMap.get("ID");
			}
		} catch (PdeBusinessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
		datestr = format.format(date);
	}
	@Override
	public void run(Map m){
		run();
	}

	@SuppressWarnings("unchecked")
	@Override
	public void run(){
		initData();
		SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
		backMemo("---------------------------------------------------------------OA调度开始 : "+format.format(new Date()));
		//List zipnames = getZipNames(shareFloder);
		Map model = getZipNames(shareFloder);
		List zipnames = (List) model.get("filenames");
		int total = (Integer) model.get("total");
		int sucess_i = 0;
		for (String zipname : zipnames) {
			String wjname = zipname.substring(0,zipname.lastIndexOf('.'));
			String zipPath = shareFloder+"/"+ zipname;
			List files = ZipUtil.unZip(zipPath, tempFloder+"/"+wjname+"/",fileEncoding);
			boolean isSucess = parseFiles(files,zipname);
			if(isSucess) {
				sucess_i++;
			}
			try {
				Thread.sleep(50);
			} catch (InterruptedException e) {
				System.out.println("----------------"+e.getMessage());
				e.printStackTrace();
			}
		}
		backMemo("---------------------(共读取的"+total+"个数据包,成功"+sucess_i+"个,失败"+(total-sucess_i)+"个)---------------------");
		backMemo("---------------------------------------------------------------OA调度结束 : "+format.format(new Date()));
		backMemo("  ");
	}

	/**
	 * 获取压缩包列表
	 * @param path
	 * @return List
	 */
	public Map getZipNames(String path) {
		Map model = new HashMap();
		List filenames = new ArrayList();
		List all_filenames = new ArrayList();
		File file = new File(path);
		List files = Arrays.asList(file.listFiles());
		// 按文件名排序
		Collections.sort(files, new Comparator() {
			@Override
			public int compare(File o1, File o2) {
				if (o1.isDirectory() && o2.isFile())
					return -1;
				if (o1.isFile() && o2.isDirectory())
					return 1;
				return o1.getName().compareTo(o2.getName());
			}
		});
		for (File _f : files) {
			if(_f.getName().endsWith(".zip")) {
				all_filenames.add(_f.getName());
				String sql = "select count(1) from "+oaJkConfig.getTablename() +" where XT_JLZT = 1 and XT_LY = '" + _f.getName()+"'";
				try {
					int count = commonSqlService.exeCountSql(sql);
					if(count>0) {
						dealFile(_f.getName(),false,"","失败(已存在)");
						backMemo(_f.getName()+" : 该数据包档案库已存在!");
					} else {
						filenames.add(_f.getName());
					}
					
				} catch (PdeBusinessException e1) {
					System.out.println(e1.getMessage());
				}
			}
		}
		model.put("filenames", filenames);
		model.put("total", all_filenames.size());
		return model;
	}
	

	/**
	 * 解析压缩包的DATA.xml
	 * @param files
	 * @param zipname
	 */
	@SuppressWarnings("unchecked")
	public boolean parseFiles(List files,String zipname){
		String wjname = zipname.substring(0,zipname.lastIndexOf('.'));
		String dataPath = tempFloder+"/"+wjname+"/"+"DATA.xml";

		File f = new File(dataPath); 
		SAXReader reader = new SAXReader(); 
		Document doc;
		try {
			doc = reader.read(f);
			Element root = doc.getRootElement(); 
			Map tminfo = new HashMap();//存放条目信息
			List ywinfo = new ArrayList();//存放原文信息
			listNodes(root,tminfo,ywinfo); 
			//添加条目信息
			DamlModel damlModel = new DamlModel();
			
			String qzhValue = (String) tminfo.get(oaJkConfig.getQzhzd());
			if(null != qzhValue && !"".equals(qzhValue.trim())) {
				tminfo.put("XT_LY", zipname);
				tminfo.put("XT_LYLX", "同步");
				damlModel.setData(tminfo);
				R r;
				try {
					r = dakBuilderService.createDak(tableId, DasjService.class).add(damlModel);
					if(r.isState()) {
						//添加原文信息上传原文
						Map backmodel = (Map) r.getResult();
						String tmid = (String) backmodel.get("id");
						//String qzh = (String) backmodel.get(oaJkConfig.getQzhzd());
						YwModel ywModel = new YwModel();
						ywModel.setTmid(tmid);
						ywModel.setDakid(tableId);
						ywModel.setYwczr("-1");
						ywModel.setTmdh("-1");
						ywModel.setYwlx("");
						for (String filename : ywinfo) {
							if(filename.lastIndexOf(".")>0) {
								ywModel.setYwbt(filename.substring(0,filename.lastIndexOf(".")));
							} else {
								ywModel.setYwbt(filename);
							}
							ywModel.setYwmc(filename);
							InputStream in = null;
							try {
								String ywpath = tempFloder+"/"+wjname+"/DATA/"+filename;
								File ywFile = new File(ywpath);
								if(!ywFile.exists()) {
									continue;
								}
								in = new FileInputStream(tempFloder+"/"+wjname+"/DATA/"+filename);
								dakBuilderService.createDak(tableId, DasjService.class).addFile(ywModel, in, null);
								if(null != in) {
									try {
										in.close();
									} catch (IOException e) {
										//e.printStackTrace();
										System.out.println("------------------"+e.getMessage());
									}
								}
							} catch (FileNotFoundException e) {
								System.out.println("------------------"+e.getMessage());
							}
						}
						System.out.println("添加成功!");
						dealFile(zipname,true,"","成功");
						return true;
					} else {
						dealFile(zipname,false,"","失败");
						backMemo(zipname+" : 新增条目失败,请检查该档案库的模板字段(字段长度,必录项)和OA字段的值的对应情况!");
					}
					
				} catch (PdeBusinessException e) {
					//失败的条目
					System.out.println(e.getMessage());
					dealFile(zipname,false,"","失败");
					backMemo(zipname+" : 无法排除具体原因,请检查Ftp是否验证成功和OA数据包的内容是否正确!");
				}
			} else {
				dealFile(zipname,false,"","失败");
				backMemo(zipname+" : OA系统的来文单位找不到对应的全宗号,请到配置文件里进行配置对应关系!");
			}

		} catch (DocumentException e) {
			System.out.println("------------------"+e.getMessage());
			dealFile(zipname,false,"","失败");
			backMemo(zipname+" : 解析压缩包异常!");
			//e.printStackTrace();
		} 
		return false;

	}
	@SuppressWarnings("unchecked")
	public void listNodes(Element node,Map tminfo,List ywinfo) {  
		List list = node.attributes();  
		// 遍历属性节点  
		for (Attribute attr : list) {  
			if("文件".equals(node.getName().trim()) && "文件名称".equals(attr.getName().trim())) {
				if(!"".equals(attr.getValue().trim()) && null != attr.getValue()) {
					ywinfo.add(attr.getValue());
				}
			}
		}  
		if (!(node.getTextTrim().equals(""))) {  
			String zdmc = (String) oaJkConfig.getZddy().get(node.getName());
			if(null != zdmc && !"".equals(zdmc.trim())) {
				tminfo.put(zdmc,  node.getText());
			}
			if(node.getName().equals(oaJkConfig.getQzhdydw())) {
				zdmc = oaJkConfig.getQzhzd();
				tminfo.put(zdmc, qzdygx.get(node.getText()));
			}
		}  

		// 当前节点下面子节点迭代器  
		Iterator it = node.elementIterator();  
		// 遍历  
		while (it.hasNext()) {  
			// 获取某个子节点对象  
			Element e = it.next();  
			// 对子节点进行遍历  
			listNodes(e,tminfo,ywinfo);  
		}  

	}  

	public void dealFile(String zipname,boolean isSucess,String id,String infoFolder){
		String wjname = zipname.substring(0,zipname.lastIndexOf('.'));
		String tempFile = tempFloder+"/"+wjname;
		String oldFile = shareFloder+"/"+ zipname;
		String newFile = null;
		if(isSucess) {
			newFile = backFloder+"/"+datestr+"/"+infoFolder+"/"+ zipname;
		} else {
			newFile = backFloder+"/"+datestr+"/"+infoFolder+"/"+ zipname;
			if(null != id && !"".equals(id)) {
				//删除条目数据
				try {
					dakBuilderService.createDak(tableId, DasjService.class).deleteByKey(id,0);
				} catch (PdeBusinessException e) {
					System.out.println("------------------"+e.getMessage());
					//e.printStackTrace();
				}
			}
		}
		FileUtil.copyFile(oldFile, newFile);
		FileUtil.delete(oldFile);
		FileUtil.delete(tempFile);
	}
	
	public void backMemo(String info) {
		FileWriter fw = null;
		try {
			File folder = new File(backFloder+"/"+datestr);
			if(!folder.exists()) {
				folder.mkdirs();
			}
			//如果文件存在,则追加内容;如果文件不存在,则创建文件
			File f=new File(backFloder+"/"+datestr+"/"+datestr+"_执行调度错误日志记录信息.txt");
			fw = new FileWriter(f, true);
		} catch (IOException e) {
			e.printStackTrace();
		}
		PrintWriter pw = new PrintWriter(fw);
		pw.println(info);
		pw.flush();
		try {
			fw.flush();
			pw.close();
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}



你可能感兴趣的:(代码)