解析xml后进行报表的导入
解析xml后进行报表的导入
现将图集的xml进行解析,然后将解析后的文件拼成xml并进行验证判断导入数据是否存在重复数据选择是否把数据进行覆盖
js代码
// 点击导入,弹出框
$('#dg-importBtn').click(function() {
if ($(this).linkbutton('options').disabled == false) {
// 设置获取日志的类型
getting["data"] = {
"loggerType" : "import"
};
$('#importForm').form("reset");
$('#resultDiv').empty();
$('#importdlg').dialog('open').dialog('setTitle', '导入图集数据');
}
});
// 确定导入文件
$("#importConfirmBtn").click(function() {
if ($(this).linkbutton('options').disabled == false) {
var file = $("#file").filebox('getValue');
if (file == "") {
$.messager.alert('提示', '请先选择要上传文件!', 'info');
return;
} else {
var type = file.slice(file.lastIndexOf(".") + 1, file.length);
var checkType = type.toUpperCase();
if (checkType !== "XML") {
$.messager.alert('提示', '所选的文件格式不正确!', 'info');
return;
}
}
var options = {
dataType : "json",
beforeSubmit : function() {
$.messager.progress({
title : '请稍后',
msg : '正在解析文件中...',
});
},
complete : function() {
$.messager.progress('close');
},
success : function(data) {
if (data.success) {
$('#importForm').form("reset");
// 判断是否有编码重复数据,初始化弹出框表格
if ((data.isCodeRepetitive) == true) {
$('#selecteCoverTable').datagrid({
nowrap : true,
autoRowHeight : true,
collapsibale : true,
url : contextPathName + "/reportDisplayInfo/getCodeRepetitiveReportDisplay.do",
singleSelect : false,
rownumbers : true,
fitColumns : true,
fit : true,
idField : "displayCode",
columns : [ [ {
field : 'ck',
checkbox : true,
}, {
field : 'displayCode',
title : '图集编码',
width : '48%',
align : 'left'
}, {
field : 'displayName',
title : '图集名称',
width : '50%',
align : 'left'
} ] ],
onLoadError : function() {
$.messager.alert("警告", "服务器发生错误!");
}
});
$('#selecteCover').dialog('open').dialog("setTitle", "编码重复数据");
var content2 = "解析结果:
";
$.each(data.analysisResult, function(index, value) {
content2 += "" + value + "
";
});
$('#resultDiv').html(content2);
} else {
// 直接打开日志
content = "导入数据日志:
";
$('#importResultDiv').html(content);
$('#showResult').dialog("open").dialog("setTitle", "导入数据日志信息");
// 初始化进度条
$('#importProgressbar').progressbar("setValue", 0);
// 开始获取
flag = true;
// 定时ajax获取日志信息
if (flag) {
dingShiQiArr.push(window.setInterval(function() {
$.ajax(getting)
}, 200));
}
$.ajax({
beforeSubmit : function() {
$.messager.progress({
title : '请稍后',
msg : '正在导入数据中...',
});
},
async : true,
method : "POST",
url : contextPathName + "/reportDisplayInfo/importReportDisplayInfoData.do",
dataType : "json",
data : {
"JSONArrStr" : "",
},
complete : function() {// 完成响应
$.messager.progress('close');
},
success : function(data) {
if (data.status == true) {
// 重载表格(等日志获取完毕后再刷新表格)
$('#dg').datagrid('unselectAll');
$('#dg').datagrid('reload');
}
},
error : function(data) {
$.messager.alert('提示', "服务器发生错误!", 'info');
}
});
}
} else {
$('#importForm').form("reset");
$('#resultDiv').empty();
//判断文件解析是否发生发生异常
if(data.existError==true){
//弹出错误提示
$.messager.confirm('提示', data.errorMsg+'点击确定查看日志详情!', function(r){
if (r){
content = "日志详情:
";
$('#importResultDiv').html(content);
$('#showResult').dialog("open").dialog("setTitle", "日志详情");
// 初始化进度条
$('#importProgressbar').progressbar("setValue", 0);
// 开始获取
flag = true;
// 定时ajax获取日志信息
if (flag) {
dingShiQiArr.push(window.setInterval(function() {
$.ajax(getting)
}, 200));
}
}else{
$('#showResult').dialog("close");
}
});
}}
},
error : function(result) {
$.messager.progress('close');
}
};
$('#importForm').ajaxSubmit(options);
return !1;
}
});
// 确定覆盖数据,传入后台,进行导入操作
$('#coverBtn').click(function() {
// 关闭选择框
$('#selecteCover').dialog("close", true);
// 打开日志框
content = "导入数据日志:
";
$('#importResultDiv').html(content);
$('#showResult').dialog("open").dialog("setTitle", "导入数据日志信息");
// 初始化进度条
$('#importProgressbar').progressbar("setValue", 0);
// 开始获取
flag = true;
// 定时ajax获取日志信息
if (flag) {
dingShiQiArr.push(window.setInterval(function() {
$.ajax(getting)
}, 200));
}
/**
* 将可覆盖数据传入后台
*/
var arr = $("#selecteCoverTable").datagrid('getSelections');
var JSONArr = [];
for (var i = 0;
i < arr.length;
i++) {
var JSONObject = {
"id" : arr[i].id,
"displayCode" : arr[i].displayCode,
"displayName" : arr[i].displayName,
"displayTemplate" : arr[i].displayTemplate,
"layoutType" : arr[i].layoutType,
"enableStatus" : arr[i].enableStatus
};
JSONArr.push(JSONObject);
}
var JSONArrStr = JSON.stringify(JSONArr);
// js数组转json字符串
$.ajax({
async : true,
method : "POST",
url : contextPathName + "/reportDisplayInfo/importReportDisplayInfoData.do",
dataType : "json",
data : {
"JSONArrStr" : JSONArrStr,
},
complete : function() {// 完成响应
$.messager.progress('close');
},
success : function(data) {
if (data.status == true) {
// 重载表格(等日志获取完毕后再刷新表格)
$('#dg').datagrid('unselectAll');
$('#dg').datagrid('reload');
}
},
error : function(data) {
$.messager.alert('提示', "服务器发生错误!", 'info');
}
});
});
// 关闭日志窗口出发(清空缓存,重置定时ajax属性)
$("#claenResult").click(function() {
$('#showResult').dialog("close");
});
// 初始化导入日志关闭时调用函数
$('#showResult').dialog({
onBeforeClose : function() {
$.ajax({
async : false,
method : "POST",
url : contextPathName + '/reportDisplayInfo/claenResult.do',
dataType : "json",
success : function(data) {
$('#showResult').dialog("close", true);
// 重置进度条
$('#importProgressbar').progressbar("setValue", 0);
// 刷新表格
// $('#dg').datagrid('unselectAll');
// $('#dg').datagrid('reload');
flag = false;
$('#importResultDiv').html(content);
// 清除定时器
for (var i = dingShiQiArr.length - 1;
i >= 0;
i--) {
clearInterval(dingShiQiArr[i]);
}
;
},
error : function(data) {
$('#showResult').dialog("close", true);
// 重置进度条
$('#importProgressbar').progressbar("setValue", 0);
// 刷新表格
// $('#dg').datagrid('unselectAll');
// $('#dg').datagrid('reload');
flag = false;
content = "导入数据日志:
";
$('#importResultDiv').html(content);
// 清除定时器
for (var i = dingShiQiArr.length - 1;
i >= 0;
i--) {
clearInterval(dingShiQiArr[i]);
}
;
}
});
return false;
}
});
controller代码
/**
*
* 上传并解析文件
* @param file
* @return
*/
@RequestMapping ("/uploadAnalysisFile") // importReportDisplayInfoData
@ResponseBody
public String uploadAnalysisFile (@RequestParam (value = "https://www.it610.com/article/file", required = false) MultipartFile file,
HttpServletRequest request)
{
HttpSession session = request.getSession (true);
Object obj = session.getAttribute ("importData");
if (null != obj)
{
session.removeAttribute ("importData");
}
ListresultList = new ArrayList();
ListsumResultList = new ArrayList();
Mapdata = https://www.it610.com/article/new HashMap();
boolean result = Boolean.TRUE;
boolean reportDisplayInfoOKButCode = false;
try
{
InputStreamReader read = new InputStreamReader (file.getInputStream (),"utf-8");
// 考虑到编码格式
BufferedReader bufferedReader = new BufferedReader (read);
StringBuffer xmlContent = new StringBuffer ();
String content = "";
while ((content = bufferedReader.readLine ()) != null)
{
xmlContent.append (content);
}
read.close ();
ReportDisplay ReportDisplay = JaxbUtil.converyToJavaBean (xmlContent.toString (), ReportDisplay.class);
if (null != ReportDisplay)
{
resultList.add ("开始解析数据!");
List displayInfos = ReportDisplay.getReportDisplayInfos ();
int reportDisplayInfoError = 0;
if (CollectionUtils.isNotEmpty (displayInfos))
{
for (int i = 0;
i < displayInfos.size ();
i++)
{
ReportDisplayInfoExportDto reportDisplayInfoExportDto = displayInfos.get (i);
if (null != reportDisplayInfoExportDto)
{
// 解析数据
String resultContent = operationDisplayInfoExportDto (reportDisplayInfoExportDto, i,
request);
if (resultContent.contains (OperationConstants.OPERATION_FAIL))
{
reportDisplayInfoError++;
}
resultList.add (resultContent);
}
}
}
// 存关于导入的数据(可新增数据,可更新数据,解析后所有数据)
MapimportData = https://www.it610.com/article/new HashMap();
// 可更新数据
List codeRepetitiveData = https://www.it610.com/article/new ArrayList ();
// 可新增数据
List normalData = https://www.it610.com/article/new ArrayList ();
// 解析后所有数据
List allImportData = https://www.it610.com/article/new ArrayList ();
// 临时容器
List temp = new ArrayList ();
Object objAllImportData = https://www.it610.com/article/session.getAttribute ("importData");
if (null != objAllImportData)
{
importData = https://www.it610.com/article/(Map ) objAllImportData;
allImportData = https://www.it610.com/article/(List ) importData.get ("allImportData");
}
else
{
session.setAttribute ("existError", true);
throw new RuntimeException ("文件中无正确数据!");
}
// 一次sql查编码重复数据
temp = _reportDisplayInfoService.checkCodeIsRepetition (allImportData);
if (CollectionUtils.isNotEmpty (temp))
{
reportDisplayInfoOKButCode = true;
// 筛选出可新增数据(分组[可增加数据,选择更新的数据])
for (ReportDisplayInfo reportDisplayInfo : allImportData)
{
int index = 0;
for (ReportDisplayInfo reportDisplayInfo2 : temp)
{
if (reportDisplayInfo.getDisplayCode ().equals (reportDisplayInfo2.getDisplayCode ()))
{
reportDisplayInfo.setId (reportDisplayInfo2.getId ());
codeRepetitiveData.add (reportDisplayInfo);
break;
}
else
{
index++;
if (index == temp.size ())
{
normalData.add (reportDisplayInfo);
}
}
}
}
}
else
{
normalData.addAll (allImportData);
}
importData.put ("codeRepetitiveData", codeRepetitiveData);
importData.put ("normalData", normalData);
session.setAttribute ("importData", importData);
String reportInfoStr = MessageFormat.format ("总计解析: {0}个图集数据,总计成功:{1}个,其中检测到与数据库中数据发生编码重复:{2}个,失败:{3}个",
CollectionUtils.size (allImportData),
CollectionUtils.size (allImportData),
CollectionUtils.size (codeRepetitiveData),
reportDisplayInfoError);
sumResultList.add (reportInfoStr);
// resultList.add (reportInfoStr);
resultList.add ("解析完成!");
}
}
catch (Exception e)
{
result = Boolean.FALSE;
_logger.error (e.getMessage (), e);
data.put ("errorMsg", "系统发生异常!");
}
data.put ("success", result);
boolean b = false;
Object existError = session.getAttribute ("existError");
if (null != existError)
{
Listlist = new ArrayList();
// 如果为true,则表示在解析文件中主动抛出的异常(文件本身存在重复编码),本次
b = (Boolean) existError;
if (b)
{
data.put ("errorMsg", "文件解析发生异常!");
data.put ("success", Boolean.FALSE);
Object errorCodeDataObj = session.getAttribute ("errorCodeData");
if (null != errorCodeDataObj)
{
list = (List ) errorCodeDataObj;
if (CollectionUtils.isNotEmpty (list))
{
resultList.add ("文件解析发生错误!导入操作中止!");
resultList.add ("文件中发现相同编码数据(显示编码):");
for (String str : list)
{
resultList.add (str);
}
resultList.add ("OVER");
}
}
else
{
resultList.add ("文件中无正常数据!请核对数据文件!");
}
}
data.put ("existError", b);
}
if (CollectionUtils.isEmpty (resultList))
{
data.put ("errorMsg", "系统异常,导入xml格式存在问题");
data.put ("success", Boolean.FALSE);
}
if (result)
{
// 不为false,则表示有编码重复的
if (reportDisplayInfoOKButCode)
{
data.put ("isCodeRepetitive", true);
}
data.put ("analysisResult", sumResultList);
}
// 解析数据信息存入session
session.setAttribute ("resultList", resultList);
String jsonStr = JSONObject.fromObject (data).toString ();
return jsonStr;
}/**
*
* @param reportDisplayInfoExportDto[xml导入数据]
* @param j[数据编号]
* @return
*/
private String operationDisplayInfoExportDto (ReportDisplayInfoExportDto reportDisplayInfoExportDto, int j,
HttpServletRequest request)
{
// 存可导入数据
MapimportData = https://www.it610.com/article/new HashMap();
// 存存解析的所有可导入数据
List allImportData = https://www.it610.com/article/new ArrayList ();
// 存解析的所有可导入数据的编码,用来判断文件中是否存在相同编码的数据(仅在该方法存在)
ListallImportDataCodes = new ArrayList();
// 记录文件中编码重复的编码
ListerrorCodeData = https://www.it610.com/article/new ArrayList();
HttpSession session = request.getSession (true);
Object obj = session.getAttribute ("importData");
String displayCode = "";
if (null != obj)
{
importData = https://www.it610.com/article/(Map ) obj;
allImportData = https://www.it610.com/article/(List ) importData.get ("allImportData");
allImportDataCodes = (List ) importData.get ("allImportDataCodes");
}
Object errorCodeDataObj = session.getAttribute ("errorCodeData");
if (null != errorCodeDataObj)
{
errorCodeData = https://www.it610.com/article/(List ) errorCodeDataObj;
}
int k = j + 1;
// 参数检验
displayCode = reportDisplayInfoExportDto.getDisplayCode ();
if (StringUtils.isEmpty (displayCode))
{
return MessageFormat.format ("第" + k + "个reportDisplayInfo,解析{0},异常编码{1}",
OperationConstants.OPERATION_FAIL, ReportExceptionType.ER00026.getName ());
}String displayName = reportDisplayInfoExportDto.getDisplayName ();
if (StringUtils.isEmpty (displayName))
{
return MessageFormat.format (displayCode + ",解析{0},异常编码{1}", OperationConstants.OPERATION_FAIL,
ReportExceptionType.ER00027.getName ());
}
String displayTemplate = reportDisplayInfoExportDto.getDisplayTemplate ();
if (StringUtils.isEmpty (displayTemplate))
{
return MessageFormat.format (displayCode + ",解析{0},异常编码{1}", OperationConstants.OPERATION_FAIL,
ReportExceptionType.ER00028.getName ());
}String enableStatus = reportDisplayInfoExportDto.getEnableStatus ();
if (StringUtils.isEmpty (enableStatus))
{
return MessageFormat.format (displayCode + ",解析{0},异常编码{1}", OperationConstants.OPERATION_FAIL,
ReportExceptionType.ER00029.getName ());
}
String layoutType = reportDisplayInfoExportDto.getLayoutType ();
if (StringUtils.isEmpty (layoutType))
{
return MessageFormat.format (displayCode + ",解析{0},异常编码{1}", OperationConstants.OPERATION_FAIL,
ReportExceptionType.ER00030.getName ());
}displayTemplate = Encr.decrypt (displayTemplate);
String updateTime = reportDisplayInfoExportDto.getUpdateTime ();
String createTime = reportDisplayInfoExportDto.getCreateTime ();
Date curUpdateTime = null;
int isError = 0;
if (StringUtils.isNotEmpty (updateTime))
{
try
{
curUpdateTime = DateUtil.string2date (updateTime, DateUtil.DATE_TIME_FORMAT);
}
catch (Exception ex)
{
isError++;
}
}
if (StringUtils.isNotEmpty (createTime))
{
try
{
curUpdateTime = DateUtil.string2date (createTime, DateUtil.DATE_TIME_FORMAT);
}
catch (Exception ex)
{
isError++;
}
}if (isError > 0)
{
return MessageFormat.format (displayCode + ",解析{0},异常编码{1}", OperationConstants.OPERATION_FAIL,
ReportExceptionType.ER00025.getName ());
}if (!StringUtils.isNumeric (layoutType)
|| (LayoutType.getLayoutType (Integer.valueOf (layoutType)) == LayoutType.UNKONWN))
{
return MessageFormat.format (displayCode + ",解析{0},异常编码{1}", OperationConstants.OPERATION_FAIL,
ReportExceptionType.ER00031.getName ());
}if (!allImportDataCodes.contains (displayCode))
{
ReportDisplayInfo reportDisplayInfo = new ReportDisplayInfo ();
reportDisplayInfo.setDisplayCode (displayCode);
reportDisplayInfo.setDisplayName (displayName);
reportDisplayInfo.setDisplayTemplate (displayTemplate);
reportDisplayInfo.setLayoutType (layoutType);
reportDisplayInfo.setEnableStatus (enableStatus);
allImportData.add (reportDisplayInfo);
allImportDataCodes.add (displayCode);
importData.put ("allImportDataCodes", allImportDataCodes);
importData.put ("allImportData", allImportData);
session.setAttribute ("importData", importData);
session.setAttribute ("existError", Boolean.FALSE);
return MessageFormat.format (displayCode + ",解析{0}", OperationConstants.OPERATION_SUCCESS);
}
else
{
if (!errorCodeData.contains (displayCode))
{
errorCodeData.add (displayCode);
}
session.setAttribute ("errorCodeData", errorCodeData);
session.setAttribute ("existError", Boolean.TRUE);
return MessageFormat.format (displayCode + ",解析{0},错误编码{1}", OperationConstants.OPERATION_FAIL,
ReportExceptionType.ER00033.getName ());
}
}
@RequestMapping ("/getCodeRepetitiveReportDisplay")
@ResponseBody
public String getCodeRepetitiveReportDisplay (HttpServletRequest request, HttpServletResponse response)
{
// 存可导入数据
MapimportData = https://www.it610.com/article/new HashMap();
// 存编码重复数据
List codeRepetitiveData = https://www.it610.com/article/new ArrayList ();
// 存正常数据
List normalData = https://www.it610.com/article/new ArrayList ();
try
{
HttpSession session = request.getSession (true);
Object obj = session.getAttribute ("importData");
if (null != obj)
{
importData = https://www.it610.com/article/(Map ) obj;
codeRepetitiveData = https://www.it610.com/article/(List ) importData.get ("codeRepetitiveData");
normalData = https://www.it610.com/article/(List ) importData.get ("normalData");
}
}
catch (Exception e)
{
codeRepetitiveData = https://www.it610.com/article/null;
_logger.info ("获取数据失败(编码重复数据)!");
}
MapjsonMap = new HashMap();
jsonMap.put ("total", codeRepetitiveData.size ());
// total键
jsonMap.put ("rows", codeRepetitiveData);
// rows键 存放每页记录 list
JsonConfig config = new JsonConfig ();
config.registerJsonValueProcessor (Date.class, new JsonDateValueProcessor ("yyyy-MM-dd HH:mm:ss"));
String jsonStr = JSONObject.fromObject (jsonMap, config).toString ();
return jsonStr;
}/**
*
* 导入图集数据,将日志存入session,导入完毕返回成功或失败给前台
* @param request
* @param response
*/
@RequestMapping ("/importReportDisplayInfoData")
@ResponseBody
public String importReportDisplayInfoData (HttpServletRequest request, HttpServletResponse response)
{
ListresultList = new ArrayList();
// 存可导入数据
MapimportData = https://www.it610.com/article/new HashMap();
// 存正常数据
List normalData = https://www.it610.com/article/new ArrayList ();
List reportDisplayInfos = new ArrayList ();
MapjsonMap = new HashMap();
Integer importProgress = 100;
int updataNum = 0;
int addNum = 0;
int errorNum = 0;
try
{
HttpSession session = request.getSession (true);
Object obj = session.getAttribute ("importData");
if (null != obj)
{
importData = (Map ) obj;
normalData = https://www.it610.com/article/(List ) importData.get ("normalData");
}
// 将解析日志取出
Object obj2 = session.getAttribute ("resultList");
if (null != obj2)
{
resultList = (List ) obj2;
}
resultList.add ("开始导入数据!");
String jsonArrStr = request.getParameter ("JSONArrStr");
// 接收到数据字符串
if (!StringUtils.isBlank (jsonArrStr))
{
JSONArray arr = JSONArray.fromObject (jsonArrStr);
// 将其解析为JSON数组
List
// 清除缓存
@RequestMapping ("/claenResult")
@ResponseBody
public String claenResult (HttpServletRequest request, HttpServletResponse response)
{
MapjsonMap = new HashMap();
try
{
HttpSession session = request.getSession (true);
Object obj = session.getAttribute ("importData");
if (null != obj)
{
session.removeAttribute ("importData");
}
Object obj2 = session.getAttribute ("resultList");
if (null != obj2)
{
session.removeAttribute ("resultList");
}
Object obj3 = session.getAttribute ("importProgress");
if (null != obj3)
{
session.removeAttribute ("importProgress");
}
Object obj4 = session.getAttribute ("exportProgress");
if (null != obj4)
{
session.removeAttribute ("exportProgress");
}
Object obj5 = session.getAttribute ("exportResultList");
if (null != obj5)
{
session.removeAttribute ("exportResultList");
}
Object obj6 = session.getAttribute ("loggerIndex");
if (null != obj6)
{
session.removeAttribute ("loggerIndex");
}
Object obj7 = session.getAttribute ("exp_loggerIndex");
if (null != obj7)
{
session.removeAttribute ("exp_loggerIndex");
}
Object obj8 = session.getAttribute ("existError");
if (null != obj8)
{
session.removeAttribute ("existError");
}
Object obj9 = session.getAttribute ("errorCodeData");
if (null != obj9)
{
session.removeAttribute ("errorCodeData");
}
jsonMap.put ("status", true);
}
catch (Exception e)
{
_logger.error ("清除缓存信息失败!", e);
jsonMap.put ("status", false);
}String jsonStr = JSONObject.fromObject (jsonMap).toString ();
return jsonStr;
}
【解析xml后进行报表的导入】
推荐阅读
- 开学第一天(下)
- 爱就是希望你好好活着
- 三十年后的广场舞大爷
- Y房东的后半生14
- 七年之痒之后
- MediaRecorder前后摄像头同时录像
- 基于微信小程序带后端ssm接口小区物业管理平台设计
- 迷失的世界(二十七)
- 上班后阅读开始变成一件奢侈的事
- 你有婚内虐待行为吗()