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数据包备份的更多相关文章

  1. mysql导入导出数据,备份,恢复数据

    MYSQL 实现导入数据 .备份和恢复数据库 1.使用msql命令导入数据 # mysql -uroot -p 需要选择一个数据库 < runoob.sql #mysql -u username ...

  2. python 导入数据包的几种方法

    1.直接导入整个数据包:improt 数据包 参考代码: # -*- coding:utf-8 -*- # 导入random数据包 import random # 引用random数据包中的randi ...

  3. 可视化数据包分析工具-CapAnalysis

    可视化数据包分析工具-CapAnalysis 我们知道,Xplico是一个从pcap文件中解析出IP流量数据的工具,本文介绍又一款实用工具-CapAnalysis(可视化数据包分析工具),将比Xpli ...

  4. 记一次oracle创建一个新数据库,并导入正式环境数据库备份的dmp包过程

    背景:正式环境oracle数据库定时用exp备份一个dmp包,现在打算在一台机器上创建一个新数据库,并导入这个dmp包. 1.创建数据库 开始 -> 所有程序 -> Oracle -> ...

  5. ECshop导入淘宝数据包乱码问题解决方法

    ECshop在导入淘宝数据包的时候出现数据乱码. 测试版本 ecshop2.73 利用淘宝助手导出一个数据包(.csv),不要一次全部商品导出,最好是将数据包控制在1M左右,因为ecshop对上传文件 ...

  6. oracle中导入导出数据备份数据库

    原文:oracle中导入导出数据备份数据库 数据库所在位置                         将数据导出到的文件名                    用户名 备份数据库 :exp c ...

  7. jdbc数据连接池dbcp要导入的jar包

    jdbc数据连接池dbcp要导入的jar包 只用导入commons-dbcp-x.y.z.jarcommons-pool-a.b.jar

  8. mysql查询进程、导入数据包大小设置

    mysql查询进程.导入数据包大小设置 zoerywzhou@163.com http://www.cnblogs.com/swje/ 作者:Zhouwan 2017-12-27 查询正在执行的进程: ...

  9. 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 ...

随机推荐

  1. canvas 3D运动球效果

    <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content ...

  2. java,我准备好了

    1.你对自己的未来有什么规划?做了哪些准备? 长期上学好公务员和本专业知识,将来能找一份好工作,并能在职务上履行好相称的工作.短期上在下一学期拿一等奖学金,尽快入党,考出英语四级和二级c语言.任何成就 ...

  3. iOS学习04C语言数组

    1.一维数组 数组:具有相同类型的成员组成的一组数据 1> 定义 元素:数组中存放的数据成为数组的元素     数组是构造类型,用{...}来给构造类型赋初始值,类型修饰符用来表示元素的类型 类 ...

  4. Educational Codeforces Round 15 [111110]

    注意一个词:连续 #include<stdio.h> #include<stdlib.h> #include<string.h> #include<bits/ ...

  5. 【转】敏捷开发 Scrum 总结

    转:http://www.open-open.com/lib/view/open1330413325514.html 最近把之前学习 Scrum 的资料整理为一篇文档,在接下来的团队和项目开发中,根据 ...

  6. Grunt vs Gulp

    grunt vs gulp 虽然gulp已经出来很久了,但是一直没有去使用过.得益于最近项目需要,就尝试了一下,以下从几个要点讲一下grunt和gulp使用的区别,侧重讲一下在使用gulp过程中发现的 ...

  7. IOS之同步请求、异步请求、GET请求、POST请求

    .同步请求可以从因特网请求数据,一旦发送同步请求,程序将停止用户交互,直至服务器返回数据完成,才可以进行下一步操作, .异步请求不会阻塞主线程,而会建立一个新的线程来操作,用户发出异步请求后,依然可以 ...

  8. BZOJ3212 Pku3468 A Simple Problem with Integers 题解

    题目大意: 一个数列,有两个操作:1.修改操作,将一段区间内的数加上c:2.查询操作,查询一段区间内的数的和. 思路: 线段树裸题,区间修改.区间查询,维护和以及加上的数,由于无序,不需要向下推标记, ...

  9. Codeforces Round #233 (Div. 2) B. Red and Blue Balls

    #include <iostream> #include <string> using namespace std; int main(){ int n; cin >&g ...

  10. 【bzoj1455】罗马游戏 可并堆

    2016-05-31  10:04:41 可并堆的裸题. 左偏树(小根堆为例 性质 1.满足堆的性质,每个节点权值小于左右儿子权值 2.每个节点有dis值,表示子树最浅的叶子深度加1 3.左子树dis ...