导入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 ...
随机推荐
- struts2总结一:MVC设计模式
设计模式 一.什么是编程里面的设计模式? 1.设计模式是一套被反复使用,多数人知晓的,代码设计经验的总结. 2.模式必须是典型问题(不是个别问题)的解决方案. 二.设计模式的作用 1.解决一类问题的成 ...
- 最近点对问题 POJ 3714 Raid && HDOJ 1007 Quoit Design
题意:有n个点,问其中某一对点的距离最小是多少 分析:分治法解决问题:先按照x坐标排序,求解(left, mid)和(mid+1, right)范围的最小值,然后类似区间合并,分离mid左右的点也求最 ...
- 解决(空密码的root)提示修改phpmyadmin用户密码
打开 phpmyadmin数据表,点击权限 如果没有,请参考:http://jingyan.baidu.com/article/636f38bb293a9bd6b846100d.html 创建 在 ...
- CF#335 Sorting Railway Cars
Sorting Railway Cars time limit per test 2 seconds memory limit per test 256 megabytes input standar ...
- Learning storm book 笔记8-Log Processing With Storm
有代码的书籍看起来就是爽,看完顺便跑个demo,感觉很爽! 场景分析 主要是利用apache的访问日志来进行分析统计 如用户的IP来源,来自哪个国家或地区,用户使用的Os,浏览器等信息,以及像搜索的热 ...
- ccc tiledmap 获取元素属性
cc.Class({ extends: cc.Component, properties: { elementLable: { default: null, type : cc.Label }, ma ...
- <构建之法>第十一章、十二章有感
十一章:软件设计与实现 工作时要懂得平衡进度和质量.我一直有一个困扰:像我们团队这次做 男神女神配 社区交友网,我负责主页的设计及内容模块,有个队友负责网站的注册和登录模块,有个队友负责搜索模块,有个 ...
- [Noi2015]软件包管理器 题解
题目大意: 有n个软件安装包,除第一个以外,其他的要在另一个安装包的基础上安装,且无环,问在安装和卸载某个软件包时,这个操作实际上会改变多少个软件包的安装状态. 思路: 可构成树,用树链剖分,线段树. ...
- [Cocos2D-x For WP8]CocosDenshion音频播放
Cocos2D-x的音频分为长时间的背景音乐和短的音效两种,我们可以通过SimpleAudioEngine::sharedEngine()方法来获取音频播放的引擎,然后调用对音频相关的操作方法就可以了 ...
- 用存储过程 将大段的SQL藏起来
在日常工作中,当面对比较复杂的数据库操作时不免要写一些比较长的SQL,由于某系SQL有些长(目前我写的最长的貌似有30多行吧),这时候长会面临这个 方法 优点 缺点 用"+"串 ...