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. Sleep函数的真正用意

    转自:http://blog.csdn.net/boyuejiang/article/details/8908333 关于VOID Sleep(DWORD dwMilliseconds);函数,许多人 ...

  2. http://blog.csdn.net/z69183787/article/details/37819831

    http://blog.csdn.net/z69183787/article/details/37819831

  3. 优先队列 UVA 11997 K Smallest Sums

    题目传送门 题意:训练指南P189 分析:完全参考书上的思路,k^k的表弄成有序表: 表1:A1 + B1 <= A1 + B2 <= .... A1 + Bk 表2:A2 + B1 &l ...

  4. IE下Array.prototype.slice.call(params,0)

    i8 不支持 Array.prototype.slice.call(params,0) params可以是 HTMLCollection.类数组.string字符串

  5. 关于listView 中的聚焦问题

    我在使用listView+adapter 中,遇到一个问题,就是item项添加了若干个可以被监听的控件后 在listView中的setOnItemClickListener失效了 原因是焦点已经在it ...

  6. 每天一个linux命令---tar

    解包/打包语法:tar [主选项+辅选项] 文件或者目录 使用该命令时,主选项是必须要有的,它告诉tar要做什么事情,辅选项是辅助使用的,可以选用. 主选项: c 创建新的档案文件.如果用户想备份一个 ...

  7. underscore.js依赖库函数分析二(查找)

    查找: 在underscore.js封装了对dom查找的操作,find()和filter()函数,find()函数的查找操作是返回首个与条件相符的元素值,filter()函数是找到与条件相符的所有元素 ...

  8. (转)Storm UI 解释

    Storm UI link:http://lbxc.iteye.com/category/221265 本文主要解释下storm ui上各项属性的含义. 1. mainpage 首页主要分为3块: a ...

  9. word 批量修改表格格式

    For i = 1 To ActiveDocument.Tables.Count ActiveDocument.Tables(i).Cell(1, 1).Select With Selection . ...

  10. css3立体旋转动画

    demo地址 效果图 在别人网站上看到一个立体旋转的例子,然后突然想到自己前几天学习的css3旋转,就试着做了一个例子,看起来有一些粗糙. html结构很简单: <div> <ul ...