`

导入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;
	}
	*/
}

 

分享到:
评论

相关推荐

    TSM5.2+TDP+RMAN备份安装配置及说明

    总结来说,TSM5.2、TDP和RMAN的结合使用,提供了一套强大的Oracle数据库备份和恢复解决方案。通过详细配置TSM SERVER、客户端和TDP,可以确保数据的安全存储,同时简化备份和恢复过程,适应企业对数据保护的高要求。...

    TDP-UDP.rar_TDP UDP 区别_UDP和TDP_tdp_tdp和udp区别

    - TDP可能提供更高的可靠性,确保数据按照正确的顺序到达,并处理丢失的数据包。 3. **流量控制和拥塞控制**: - UDP没有内置的流量控制和拥塞控制机制,可能导致网络拥塞。 - TDP可能包含这些机制,以避免网络...

    TDP协议 网络编程协议

    ### TDP协议网络编程知识点详解 #### 一、TDP协议概述 TDP(TCP-over-UDP library)是一种新兴的网络编程协议,旨在为开发者提供一种在UDP协议基础之上实现的、具有TCP特性且易于使用的网络通信解决方案。该协议...

    TDP.rar_Shy_UDP 可靠_tcp over udp 实现_tdp_tdp u

    1. **序列号与确认机制**:TDP为每个发送的数据包分配一个唯一的序列号,并在接收端通过确认机制来确保数据包的正确接收。如果未收到确认,发送端将重发数据包,类似于TCP的ACK机制。 2. **错误检测与纠正**:TDP...

    Mobile Pascal TDP Tweaker

    英伟达帕斯卡架构显卡TDP修改工具。

    TCP/TDP 飞鸽传书

    TCP(Transmission Control Protocol)是互联网协议栈中最基础的传输层协议之一,负责确保数据的可靠传输,通过确认、重传和流量控制机制,确保数据包在网络中的准确无误地到达目的地。而TDP(Telephony Data ...

    TDP for Oracle

    TDP(Tivoli® Storage Manager for Databases)是IBM开发的一款数据库保护和备份管理解决方案,专为提高数据恢复能力和减少备份窗口时间而设计。TDP for Oracle是该系列中针对Oracle数据库的特定产品,它利用了RMAN...

    特定电磁波(TDP)照射治疗冻疮的疗效观察.pdf

    【特定电磁波(TDP)照射治疗冻疮的疗效观察】 冻疮是由于长时间暴露于湿冷环境中导致的皮肤病变,主要表现为皮肤红肿、疼痛、瘙痒,并可能伴有水疱或溃疡。常规治疗方法包括使用冻疮膏、庆大霉素或红霉素软膏等...

    TDP治疗仪操作流程图.pdf

    【TDP治疗仪操作流程详解】 TDP治疗仪是一种利用特定波长的电磁辐射进行物理治疗的设备,常用于缓解疼痛、促进伤口愈合以及改善血液循环等。在使用TDP治疗仪时,遵循正确的操作流程至关重要,以确保治疗的安全性和...

    Mobile Pascal TDP Tweaker显卡vbios功耗修改查看软件

    可修改英伟达十代及以下的显卡vbios

    2019 RoboCup Small Size League TDP(all)

    在“2019 RoboCup Small Size League TDP”(Technical Development Plan)中,各参赛队伍分享了他们的设计思路、技术实现和比赛策略,这为我们提供了深入了解机器人足球技术的宝贵资料。TDP包括了硬件设计、软件...

    TDP-245系列打印机驱动安装及使用说明

    TDP-245系列打印机是一款专业的条形码和二维码打印设备,广泛应用于物流、零售、医疗等行业的标签打印。其驱动安装及使用是确保打印机正常运行的关键步骤。以下是关于这个系列打印机驱动安装及使用的详细知识讲解: ...

    TDP特定电磁波肛部理疗对环状混合痔患者术后恢复的作用.pdf

    标题和描述中提到的《TDP特定电磁波肛部理疗对环状混合痔患者术后恢复的作用》是一篇关于医疗应用的技术文章,研究了TDP(Therapeutic Device for the Prevention)特定电磁波理疗技术在环状混合痔手术后患者康复中...

    CPU中TDP技术是什么.docx

    **CPU中的TDP技术详解** TDP(Thermal Design Power),中文名为热设计功率,是一项衡量计算机处理器(CPU)功耗的重要指标。它并非代表CPU的实际运行功率,而是CPU公司为某一系列处理器设定的散热器设计参考功率...

    XILINX-7SERIES-BARM-TDP-MACRO

    XILINX-7SERIES-BARM-TDP-MACRO

    特定电磁波治疗仪(TDP)操作说明及注意事项.pdf

    特定电磁波治疗仪(TDP)操作说明及注意事项 特定电磁波治疗仪(TDP)是一种非侵入性治疗设备,通过电磁波来治疗各种疾病和损伤。为了确保正确和安全地使用这种设备,本文将详细介绍特定电磁波治疗仪的操作说明和...

    TDP治疗仪的使用.doc

    TDP治疗仪的使用 TDP治疗仪是一种高效、安全、简单的理疗型医疗器械。其治疗板根据人体必须的几十种元素,通过科学配方涂制而成。在温度的作用下,能产生出带有各种元素特征信息的振荡信号,故命名为“特定电磁波谱...

    功耗≠TDP CPU实际功耗解疑.pdf

    功耗≠TDP CPU实际功耗解疑 在讨论 CPU 的功耗时,我们经常听到两个概念:TDP(Thermal Design Power)和实际功耗。许多人认为 TDP 就是 CPU 的实际功耗,但实际上它们是不同的概念,在实际应用中存在一定的差异。...

    TI-TDP158.pdf

    TI-TDP158 HDMI转接驱动器 TI-TDP158是一款交流耦合型高清多媒体接口(HDMI)信号转接驱动器,支持数字视频接口(DVI)1.0和高清多媒体接口(HDMI)1.4b和2.0b输出信号。该器件支持四条TMDS通道和数字显示控制(DDC)接口,...

Global site tag (gtag.js) - Google Analytics