`

导入TDP数据包备份

 
阅读更多
package org.alfresco.repo.bom.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;

import java.io.FileOutputStream;

import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import org.alfresco.repo.bom.model.BomProductModel;
import org.alfresco.repo.bom.service.BomService;
import org.alfresco.repo.bom.service.ImportService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class ImportUtil {
	private static final Log logger = LogFactory.getLog(ImportUtil.class);
	
	private static final String PROPERTIES_FILE_NAME = "alfresco-global.properties";
	String tempFile = filePath+"temp.zip";
	String unZipPath = filePath;
	
	private static Set<String> xmlPaths;
	private static Set<String> sharePaths;
	
	private BomService bomService;
	public void setBomService(BomService bomService) {
		this.bomService = bomService;
	}
	
	private ImportService importService;
	public void setImportService(ImportService importService){
		this.importService = importService;
	}
	
	private UploadUtil uploadUtil;
	public void setUploadUtil(UploadUtil uploadUtil){
		this.uploadUtil = uploadUtil;
	}
	
	static String filePath;
	static String sharePath;
	static {
		try {
			Resource resource = new ClassPathResource(PROPERTIES_FILE_NAME);
			Properties prop = new Properties();
			prop.load(resource.getInputStream());
			filePath = (String) prop.get("filePath");
			sharePath = (String) prop.get("sharePath");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 导入数据工作
	 * @param input
	 */
	public String toImport(InputStream input){
		String resultMsg = "";
		try {
			if (this.saveTempFile(input)) {
				//logger.error("临时文件保存成功!");
				if (this.toUnzip()) {	
					File temp = new File(tempFile);
					if(temp.exists())//删除临时文件
						temp.delete();
				}
				else {
					return "解压失败!";
				}
			}else{
				return "临时文件保存失败!";
			}
			
			//
			if(xmlPaths!=null && xmlPaths.size()>0)
				this.toParsingXML(xmlPaths);//解析判定XML
			
			if(sharePaths!=null && sharePaths.size()>0)
				this.uploadUtil.execute();//上传相关文件
			
			input.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("导入数据失败,错误信息:"+e.getMessage());
			resultMsg = "导入数据失败,错误信息:"+e.getMessage();
		}
		if(resultMsg=="")
			resultMsg = "导入数据成功!";
		return resultMsg;
	}
	/**
	 * 解析判定 XML
	 * @param paths
	 * @throws IOException 
	 */
	public boolean toParsingXML(Set<String> paths) throws IOException{
		boolean flag = true;
		SAXReader sax = new SAXReader();
		Document document = null;
		InputStream input = null;
		try {
			for(String path:paths){
				input = new FileInputStream(new File(path));
				document = sax.read(input);
				Element rootElement = document.getRootElement();
				if ("bom".equals(rootElement.getName())) {
					this.importService.insertByParsingBom(rootElement);
				}
				if ("ecn".equals(rootElement.getName())) {
					this.importService.insertByParsingEcn(rootElement,sharePaths);
				}
				if ("tdp".equals(rootElement.getName())) {
					this.importService.insertByParsingTdp(rootElement,sharePaths);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			flag = false;
			logger.error("解析XML失败,错误信息:"+e.getMessage());
		}finally{
			if(input!=null)
				input.close();
		}
		return flag;
	}
	/**
	 * 解压文件到 uploadfile路径
	 * @return
	 * @throws IOException 
	 */
	public boolean toUnzip() throws IOException{
		boolean flag = true;
		ZipFile zipFile = null;
		File file = null;
		FileOutputStream out = null;
		InputStream input = null;
		xmlPaths = new HashSet<String>();
		sharePaths = new HashSet<String>();
		try {
			zipFile = new ZipFile(tempFile, "GBK");
			Enumeration<? extends ZipEntry> e = zipFile.getEntries();
			while (e.hasMoreElements()) {
				ZipEntry entry = e.nextElement();
				file = new File(unZipPath+file.separator+entry.getName());
				if (entry.isDirectory()) {
					logger.error("Dir:"+entry.getName());
					file.mkdirs();
				}else {
					File parent = file.getParentFile();
					if (!parent.exists())
						parent.mkdirs();
					out = new FileOutputStream(file);
					input = zipFile.getInputStream(entry);
					this.toWrite(input, out);  //
					//record unzip file path  ( xml and other file type)
					if (entry.getName().endsWith(".xml")) {//f
						// 
						xmlPaths.add(unZipPath+File.separator+entry.getName());
					}else {
						sharePaths.add(sharePath+entry.getName());
					}
				}
			}
			zipFile.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			flag = false;
			logger.error("解压失败,错误信息:"+e.getMessage());
		}finally{
			if (input!=null) 
				input.close();
		}
		
		return flag;
	}	
	/**
	 * 根据xml文件InputStream读取xml内容存入缓存中
	 * @param input
	 * @return
	 */
	public String getStringXML(InputStream input){
		String xml = "";
		StringBuffer buffer = new StringBuffer();
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
			String str = "";
			while((str=reader.readLine())!=null){
				buffer = buffer.append(str+"\n");
			}
		} catch (Exception e) { 
			// TODO Auto-generated catch block
			logger.error("xml文件转换字符串失败,错误信息:"+e.getMessage());
		}
		xml = buffer.toString();
		return xml;
	}
	/**
	 * 将文件流写到临时文件中
	 * @param input
	 */
	public boolean saveTempFile(InputStream input){
		boolean flag = true;
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(tempFile);
			this.toWrite(input, out);//
		} catch (Exception e) {
			// TODO Auto-generated catch block
			flag = false;
			logger.error("保存到临时文件失败,错误信息:"+e.getMessage());
		}
		return flag;
	}
	/**
	 * 写文件
	 * @param input
	 * @param out
	 * @throws IOException 
	 */
	public void toWrite(InputStream input,FileOutputStream out) throws IOException{
		try {
			byte[] data = new byte[1024*1024];
			int len = 0;
			while((len = input.read(data))!=-1){
				out.write(data,0,len);
			}
		} catch (Exception e) {
			// TODO: handle exception
			logger.error("写文件失败,错误信息:"+e.getMessage());
		}finally{
			if (out!=null) {
				out.flush();
				out.close();
			}
		}
	}
	
}

 

package org.alfresco.repo.bom.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.transaction.UserTransaction;

import org.alfresco.repo.bom.model.BomProductModel;
import org.alfresco.repo.bom.util.UploadUtil;
import org.alfresco.repo.db.HibernateSessionFactory;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.service.ServiceRegistry;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Element;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class ImportService {
	
	private static final Log logger = LogFactory.getLog(ImportService.class);
	
	private BomService bomService;
	public void setBomService(BomService bomService) {
		this.bomService = bomService;
	}
	
	protected ServiceRegistry services;
	public void setServiceRegistry(ServiceRegistry services) {
		this.services = services;
	}
	
	private UploadUtil uploadUtil;
	public void setUploadUtil(UploadUtil uploadUtil){
		this.uploadUtil = uploadUtil;
	}
	
	/**
	 * insert data by parsing xml has bom node
	 * @param rootElement
	 * @return
	 */
	public boolean insertByParsingBom(Element rootElement){
		
		boolean flag = true;
		UserTransaction transaction = null;
		try {
			//AuthenticationUtil.setRunAsUser(AuthenticationUtil.getAdminUserName());
			transaction = this.services.getTransactionService().getUserTransaction();
			transaction.begin();
			
			// insert bom_product
			String productID = rootElement.attributeValue("uuid");
			String productName = rootElement.attributeValue("name");
			this.bomService.insertProduct(productID,productName);
			
			//insert bom_unit
			List<Element> units = rootElement.selectNodes("//bom//configuration_context//unit");
			//String unitID = units.get(0).attributeValue("uuid");
			String unitID = units.get(0).getText();
			String unitName = units.get(0).getText();
			bomService.insertUnit(unitID, unitName);
			bomService.insertRelProUnit(productID, unitID);
			
			//insert Rel Pro Unit
			List<Element> items = rootElement.selectNodes("//bom//items//item");
			for(Element item:items){
				String itemID = item.attributeValue("uuid");
				String partNumber = item.selectSingleNode("partnumber").getText();
				String itemName = item.selectSingleNode("name").getText();
				String version = item.selectSingleNode("version").getText();
				String un = item.selectSingleNode("un").getText();
				String make = item.selectSingleNode("make").getText();
				String description = item.selectSingleNode("description").getText();
				bomService.insertItem(itemID, partNumber,itemName, version,un,make,description);
				bomService.insertRelUnitItem(unitID, itemID);
			}
			//insert Rel Item
			List<Element> itemRelElements = rootElement.selectNodes("//bom//structures//relation");
			for(Element element:itemRelElements){
				String parentItemId = element.attributeValue("parent_uuid");
				String childItemId = element.attributeValue("child_uuid");
				bomService.insertRelItem(childItemId, parentItemId);
			}
		} catch (Exception e) {
			// TODO: handle exception
			flag = false;
			//e.printStackTrace();
			logger.error("插入(BOM)数据失败,错误信息:"+e.getMessage());
		}finally{
			if(transaction != null){
				try {
					transaction.commit();
				} catch (Exception e) {
					// TODO: handle exception
					flag = false;
					transaction = null;
					logger.error("插入(BOM)数据提交事务失败,错误信息:"+e.getMessage());
				}
			}
				
		}
		
		return flag;
	}
	
	/**
	 * insert data by parsing xml has ecn node
	 * @param rootElement
	 * @return
	 */
	public boolean insertByParsingEcn(Element rootElement,Set<String> sharePaths){
		boolean flag = true;
		UserTransaction transaction = null;
		try {
			transaction = this.services.getTransactionService().getUserTransaction();
			transaction.begin();
			/*
			String ecnID = rootElement.attributeValue("uuid");
			String type = rootElement.attributeValue("type");
			String date = rootElement.attributeValue("date");
			String editor = AuthenticationUtil.getRunAsUser();
			bomService.insertBomEcnHistory(ecnID, editor, type, date, date, fileName, ecmId);
			*/
			String date = rootElement.attributeValue("date");
			String type = rootElement.attributeValue("type");
			String ecmID = "";
			String version = "";
			String sharePath = "";
			
			List<Element> items = rootElement.selectNodes("//ecn//general_info//components//component");
			for(Element itemElement:items){
				String partNumber = itemElement.attributeValue("partnumber");
				List<Element> ecnResultFileElements = rootElement.selectNodes("//ecn//released_files//file");
				for(Element element:ecnResultFileElements){
					String id = element.attributeValue("uuid");
					String name = element.attributeValue("storage");
					for(String path:sharePaths){
						if(path.endsWith(name))
							sharePath = this.getSharePath(path);
					}
					if ("".equals(sharePath)) {
						logger.error("导入文件数据错误,"+name+"文件不存在!");
						return false;
					}
					bomService.insertTempDoc(id, name, partNumber, sharePath, "0");
					bomService.insertEcn(type, ecmID, id, name, version, date, sharePath);
					bomService.insertRelItemEcn(partNumber, id);
				}
			}
			
		} catch (Exception e) {
			flag = false;
			logger.error("插入(ECN)数据失败,错误信息:"+e.getMessage());
			// TODO: handle exception
		}finally{
			if (transaction != null) {
				try {
					transaction.commit();
				} catch (Exception e) {
					// TODO: handle exception
					flag = false;
					transaction = null;
					logger.error("插入(ECN)数据提交事务失败,错误信息:"+e.getMessage());
				}
			}
		}
		return flag;
	}
	/**
	 * insert data by parsing xml has tdp node
	 * @param rootElement
	 * @return
	 */
	public boolean insertByParsingTdp(Element rootElement,Set<String> sharePaths){
		boolean flag = true;
		UserTransaction transaction = null;
		try {
			transaction = this.services.getTransactionService().getUserTransaction();
			transaction.begin();
			
			List<Element> tdpElements = rootElement.selectNodes("//tdp");
			String itemId = tdpElements.get(0).attributeValue("partnumber");
			String version = tdpElements.get(0).attributeValue("version");
			String sharePath = "";
	
			String sign = "0"; 
			String ecmId = "";
			String serialNumber = "";
			String date = "";
			
			List<Element> doc3DElements = rootElement.selectNodes("//tdp//model_definitions//engineering_model_definitions//tdms//tdm");
			
			for(Element element:doc3DElements){
				String type = element.attributeValue("aspect");
				//
				List<Element> sequences = element.elements("sequence");
				Element sequence = null;
				if(sequences!=null && sequences.size()>1)
					sequence = sequences.get(sequences.size()-1);
				else
					sequence = sequences.get(0);
					
				//Element sequence = sequences.get(sequences.size()-1);
				//
				//Element seq= (Element)element.element("sequence");
				List<Element> files = sequence.elements("file");
				for(Element file:files){
					String id = file.attributeValue("uuid");
					String name = file.getText();
					for(String path:sharePaths){
						if(path.endsWith(name))
							sharePath = this.getSharePath(path);
					}
					if ("".equals(sharePath)) {
						logger.error("导入文件数据错误,"+name+"文件不存在!");
						return false;
					}
					bomService.insertTempDoc(id, name, itemId, sharePath, sign);
					bomService.insertRelItemDoc(itemId, id);
					bomService.insertDoc(ecmId, id, name, version, serialNumber, "", "1", type, sharePath);
				}
			}
			
			//2D图纸
			
			List<Element> doc2DElements = rootElement.selectNodes("//tdp//model_definitions//engineering_model_definitions//drawings//drawing");
			for(Element element:doc2DElements){
				String type = element.attributeValue("aspect");
				Element sequence = element.element("sequence");
				List<Element> files = sequence.elements("file");
				for(Element e:files){
					String id = e.attributeValue("uuid");
					String name = e.getText();
					for(String path:sharePaths){
						if(path.endsWith(name))
							sharePath = this.getSharePath(path);
					}
					if ("".equals(sharePath)) {
						logger.error("导入文件数据错误,"+name+"文件不存在!");
						return false;
					}
					bomService.insertTempDoc(id, name, itemId, sharePath, sign);
					bomService.insertRelItemDoc(itemId,id);
					bomService.insertDoc(ecmId, id, name, version, serialNumber, date, "2", type, sharePath);
				}
				
			}
			
		
			List<Element> documentElements = rootElement.selectNodes("//tdp//model_definitions//engineering_model_definitions//documents//document");
			for(Element element:documentElements){
				String type = element.attributeValue("aspect");
				Element seq = element.element("sequence");
				List<Element> filelElements = seq.elements("file");
				for(Element e:filelElements){
					String id = e.attributeValue("uuid");
					String name = e.getText();
					for(String path:sharePaths){
						if(path.endsWith(name))
							sharePath = this.getSharePath(path);
					}
					if ("".equals(sharePath)) {
						logger.error("导入文件数据错误,"+name+"文件不存在!");
						return false;
					}
					bomService.insertTempDoc(id, name, itemId, sharePath, sign);
					bomService.insertRelItemDoc(itemId,id);
					bomService.insertDoc(ecmId, id, name, version, serialNumber, "", "3", type, sharePath);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			flag = false;
			logger.error("插入(TDP)数据失败,错误信息:"+e.getMessage());
		}finally{
			if (transaction != null) {
				try {
					transaction.commit();
				} catch (Exception e) {
					// TODO: handle exception
					flag = false;
					transaction = null;
					logger.error("插入(TDP)数据提交事务失败,错误信息:"+e.getMessage());
				}
			}
		}
		return flag;
	}
	/**
	 * 去文件名获取sharePath
	 * @param sharePath
	 * @return
	 */
	public String getSharePath(String sharePath){
		String[] s = sharePath.split("/");
		String result = "";
		for (int i = 0; i < s.length-1; i++) {
			result+=s[i]+"/";
		}
		return result;
	}
	/*
	public boolean insertByParsingBom(BomProductModel model){
		boolean flag = true;
		Session session = HibernateSessionFactory.getSession();
		String sql = "";
		Transaction tx = null;
		Query query = null;
		try {
			sql = "select * from bom_product where id ='"+model.getId()+"'";
			tx = session.beginTransaction();
			query = session.createSQLQuery(sql);
			List list= query.list();
			if (list!=null && list.size()>0) {
				flag = false;
				logger.error("待插入数据重复!");
			}else {
				sql = "insert into bom_product(id,name) values('"+model.getId()+"','"+model.getName()+"')";
				query = session.createSQLQuery(sql);
				int result = query.executeUpdate();
				tx.commit();
				if (result==1) {
					logger.error("数据插入成功!");
				}else {
					logger.error("数据插入失败!");
				}
			}
			
		} catch (Exception e) {
			  if ((tx != null) && (tx.isActive()))
			  {
			    tx.rollback();
			  }
			  flag = false;
			// TODO: handle exception
		}
		return flag;
	}
	*/
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics