导入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;
}
*/
}
导入TDP数据包备份的更多相关文章
- mysql导入导出数据,备份,恢复数据
MYSQL 实现导入数据 .备份和恢复数据库 1.使用msql命令导入数据 # mysql -uroot -p 需要选择一个数据库 < runoob.sql #mysql -u username ...
- python 导入数据包的几种方法
1.直接导入整个数据包:improt 数据包 参考代码: # -*- coding:utf-8 -*- # 导入random数据包 import random # 引用random数据包中的randi ...
- 可视化数据包分析工具-CapAnalysis
可视化数据包分析工具-CapAnalysis 我们知道,Xplico是一个从pcap文件中解析出IP流量数据的工具,本文介绍又一款实用工具-CapAnalysis(可视化数据包分析工具),将比Xpli ...
- 记一次oracle创建一个新数据库,并导入正式环境数据库备份的dmp包过程
背景:正式环境oracle数据库定时用exp备份一个dmp包,现在打算在一台机器上创建一个新数据库,并导入这个dmp包. 1.创建数据库 开始 -> 所有程序 -> Oracle -> ...
- ECshop导入淘宝数据包乱码问题解决方法
ECshop在导入淘宝数据包的时候出现数据乱码. 测试版本 ecshop2.73 利用淘宝助手导出一个数据包(.csv),不要一次全部商品导出,最好是将数据包控制在1M左右,因为ecshop对上传文件 ...
- oracle中导入导出数据备份数据库
原文:oracle中导入导出数据备份数据库 数据库所在位置 将数据导出到的文件名 用户名 备份数据库 :exp c ...
- jdbc数据连接池dbcp要导入的jar包
jdbc数据连接池dbcp要导入的jar包 只用导入commons-dbcp-x.y.z.jarcommons-pool-a.b.jar
- mysql查询进程、导入数据包大小设置
mysql查询进程.导入数据包大小设置 zoerywzhou@163.com http://www.cnblogs.com/swje/ 作者:Zhouwan 2017-12-27 查询正在执行的进程: ...
- MySQL 导入外部数据时报错:1153: Got a packet bigger than 'max_allowed_packet' 解决方案
MySQL 导入外部数据时报错:1153: Got a packet bigger than 'max_allowed_packet' 解决方案 zoerywzhou@163.com http://w ...
随机推荐
- css3 -- 浏览器支持
浏览器支持的前缀: 1.浏览器兼容前缀 -webkit-transform:rotate(-3deg); /*为Chrome/Safari*/ -moz-transform:rotate(-3deg) ...
- 停靠技术 Dock
C:\Program Files\Borland\Delphi7\Demos\Docking delphi例子 网上文档 http://www.docin.com/p-95543759.html
- Java 生成16/32位 MD5
http://blog.csdn.net/codeeer/article/details/30044831
- HDU5727 Necklace(枚举 + 二分图最大匹配)
题目大概说有n个yang珠子n个yin珠子,要交替串成一个环形项链,有些yang珠子和某个yin珠子相邻这个yang珠子会不高兴,问最少有几个yang珠子不高兴. 自然会想到直接用状压DP去解,转移很 ...
- WPF – pass multiple parameters to a Command
public class SendCommand : ICommand { public void Execute(object parameter) { var labels = ((object[ ...
- Java集合框架学习总结
转自:http://www.cnblogs.com/oubo/archive/2012/01/07/2394639.html Oubo的博客 以下介绍经常使用的集合类,这里不介绍集合类的使用方法,只介 ...
- CodeForces - 241E Flights 题解
题目大意: 有一个有向无环图,n个点m条边,所有边权为1或2,求一组使所有从1到n的路径长度相同的边权的方案. 思路: 设从1到i的最短路为dist[i],若有一条从x到y的边,则1<=dist ...
- HttpLuaModule 获取Get和Post参数
Get方式: local id = tostring(ngx.var.arg_id) local type = tostring(ngx.var.arg_type) Post方式: ngx.req.r ...
- ACM 关于521
关于521 时间限制:1000 ms | 内存限制:65535 KB 难度:2 描述 Acm队的流年对数学的研究不是很透彻,但是固执的他还是想一头扎进去. 浏览网页的流年忽然看到了网上有人用玫 ...
- Codeforce - Street Lamps
Bahosain is walking in a street of N blocks. Each block is either empty or has one lamp. If there is ...