提交 9cc8df19 编写于 作者: O o2null

codeSafe代码第二次扫描

上级 f9d2e6b6
......@@ -33,9 +33,9 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem;
* 抽象Excel2003读取器,通过实现HSSFListener监听器,采用事件驱动模式解析excel2003
* 中的内容,遇到特定事件才会触发,大大减少了内存的使用。
*/
public class Excel2003Reader implements HSSFListener{
public class Excel2003Reader implements HSSFListener {
private int minColumns = -1;
private POIFSFileSystem fs;
// private POIFSFileSystem fs;
private int lastRowNumber;
private int lastColumnNumber;
......@@ -44,14 +44,14 @@ public class Excel2003Reader implements HSSFListener{
/** For parsing Formulas */
private SheetRecordCollectingListener workbookBuildingListener;
//excel2003工作薄
// excel2003工作薄
private HSSFWorkbook stubWorkbook;
// Records we pick up as we process
private SSTRecord sstRecord;
private FormatTrackingHSSFListener formatListener;
//表索引
// 表索引
private int sheetIndex = -1;
private BoundSheetRecord[] orderedBSRs;
@SuppressWarnings("rawtypes")
......@@ -61,67 +61,70 @@ public class Excel2003Reader implements HSSFListener{
private int nextRow;
private int nextColumn;
private boolean outputNextStringRecord;
//当前行
// 当前行
private int curRow = 0;
//存储行记录的容器
// 存储行记录的容器
private List<String> rowlist = new ArrayList<String>();;
@SuppressWarnings( "unused")
@SuppressWarnings("unused")
private String sheetName;
private String fileKey;
private int startRow;
private IRowReader rowReader;
public void setRowReader(IRowReader rowReader, String fileKey, int startRow ){
public void setRowReader(IRowReader rowReader, String fileKey, int startRow) {
this.rowReader = rowReader;
this.fileKey = fileKey;
this.startRow = startRow;
}
/**
* 遍历excel下所有的sheet
* @param fileKey
*
* @param fileKey
* @throws IOException
*/
public void process(String fileName ) throws IOException {
this.fs = new POIFSFileSystem(new FileInputStream(fileName));
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener( this);
formatListener = new FormatTrackingHSSFListener(listener);
HSSFEventFactory factory = new HSSFEventFactory();
HSSFRequest request = new HSSFRequest();
if ( outputFormulaValues ) {
request.addListenerForAllRecords( formatListener );
} else {
workbookBuildingListener = new SheetRecordCollectingListener( formatListener);
request.addListenerForAllRecords(workbookBuildingListener);
public void process(String fileName) throws IOException {
try (POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(fileName))) {
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener(this);
formatListener = new FormatTrackingHSSFListener(listener);
HSSFEventFactory factory = new HSSFEventFactory();
HSSFRequest request = new HSSFRequest();
if (outputFormulaValues) {
request.addListenerForAllRecords(formatListener);
} else {
workbookBuildingListener = new SheetRecordCollectingListener(formatListener);
request.addListenerForAllRecords(workbookBuildingListener);
}
factory.processWorkbookEvents(request, fs);
}
factory.processWorkbookEvents(request, fs);
//数据读取完成
// 数据读取完成
}
/**
* 遍历excel下所有的sheet
* @param fileKey
*
* @param fileKey
* @throws IOException
*/
public void process( InputStream is ) throws IOException {
this.fs = new POIFSFileSystem( is );
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener( this);
formatListener = new FormatTrackingHSSFListener(listener);
HSSFEventFactory factory = new HSSFEventFactory();
HSSFRequest request = new HSSFRequest();
if ( outputFormulaValues ) {
request.addListenerForAllRecords( formatListener );
} else {
workbookBuildingListener = new SheetRecordCollectingListener( formatListener);
request.addListenerForAllRecords(workbookBuildingListener);
public void process(InputStream is) throws IOException {
try (POIFSFileSystem fs = new POIFSFileSystem(is)) {
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener(this);
formatListener = new FormatTrackingHSSFListener(listener);
HSSFEventFactory factory = new HSSFEventFactory();
HSSFRequest request = new HSSFRequest();
if (outputFormulaValues) {
request.addListenerForAllRecords(formatListener);
} else {
workbookBuildingListener = new SheetRecordCollectingListener(formatListener);
request.addListenerForAllRecords(workbookBuildingListener);
}
factory.processWorkbookEvents(request, fs);
}
factory.processWorkbookEvents(request, fs);
//数据读取完成
// 数据读取完成
}
/**
* HSSFListener 监听方法,处理 Record
*/
......@@ -132,107 +135,104 @@ public class Excel2003Reader implements HSSFListener{
String thisStr = null;
String value = null;
switch (record.getSid()) {
case BoundSheetRecord.sid:
boundSheetRecords.add(record);
break;
case BOFRecord.sid:
BOFRecord br = (BOFRecord) record;
if (br.getType() == BOFRecord.TYPE_WORKSHEET) {
// 如果有需要,则建立子工作薄
if (workbookBuildingListener != null && stubWorkbook == null) {
stubWorkbook = workbookBuildingListener
.getStubHSSFWorkbook();
}
sheetIndex++;
if (orderedBSRs == null) {
orderedBSRs = BoundSheetRecord
.orderByBofPosition(boundSheetRecords);
}
sheetName = orderedBSRs[sheetIndex].getSheetname();
case BoundSheetRecord.sid:
boundSheetRecords.add(record);
break;
case BOFRecord.sid:
BOFRecord br = (BOFRecord) record;
if (br.getType() == BOFRecord.TYPE_WORKSHEET) {
// 如果有需要,则建立子工作薄
if (workbookBuildingListener != null && stubWorkbook == null) {
stubWorkbook = workbookBuildingListener.getStubHSSFWorkbook();
}
break;
case SSTRecord.sid:
sstRecord = (SSTRecord) record;
break;
case BlankRecord.sid:
BlankRecord brec = (BlankRecord) record;
thisRow = brec.getRow();
thisColumn = brec.getColumn();
thisStr = "";
rowlist.add(thisColumn, thisStr);
break;
case BoolErrRecord.sid: //单元格为布尔类型
BoolErrRecord berec = (BoolErrRecord) record;
thisRow = berec.getRow();
thisColumn = berec.getColumn();
thisStr = berec.getBooleanValue()+"";
rowlist.add(thisColumn, thisStr);
break;
case FormulaRecord.sid: //单元格为公式类型
FormulaRecord frec = (FormulaRecord) record;
thisRow = frec.getRow();
thisColumn = frec.getColumn();
if (outputFormulaValues) {
if (Double.isNaN(frec.getValue())) {
// Formula result is a string
// This is stored in the next record
outputNextStringRecord = true;
nextRow = frec.getRow();
nextColumn = frec.getColumn();
} else {
thisStr = formatListener.formatNumberDateCell(frec);
}
} else {
thisStr = '"' + HSSFFormulaParser.toFormulaString(stubWorkbook, frec.getParsedExpression()) + '"';
}
rowlist.add(thisColumn,thisStr);
break;
case StringRecord.sid://单元格中公式的字符串
if (outputNextStringRecord) {
// String for formula
StringRecord srec = (StringRecord) record;
thisStr = srec.getString();
thisRow = nextRow;
thisColumn = nextColumn;
outputNextStringRecord = false;
sheetIndex++;
if (orderedBSRs == null) {
orderedBSRs = BoundSheetRecord.orderByBofPosition(boundSheetRecords);
}
break;
case LabelRecord.sid:
LabelRecord lrec = (LabelRecord) record;
curRow = thisRow = lrec.getRow();
thisColumn = lrec.getColumn();
value = lrec.getValue().trim();
value = value.equals("")?" ":value;
this.rowlist.add(thisColumn, value);
break;
case LabelSSTRecord.sid: //单元格为字符串类型
LabelSSTRecord lsrec = (LabelSSTRecord) record;
curRow = thisRow = lsrec.getRow();
thisColumn = lsrec.getColumn();
if (sstRecord == null) {
rowlist.add(thisColumn, " ");
sheetName = orderedBSRs[sheetIndex].getSheetname();
}
break;
case SSTRecord.sid:
sstRecord = (SSTRecord) record;
break;
case BlankRecord.sid:
BlankRecord brec = (BlankRecord) record;
thisRow = brec.getRow();
thisColumn = brec.getColumn();
thisStr = "";
rowlist.add(thisColumn, thisStr);
break;
case BoolErrRecord.sid: // 单元格为布尔类型
BoolErrRecord berec = (BoolErrRecord) record;
thisRow = berec.getRow();
thisColumn = berec.getColumn();
thisStr = berec.getBooleanValue() + "";
rowlist.add(thisColumn, thisStr);
break;
case FormulaRecord.sid: // 单元格为公式类型
FormulaRecord frec = (FormulaRecord) record;
thisRow = frec.getRow();
thisColumn = frec.getColumn();
if (outputFormulaValues) {
if (Double.isNaN(frec.getValue())) {
// Formula result is a string
// This is stored in the next record
outputNextStringRecord = true;
nextRow = frec.getRow();
nextColumn = frec.getColumn();
} else {
value = sstRecord
.getString(lsrec.getSSTIndex()).toString().trim();
value = value.equals("")?" ":value;
rowlist.add(thisColumn,value);
thisStr = formatListener.formatNumberDateCell(frec);
}
break;
case NumberRecord.sid: //单元格为数字类型
NumberRecord numrec = (NumberRecord) record;
curRow = thisRow = numrec.getRow();
thisColumn = numrec.getColumn();
value = formatListener.formatNumberDateCell(numrec).trim();
value = value.equals("")?" ":value;
// 向容器加入列值
} else {
thisStr = '"' + HSSFFormulaParser.toFormulaString(stubWorkbook, frec.getParsedExpression()) + '"';
}
rowlist.add(thisColumn, thisStr);
break;
case StringRecord.sid:// 单元格中公式的字符串
if (outputNextStringRecord) {
// String for formula
StringRecord srec = (StringRecord) record;
thisStr = srec.getString();
thisRow = nextRow;
thisColumn = nextColumn;
outputNextStringRecord = false;
}
break;
case LabelRecord.sid:
LabelRecord lrec = (LabelRecord) record;
curRow = thisRow = lrec.getRow();
thisColumn = lrec.getColumn();
value = lrec.getValue().trim();
value = value.equals("") ? " " : value;
this.rowlist.add(thisColumn, value);
break;
case LabelSSTRecord.sid: // 单元格为字符串类型
LabelSSTRecord lsrec = (LabelSSTRecord) record;
curRow = thisRow = lsrec.getRow();
thisColumn = lsrec.getColumn();
if (sstRecord == null) {
rowlist.add(thisColumn, " ");
} else {
value = sstRecord.getString(lsrec.getSSTIndex()).toString().trim();
value = value.equals("") ? " " : value;
rowlist.add(thisColumn, value);
break;
default:
break;
}
break;
case NumberRecord.sid: // 单元格为数字类型
NumberRecord numrec = (NumberRecord) record;
curRow = thisRow = numrec.getRow();
thisColumn = numrec.getColumn();
value = formatListener.formatNumberDateCell(numrec).trim();
value = value.equals("") ? " " : value;
// 向容器加入列值
rowlist.add(thisColumn, value);
break;
default:
break;
}
// 遇到新行的操作
......@@ -245,7 +245,7 @@ public class Excel2003Reader implements HSSFListener{
MissingCellDummyRecord mc = (MissingCellDummyRecord) record;
curRow = thisRow = mc.getRow();
thisColumn = mc.getColumn();
rowlist.add(thisColumn," ");
rowlist.add(thisColumn, " ");
}
// 更新行和列的值
......@@ -264,12 +264,12 @@ public class Excel2003Reader implements HSSFListener{
}
lastColumnNumber = -1;
// 每行结束时, 调用getRows() 方法
rowReader.getRows(sheetIndex,curRow, rowlist, this.fileKey, this.startRow );
rowReader.getRows(sheetIndex, curRow, rowlist, this.fileKey, this.startRow);
// 清空容器
rowlist.clear();
}
}
}
......@@ -41,24 +41,22 @@ public abstract class AbstractExcel2007Writer {
String sheetRef = sheet.getPackagePart().getPartName().getName();
// 保存模板
FileOutputStream os = new FileOutputStream("template.xlsx");
wb.write(os);
os.close();
try (FileOutputStream os = new FileOutputStream("template.xlsx")) {
wb.write(os);
}
// 生成xml文件
File tmp = File.createTempFile("sheet", ".xml");
Writer fw = new FileWriter(tmp);
sw = new SpreadsheetWriter(fw);
generate();
fw.close();
try (Writer fw = new FileWriter(tmp)) {
sw = new SpreadsheetWriter(fw);
generate();
}
// 使用产生的数据替换模板
File templateFile = new File("template.xlsx");
FileOutputStream out = new FileOutputStream(fileName);
substitute(templateFile, tmp, sheetRef.substring(1), out);
out.close();
// 删除文件之前调用一下垃圾回收器,否则无法删除模板文件
System.gc();
try (FileOutputStream out = new FileOutputStream(fileName)) {
substitute(templateFile, tmp, sheetRef.substring(1), out);
}
// 删除临时模板文件
if (templateFile.isFile() && templateFile.exists()) {
templateFile.delete();
......
package com.x.attendance.assemble.control.service;
import com.x.attendance.assemble.control.Business;
import com.x.attendance.assemble.control.jaxrs.attendanceworkdayconfig.AttendanceWorkDayConfigAction;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.organization.Identity;
import com.x.base.core.project.organization.Person;
import com.x.base.core.project.organization.Unit;
......@@ -19,6 +22,8 @@ import java.util.List;
*/
public class UserManagerService {
private static Logger logger = LoggerFactory.getLogger(UserManagerService.class);
public List<String> listIdentitiesWithPerson(String personName) throws Exception {
Business business = null;
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
......@@ -243,6 +248,7 @@ public class UserManagerService {
return parentUnit.getDistinguishedName();
}
} catch (NullPointerException e) {
logger.error(e);
}
}
}
......@@ -298,6 +304,7 @@ public class UserManagerService {
try {
parentUnit = business.organization().unit().getObject(parentUnitName);
} catch (NullPointerException e) {
logger.error(e);
}
}
if (parentUnit == null) {
......
......@@ -34,9 +34,9 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem;
* 中的内容,遇到特定事件才会触发,大大减少了内存的使用。
*
*/
public class Excel2003Reader implements HSSFListener{
public class Excel2003Reader implements HSSFListener {
private int minColumns = -1;
private POIFSFileSystem fs;
// private POIFSFileSystem fs;
private int lastRowNumber;
private int lastColumnNumber;
......@@ -45,14 +45,14 @@ public class Excel2003Reader implements HSSFListener{
/** For parsing Formulas */
private SheetRecordCollectingListener workbookBuildingListener;
//excel2003工作薄
// excel2003工作薄
private HSSFWorkbook stubWorkbook;
// Records we pick up as we process
private SSTRecord sstRecord;
private FormatTrackingHSSFListener formatListener;
//表索引
// 表索引
private int sheetIndex = -1;
private BoundSheetRecord[] orderedBSRs;
@SuppressWarnings("rawtypes")
......@@ -62,180 +62,178 @@ public class Excel2003Reader implements HSSFListener{
private int nextRow;
private int nextColumn;
private boolean outputNextStringRecord;
//当前行
// 当前行
private int curRow = 0;
//存储行记录的容器
// 存储行记录的容器
private List<String> rowlist = new ArrayList<String>();;
@SuppressWarnings( "unused" )
@SuppressWarnings("unused")
private String sheetName;
private String fileKey;
private int startRow;
private IRowReader rowReader;
public void setRowReader(IRowReader rowReader, String fileKey, int startRow ){
public void setRowReader(IRowReader rowReader, String fileKey, int startRow) {
this.rowReader = rowReader;
this.fileKey = fileKey;
this.startRow = startRow;
}
/**
* 遍历excel下所有的sheet
* @param fileKey
*
* @param fileKey
* @throws IOException
*/
public void process( String fileName ) throws IOException {
this.fs = new POIFSFileSystem( new FileInputStream(fileName) );
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener( this);
formatListener = new FormatTrackingHSSFListener(listener);
HSSFEventFactory factory = new HSSFEventFactory();
HSSFRequest request = new HSSFRequest();
if ( outputFormulaValues ) {
request.addListenerForAllRecords( formatListener );
} else {
workbookBuildingListener = new SheetRecordCollectingListener( formatListener);
request.addListenerForAllRecords(workbookBuildingListener);
public void process(String fileName) throws IOException {
try (POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(fileName))) {
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener(this);
formatListener = new FormatTrackingHSSFListener(listener);
HSSFEventFactory factory = new HSSFEventFactory();
HSSFRequest request = new HSSFRequest();
if (outputFormulaValues) {
request.addListenerForAllRecords(formatListener);
} else {
workbookBuildingListener = new SheetRecordCollectingListener(formatListener);
request.addListenerForAllRecords(workbookBuildingListener);
}
factory.processWorkbookEvents(request, fs);
// 数据读取完成
}
factory.processWorkbookEvents(request, fs);
//数据读取完成
}
/**
* 遍历excel下所有的sheet
* @param fileKey
*
* @param fileKey
* @throws IOException
*/
public void process( InputStream is ) throws IOException {
this.fs = new POIFSFileSystem( is );
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener( this);
formatListener = new FormatTrackingHSSFListener(listener);
HSSFEventFactory factory = new HSSFEventFactory();
HSSFRequest request = new HSSFRequest();
if ( outputFormulaValues ) {
request.addListenerForAllRecords( formatListener );
} else {
workbookBuildingListener = new SheetRecordCollectingListener( formatListener);
request.addListenerForAllRecords(workbookBuildingListener);
public void process(InputStream is) throws IOException {
try (POIFSFileSystem fs = new POIFSFileSystem(is)) {
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener(this);
formatListener = new FormatTrackingHSSFListener(listener);
HSSFEventFactory factory = new HSSFEventFactory();
HSSFRequest request = new HSSFRequest();
if (outputFormulaValues) {
request.addListenerForAllRecords(formatListener);
} else {
workbookBuildingListener = new SheetRecordCollectingListener(formatListener);
request.addListenerForAllRecords(workbookBuildingListener);
}
factory.processWorkbookEvents(request, fs);
// 数据读取完成
}
factory.processWorkbookEvents(request, fs);
//数据读取完成
}
/**
* HSSFListener 监听方法,处理 Record
*/
@SuppressWarnings( "unchecked" )
@SuppressWarnings("unchecked")
public void processRecord(Record record) {
int thisRow = -1;
int thisColumn = -1;
String thisStr = null;
String value = null;
switch (record.getSid()) {
case BoundSheetRecord.sid:
boundSheetRecords.add(record);
break;
case BOFRecord.sid:
BOFRecord br = (BOFRecord) record;
if (br.getType() == BOFRecord.TYPE_WORKSHEET) {
// 如果有需要,则建立子工作薄
if (workbookBuildingListener != null && stubWorkbook == null) {
stubWorkbook = workbookBuildingListener
.getStubHSSFWorkbook();
}
sheetIndex++;
if (orderedBSRs == null) {
orderedBSRs = BoundSheetRecord
.orderByBofPosition(boundSheetRecords);
}
sheetName = orderedBSRs[sheetIndex].getSheetname();
case BoundSheetRecord.sid:
boundSheetRecords.add(record);
break;
case BOFRecord.sid:
BOFRecord br = (BOFRecord) record;
if (br.getType() == BOFRecord.TYPE_WORKSHEET) {
// 如果有需要,则建立子工作薄
if (workbookBuildingListener != null && stubWorkbook == null) {
stubWorkbook = workbookBuildingListener.getStubHSSFWorkbook();
}
break;
case SSTRecord.sid:
sstRecord = (SSTRecord) record;
break;
case BlankRecord.sid:
BlankRecord brec = (BlankRecord) record;
thisRow = brec.getRow();
thisColumn = brec.getColumn();
thisStr = "";
rowlist.add(thisColumn, thisStr);
break;
case BoolErrRecord.sid: //单元格为布尔类型
BoolErrRecord berec = (BoolErrRecord) record;
thisRow = berec.getRow();
thisColumn = berec.getColumn();
thisStr = berec.getBooleanValue()+"";
rowlist.add(thisColumn, thisStr);
break;
case FormulaRecord.sid: //单元格为公式类型
FormulaRecord frec = (FormulaRecord) record;
thisRow = frec.getRow();
thisColumn = frec.getColumn();
if (outputFormulaValues) {
if (Double.isNaN(frec.getValue())) {
// Formula result is a string
// This is stored in the next record
outputNextStringRecord = true;
nextRow = frec.getRow();
nextColumn = frec.getColumn();
} else {
thisStr = formatListener.formatNumberDateCell(frec);
}
} else {
thisStr = '"' + HSSFFormulaParser.toFormulaString(stubWorkbook, frec.getParsedExpression()) + '"';
}
rowlist.add(thisColumn,thisStr);
break;
case StringRecord.sid://单元格中公式的字符串
if (outputNextStringRecord) {
// String for formula
StringRecord srec = (StringRecord) record;
thisStr = srec.getString();
thisRow = nextRow;
thisColumn = nextColumn;
outputNextStringRecord = false;
sheetIndex++;
if (orderedBSRs == null) {
orderedBSRs = BoundSheetRecord.orderByBofPosition(boundSheetRecords);
}
break;
case LabelRecord.sid:
LabelRecord lrec = (LabelRecord) record;
curRow = thisRow = lrec.getRow();
thisColumn = lrec.getColumn();
value = lrec.getValue().trim();
value = value.equals( "" )?" ":value;
this.rowlist.add(thisColumn, value);
break;
case LabelSSTRecord.sid: //单元格为字符串类型
LabelSSTRecord lsrec = (LabelSSTRecord) record;
curRow = thisRow = lsrec.getRow();
thisColumn = lsrec.getColumn();
if (sstRecord == null) {
rowlist.add(thisColumn, " " );
sheetName = orderedBSRs[sheetIndex].getSheetname();
}
break;
case SSTRecord.sid:
sstRecord = (SSTRecord) record;
break;
case BlankRecord.sid:
BlankRecord brec = (BlankRecord) record;
thisRow = brec.getRow();
thisColumn = brec.getColumn();
thisStr = "";
rowlist.add(thisColumn, thisStr);
break;
case BoolErrRecord.sid: // 单元格为布尔类型
BoolErrRecord berec = (BoolErrRecord) record;
thisRow = berec.getRow();
thisColumn = berec.getColumn();
thisStr = berec.getBooleanValue() + "";
rowlist.add(thisColumn, thisStr);
break;
case FormulaRecord.sid: // 单元格为公式类型
FormulaRecord frec = (FormulaRecord) record;
thisRow = frec.getRow();
thisColumn = frec.getColumn();
if (outputFormulaValues) {
if (Double.isNaN(frec.getValue())) {
// Formula result is a string
// This is stored in the next record
outputNextStringRecord = true;
nextRow = frec.getRow();
nextColumn = frec.getColumn();
} else {
value = sstRecord
.getString(lsrec.getSSTIndex()).toString().trim();
value = value.equals( "" )?" ":value;
rowlist.add(thisColumn,value);
thisStr = formatListener.formatNumberDateCell(frec);
}
break;
case NumberRecord.sid: //单元格为数字类型
NumberRecord numrec = (NumberRecord) record;
curRow = thisRow = numrec.getRow();
thisColumn = numrec.getColumn();
value = formatListener.formatNumberDateCell(numrec).trim();
value = value.equals( "" )?" ":value;
// 向容器加入列值
} else {
thisStr = '"' + HSSFFormulaParser.toFormulaString(stubWorkbook, frec.getParsedExpression()) + '"';
}
rowlist.add(thisColumn, thisStr);
break;
case StringRecord.sid:// 单元格中公式的字符串
if (outputNextStringRecord) {
// String for formula
StringRecord srec = (StringRecord) record;
thisStr = srec.getString();
thisRow = nextRow;
thisColumn = nextColumn;
outputNextStringRecord = false;
}
break;
case LabelRecord.sid:
LabelRecord lrec = (LabelRecord) record;
curRow = thisRow = lrec.getRow();
thisColumn = lrec.getColumn();
value = lrec.getValue().trim();
value = value.equals("") ? " " : value;
this.rowlist.add(thisColumn, value);
break;
case LabelSSTRecord.sid: // 单元格为字符串类型
LabelSSTRecord lsrec = (LabelSSTRecord) record;
curRow = thisRow = lsrec.getRow();
thisColumn = lsrec.getColumn();
if (sstRecord == null) {
rowlist.add(thisColumn, " ");
} else {
value = sstRecord.getString(lsrec.getSSTIndex()).toString().trim();
value = value.equals("") ? " " : value;
rowlist.add(thisColumn, value);
break;
default:
break;
}
break;
case NumberRecord.sid: // 单元格为数字类型
NumberRecord numrec = (NumberRecord) record;
curRow = thisRow = numrec.getRow();
thisColumn = numrec.getColumn();
value = formatListener.formatNumberDateCell(numrec).trim();
value = value.equals("") ? " " : value;
// 向容器加入列值
rowlist.add(thisColumn, value);
break;
default:
break;
}
// 遇到新行的操作
......@@ -248,7 +246,7 @@ public class Excel2003Reader implements HSSFListener{
MissingCellDummyRecord mc = (MissingCellDummyRecord) record;
curRow = thisRow = mc.getRow();
thisColumn = mc.getColumn();
rowlist.add(thisColumn," " );
rowlist.add(thisColumn, " ");
}
// 更新行和列的值
......@@ -267,12 +265,12 @@ public class Excel2003Reader implements HSSFListener{
}
lastColumnNumber = -1;
// 每行结束时, 调用getRows() 方法
rowReader.getRows(sheetIndex,curRow, rowlist, this.fileKey, this.startRow );
rowReader.getRows(sheetIndex, curRow, rowlist, this.fileKey, this.startRow);
// 清空容器
rowlist.clear();
}
}
}
......@@ -22,55 +22,56 @@ import org.xml.sax.helpers.XMLReaderFactory;
/**
* 抽象Excel2007读取器,excel2007的底层数据结构是xml文件,采用SAX的事件驱动的方法解析
* xml,需要继承DefaultHandler,在遇到文件内容时,事件会触发,这种做法可以大大降低
* 内存的耗费,特别使用于大数据量的文件。
* xml,需要继承DefaultHandler,在遇到文件内容时,事件会触发,这种做法可以大大降低 内存的耗费,特别使用于大数据量的文件。
*
*/
public class Excel2007Reader extends DefaultHandler {
//共享字符串表
// 共享字符串表
private SharedStringsTable sst;
//上一次的内容
// 上一次的内容
private String lastContents;
private boolean nextIsString;
private int sheetIndex = -1;
private List<String> rowlist = new ArrayList<String>();
//当前行
// 当前行
private int curRow = 0;
//当前列
// 当前列
private int curCol = 0;
//日期标志
// 日期标志
private boolean dateFlag;
//数字标志
// 数字标志
private boolean numberFlag;
private boolean isTElement;
private String fileKey;
private int startRow;
private IRowReader rowReader;
public void setRowReader(IRowReader rowReader, String fileKey, int startRow){
public void setRowReader(IRowReader rowReader, String fileKey, int startRow) {
this.rowReader = rowReader;
this.fileKey = fileKey;
this.startRow = startRow;
}
/**只遍历一个电子表格,其中sheetId为要遍历的sheet索引,从1开始,1-3
/**
* 只遍历一个电子表格,其中sheetId为要遍历的sheet索引,从1开始,1-3
*
* @param filename
* @param sheetId
* @throws Exception
*/
public void processOneSheet(String filename,int sheetId) throws Exception {
public void processOneSheet(String filename, int sheetId) throws Exception {
OPCPackage pkg = OPCPackage.open(filename);
XSSFReader r = new XSSFReader(pkg);
SharedStringsTable sst = r.getSharedStringsTable();
XMLReader parser = fetchSheetParser(sst);
// 根据 rId# 或 rSheet# 查找sheet
InputStream sheet2 = r.getSheet( "rId"+sheetId);
InputStream sheet2 = r.getSheet("rId" + sheetId);
sheetIndex++;
InputSource sheetSource = new InputSource(sheet2);
parser.parse(sheetSource);
......@@ -79,12 +80,13 @@ public class Excel2007Reader extends DefaultHandler {
/**
* 遍历工作簿中所有的电子表格
*
* @param filename
* @param fileKey
* @param fileKey
* @throws Exception
*/
public void process( String filename ) throws Exception {
OPCPackage pkg = OPCPackage.open( filename );
public void process(String filename) throws Exception {
OPCPackage pkg = OPCPackage.open(filename);
XSSFReader r = new XSSFReader(pkg);
SharedStringsTable sst = r.getSharedStringsTable();
XMLReader parser = fetchSheetParser(sst);
......@@ -94,19 +96,21 @@ public class Excel2007Reader extends DefaultHandler {
sheetIndex++;
InputStream sheet = sheets.next();
InputSource sheetSource = new InputSource(sheet);
parser.parse( sheetSource );
parser.parse(sheetSource);
sheet.close();
}
//数据读取完成
// 数据读取完成
}
/**
* 遍历工作簿中所有的电子表格
*
* @param is
* @param fileKey
* @param fileKey
* @throws Exception
*/
public void process( InputStream is ) throws Exception {
OPCPackage pkg = OPCPackage.open( is );
public void process(InputStream is) throws Exception {
OPCPackage pkg = OPCPackage.open(is);
XSSFReader r = new XSSFReader(pkg);
SharedStringsTable sst = r.getSharedStringsTable();
XMLReader parser = fetchSheetParser(sst);
......@@ -116,117 +120,115 @@ public class Excel2007Reader extends DefaultHandler {
sheetIndex++;
InputStream sheet = sheets.next();
InputSource sheetSource = new InputSource(sheet);
parser.parse( sheetSource );
parser.parse(sheetSource);
sheet.close();
}
//数据读取完成
// 数据读取完成
}
public XMLReader fetchSheetParser(SharedStringsTable sst) throws SAXException {
XMLReader parser = XMLReaderFactory.createXMLReader( "org.apache.xerces.parsers.SAXParser" );
XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
this.sst = sst;
parser.setContentHandler(this);
return parser;
}
public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
// c => 单元格
if ( "c".equals(name)) {
if ("c".equals(name)) {
// 如果下一个元素是 SST 的索引,则将nextIsString标记为true
String cellType = attributes.getValue( "t" );
if ( "s".equals(cellType)) {
String cellType = attributes.getValue("t");
if ("s".equals(cellType)) {
nextIsString = true;
} else {
nextIsString = false;
}
//日期格式
String cellDateType = attributes.getValue( "s" );
if ( "1".equals(cellDateType)){
// 日期格式
String cellDateType = attributes.getValue("s");
if ("1".equals(cellDateType)) {
dateFlag = true;
} else {
dateFlag = false;
}
String cellNumberType = attributes.getValue( "s" );
if( "2".equals(cellNumberType)){
String cellNumberType = attributes.getValue("s");
if ("2".equals(cellNumberType)) {
numberFlag = true;
} else {
numberFlag = false;
}
}
//当元素为t时
if( "t".equals(name)){
// 当元素为t时
if ("t".equals(name)) {
isTElement = true;
} else {
isTElement = false;
}
// 置空
lastContents = "";
}
public void endElement(String uri, String localName, String name)
throws SAXException {
public void endElement(String uri, String localName, String name) throws SAXException {
// 根据SST的索引值的到单元格的真正要存储的字符串
// 这时characters()方法可能会被调用多次
if (nextIsString) {
try {
int idx = Integer.parseInt(lastContents);
lastContents = new XSSFRichTextString(sst.getEntryAt(idx))
.toString();
lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
} catch (Exception e) {
e.printStackTrace();
}
}
//t元素也包含字符串
if(isTElement){
}
// t元素也包含字符串
if (isTElement) {
String value = lastContents.trim();
rowlist.add(curCol, value);
curCol++;
isTElement = false;
// v => 单元格的值,如果单元格是字符串则v标签的值为该字符串在SST中的索引
// 将单元格内容加入rowlist中,在这之前先去掉字符串前后的空白符
} else if ( "v".equals(name)) {
} else if ("v".equals(name)) {
String value = lastContents.trim();
value = value.equals( "" )?" ":value;
//日期格式处理
if(dateFlag){
try{
value = value.equals("") ? " " : value;
// 日期格式处理
if (dateFlag) {
try {
Date date = HSSFDateUtil.getJavaDate(Double.valueOf(value));
SimpleDateFormat dateFormat = new SimpleDateFormat( "dd/MM/yyyy" );
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
value = dateFormat.format(date);
}catch(Exception e){
} catch (Exception e) {
e.printStackTrace();
}
}
//数字类型处理
if(numberFlag){
try{
}
// 数字类型处理
if (numberFlag) {
try {
BigDecimal bd = new BigDecimal(value);
value = bd.setScale(3,BigDecimal.ROUND_UP).toString();
}catch(Exception e){
value = bd.setScale(3, BigDecimal.ROUND_UP).toString();
} catch (Exception e) {
e.printStackTrace();
}
}
rowlist.add(curCol, value);
curCol++;
}else {
//如果标签名称为 row ,这说明已到行尾,调用 optRows() 方法
if (name.equals( "row" )) {
rowReader.getRows(sheetIndex,curRow,rowlist, this.fileKey, this.startRow );
} else {
// 如果标签名称为 row ,这说明已到行尾,调用 optRows() 方法
if (name.equals("row")) {
rowReader.getRows(sheetIndex, curRow, rowlist, this.fileKey, this.startRow);
rowlist.clear();
curRow++;
curCol = 0;
}
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
//得到单元格内容的值
public void characters(char[] ch, int start, int length) throws SAXException {
// 得到单元格内容的值
lastContents += new String(ch, start, length);
}
}
......@@ -42,24 +42,22 @@ public abstract class AbstractExcel2007Writer {
String sheetRef = sheet.getPackagePart().getPartName().getName();
// 保存模板
FileOutputStream os = new FileOutputStream("template.xlsx");
wb.write(os);
os.close();
try (FileOutputStream os = new FileOutputStream("template.xlsx")) {
wb.write(os);
}
// 生成xml文件
File tmp = File.createTempFile("sheet", ".xml");
Writer fw = new FileWriter(tmp);
sw = new SpreadsheetWriter(fw);
generate();
fw.close();
try (Writer fw = new FileWriter(tmp)) {
sw = new SpreadsheetWriter(fw);
generate();
}
// 使用产生的数据替换模板
File templateFile = new File("template.xlsx");
FileOutputStream out = new FileOutputStream(fileName);
substitute(templateFile, tmp, sheetRef.substring(1), out);
out.close();
// 删除文件之前调用一下垃圾回收器,否则无法删除模板文件
System.gc();
try (FileOutputStream out = new FileOutputStream(fileName)){
substitute(templateFile, tmp, sheetRef.substring(1), out);
}
// 删除临时模板文件
if (templateFile.isFile() && templateFile.exists()) {
templateFile.delete();
......
......@@ -20,7 +20,7 @@ public class Excel2003Writer {
writeExcel( "tes2003.xls" );
//System.out.println( "写完xcel2003" );
} catch (IOException e) {
e.printStackTrace();
}
}
......
package com.x.cms.assemble.control.jaxrs.script;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import com.google.gson.JsonElement;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
......@@ -11,54 +16,57 @@ import com.x.base.core.project.exception.ExceptionAccessDenied;
import com.x.base.core.project.gson.GsonPropertyObject;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.ListTools;
import com.x.base.core.project.tools.StringTools;
import com.x.cms.core.entity.AppInfo;
import com.x.cms.core.entity.element.Script;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
class ActionManagerList extends BaseAction {
private static Logger logger = LoggerFactory.getLogger(ActionManagerList.class);
ActionResult<List<Wo>> execute(EffectivePerson effectivePerson, JsonElement jsonElement) throws Exception {
if(!effectivePerson.isManager()){
if (!effectivePerson.isManager()) {
throw new ExceptionAccessDenied(effectivePerson);
}
Wi wi = this.convertToWrapIn(jsonElement, Wi.class);
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<List<Wo>> result = new ActionResult<>();
List<Wo> wos;
if(ListTools.isEmpty(wi.getAppIdList())){
wos = emc.fetchAll(Script.class, Wo.copier);
}else{
if (ListTools.isEmpty(wi.getAppIdList())) {
wos = emc.fetchAll(Script.class, Wo.copier);
} else {
wos = emc.fetchIn(Script.class, Wo.copier, Script.appId_FIELDNAME, wi.getAppIdList());
}
final List<Wo> resWos = new ArrayList<>();
wos.stream().forEach(wo -> {
try {
AppInfo appInfo = emc.find( wo.getAppId(), AppInfo.class );
if(appInfo != null){
AppInfo appInfo = emc.find(wo.getAppId(), AppInfo.class);
if (appInfo != null) {
wo.setAppName(appInfo.getAppName());
}
} catch (Exception e) {
logger.error(e);
}
if(StringUtils.isNotBlank(wi.getKeyword())){
if(StringTools.matchKeyword(wi.getKeyword(), wo.getText(), wi.getCaseSensitive(), wi.getMatchWholeWord(), wi.getMatchRegExp())){
if (StringUtils.isNotBlank(wi.getKeyword())) {
if (StringTools.matchKeyword(wi.getKeyword(), wo.getText(), wi.getCaseSensitive(),
wi.getMatchWholeWord(), wi.getMatchRegExp())) {
resWos.add(wo);
}
}else{
} else {
resWos.add(wo);
}
});
wos.clear();
result.setData(resWos);
result.setCount((long)resWos.size());
result.setCount((long) resWos.size());
return result;
}
}
public static class Wi extends GsonPropertyObject{
public static class Wi extends GsonPropertyObject {
@FieldDescribe("搜索关键字.")
private String keyword;
@FieldDescribe("是否区分大小写.")
......@@ -116,7 +124,7 @@ class ActionManagerList extends BaseAction {
private static final long serialVersionUID = -8095369685452823624L;
static WrapCopier<Script, Wo> copier = WrapCopierFactory.wo(Script.class, Wo.class,
JpaObject.singularAttributeField(Script.class, true, false),null);
JpaObject.singularAttributeField(Script.class, true, false), null);
@FieldDescribe("应用名称.")
private String appName;
......
......@@ -34,9 +34,9 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem;
* 中的内容,遇到特定事件才会触发,大大减少了内存的使用。
*
*/
public class Excel2003Reader implements HSSFListener{
public class Excel2003Reader implements HSSFListener {
private int minColumns = -1;
private POIFSFileSystem fs;
// private POIFSFileSystem fs;
private int lastRowNumber;
private int lastColumnNumber;
......@@ -45,14 +45,14 @@ public class Excel2003Reader implements HSSFListener{
/** For parsing Formulas */
private SheetRecordCollectingListener workbookBuildingListener;
//excel2003工作薄
// excel2003工作薄
private HSSFWorkbook stubWorkbook;
// Records we pick up as we process
private SSTRecord sstRecord;
private FormatTrackingHSSFListener formatListener;
//表索引
// 表索引
private int sheetIndex = -1;
private BoundSheetRecord[] orderedBSRs;
@SuppressWarnings("rawtypes")
......@@ -62,176 +62,175 @@ public class Excel2003Reader implements HSSFListener{
private int nextRow;
private int nextColumn;
private boolean outputNextStringRecord;
//当前行
// 当前行
private int curRow = 0;
//存储行记录的容器
// 存储行记录的容器
private List<String> rowlist = new ArrayList<String>();;
@SuppressWarnings( "unused" )
@SuppressWarnings("unused")
private String sheetName;
private IRowReader rowReader;
private ExcelReadRuntime excelReadRuntime;
public void setRowReader(IRowReader rowReader, ExcelReadRuntime excelReadRuntime ){
public void setRowReader(IRowReader rowReader, ExcelReadRuntime excelReadRuntime) {
this.rowReader = rowReader;
this.excelReadRuntime = excelReadRuntime;
}
/**
* 遍历excel下所有的sheet
* @param fileKey
*
* @param fileKey
* @throws IOException
*/
public void process( String fileName ) throws IOException {
this.fs = new POIFSFileSystem( new FileInputStream(fileName) );
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener( this);
formatListener = new FormatTrackingHSSFListener(listener);
HSSFEventFactory factory = new HSSFEventFactory();
HSSFRequest request = new HSSFRequest();
if ( outputFormulaValues ) {
request.addListenerForAllRecords( formatListener );
} else {
workbookBuildingListener = new SheetRecordCollectingListener( formatListener);
request.addListenerForAllRecords(workbookBuildingListener);
public void process(String fileName) throws IOException {
try (POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(fileName))) {
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener(this);
formatListener = new FormatTrackingHSSFListener(listener);
HSSFEventFactory factory = new HSSFEventFactory();
HSSFRequest request = new HSSFRequest();
if (outputFormulaValues) {
request.addListenerForAllRecords(formatListener);
} else {
workbookBuildingListener = new SheetRecordCollectingListener(formatListener);
request.addListenerForAllRecords(workbookBuildingListener);
}
factory.processWorkbookEvents(request, fs);
// 数据读取完成
}
factory.processWorkbookEvents(request, fs);
//数据读取完成
}
/**
* 遍历excel下所有的sheet
* @param fileKey
*
* @param fileKey
* @throws IOException
*/
public void process( InputStream is ) throws IOException {
this.fs = new POIFSFileSystem( is );
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener( this);
formatListener = new FormatTrackingHSSFListener(listener);
HSSFEventFactory factory = new HSSFEventFactory();
HSSFRequest request = new HSSFRequest();
if ( outputFormulaValues ) {
request.addListenerForAllRecords( formatListener );
} else {
workbookBuildingListener = new SheetRecordCollectingListener( formatListener);
request.addListenerForAllRecords(workbookBuildingListener);
public void process(InputStream is) throws IOException {
try (POIFSFileSystem fs = new POIFSFileSystem(is)) {
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener(this);
formatListener = new FormatTrackingHSSFListener(listener);
HSSFEventFactory factory = new HSSFEventFactory();
HSSFRequest request = new HSSFRequest();
if (outputFormulaValues) {
request.addListenerForAllRecords(formatListener);
} else {
workbookBuildingListener = new SheetRecordCollectingListener(formatListener);
request.addListenerForAllRecords(workbookBuildingListener);
}
factory.processWorkbookEvents(request, fs);
// 数据读取完成
}
factory.processWorkbookEvents(request, fs);
//数据读取完成
}
/**
* HSSFListener 监听方法,处理 Record
*/
@SuppressWarnings( "unchecked" )
@SuppressWarnings("unchecked")
public void processRecord(Record record) {
int thisRow = -1;
int thisColumn = -1;
String thisStr = null;
String value = null;
switch (record.getSid()) {
case BoundSheetRecord.sid:
boundSheetRecords.add(record);
break;
case BOFRecord.sid:
BOFRecord br = (BOFRecord) record;
if (br.getType() == BOFRecord.TYPE_WORKSHEET) {
// 如果有需要,则建立子工作薄
if (workbookBuildingListener != null && stubWorkbook == null) {
stubWorkbook = workbookBuildingListener
.getStubHSSFWorkbook();
}
sheetIndex++;
if (orderedBSRs == null) {
orderedBSRs = BoundSheetRecord
.orderByBofPosition(boundSheetRecords);
}
sheetName = orderedBSRs[sheetIndex].getSheetname();
}
break;
case SSTRecord.sid:
sstRecord = (SSTRecord) record;
break;
case BlankRecord.sid:
BlankRecord brec = (BlankRecord) record;
thisRow = brec.getRow();
thisColumn = brec.getColumn();
thisStr = "";
rowlist.add(thisColumn, thisStr);
break;
case BoolErrRecord.sid: //单元格为布尔类型
BoolErrRecord berec = (BoolErrRecord) record;
thisRow = berec.getRow();
thisColumn = berec.getColumn();
thisStr = berec.getBooleanValue()+"";
rowlist.add(thisColumn, thisStr);
break;
case FormulaRecord.sid: //单元格为公式类型
FormulaRecord frec = (FormulaRecord) record;
thisRow = frec.getRow();
thisColumn = frec.getColumn();
if (outputFormulaValues) {
if (Double.isNaN(frec.getValue())) {
// Formula result is a string
// This is stored in the next record
outputNextStringRecord = true;
nextRow = frec.getRow();
nextColumn = frec.getColumn();
} else {
thisStr = formatListener.formatNumberDateCell(frec);
}
} else {
thisStr = '"' + HSSFFormulaParser.toFormulaString(stubWorkbook, frec.getParsedExpression()) + '"';
case BoundSheetRecord.sid:
boundSheetRecords.add(record);
break;
case BOFRecord.sid:
BOFRecord br = (BOFRecord) record;
if (br.getType() == BOFRecord.TYPE_WORKSHEET) {
// 如果有需要,则建立子工作薄
if (workbookBuildingListener != null && stubWorkbook == null) {
stubWorkbook = workbookBuildingListener.getStubHSSFWorkbook();
}
rowlist.add(thisColumn,thisStr);
break;
case StringRecord.sid://单元格中公式的字符串
if (outputNextStringRecord) {
// String for formula
StringRecord srec = (StringRecord) record;
thisStr = srec.getString();
thisRow = nextRow;
thisColumn = nextColumn;
outputNextStringRecord = false;
sheetIndex++;
if (orderedBSRs == null) {
orderedBSRs = BoundSheetRecord.orderByBofPosition(boundSheetRecords);
}
break;
case LabelRecord.sid:
LabelRecord lrec = (LabelRecord) record;
curRow = thisRow = lrec.getRow();
thisColumn = lrec.getColumn();
value = lrec.getValue().trim();
value = value.equals( "" )?" ":value;
this.rowlist.add(thisColumn, value);
break;
case LabelSSTRecord.sid: //单元格为字符串类型
LabelSSTRecord lsrec = (LabelSSTRecord) record;
curRow = thisRow = lsrec.getRow();
thisColumn = lsrec.getColumn();
if (sstRecord == null) {
rowlist.add(thisColumn, " " );
sheetName = orderedBSRs[sheetIndex].getSheetname();
}
break;
case SSTRecord.sid:
sstRecord = (SSTRecord) record;
break;
case BlankRecord.sid:
BlankRecord brec = (BlankRecord) record;
thisRow = brec.getRow();
thisColumn = brec.getColumn();
thisStr = "";
rowlist.add(thisColumn, thisStr);
break;
case BoolErrRecord.sid: // 单元格为布尔类型
BoolErrRecord berec = (BoolErrRecord) record;
thisRow = berec.getRow();
thisColumn = berec.getColumn();
thisStr = berec.getBooleanValue() + "";
rowlist.add(thisColumn, thisStr);
break;
case FormulaRecord.sid: // 单元格为公式类型
FormulaRecord frec = (FormulaRecord) record;
thisRow = frec.getRow();
thisColumn = frec.getColumn();
if (outputFormulaValues) {
if (Double.isNaN(frec.getValue())) {
// Formula result is a string
// This is stored in the next record
outputNextStringRecord = true;
nextRow = frec.getRow();
nextColumn = frec.getColumn();
} else {
value = sstRecord
.getString(lsrec.getSSTIndex()).toString().trim();
value = value.equals( "" )?" ":value;
rowlist.add(thisColumn,value);
thisStr = formatListener.formatNumberDateCell(frec);
}
break;
case NumberRecord.sid: //单元格为数字类型
NumberRecord numrec = (NumberRecord) record;
curRow = thisRow = numrec.getRow();
thisColumn = numrec.getColumn();
value = formatListener.formatNumberDateCell(numrec).trim();
value = value.equals( "" )?" ":value;
// 向容器加入列值
} else {
thisStr = '"' + HSSFFormulaParser.toFormulaString(stubWorkbook, frec.getParsedExpression()) + '"';
}
rowlist.add(thisColumn, thisStr);
break;
case StringRecord.sid:// 单元格中公式的字符串
if (outputNextStringRecord) {
// String for formula
StringRecord srec = (StringRecord) record;
thisStr = srec.getString();
thisRow = nextRow;
thisColumn = nextColumn;
outputNextStringRecord = false;
}
break;
case LabelRecord.sid:
LabelRecord lrec = (LabelRecord) record;
curRow = thisRow = lrec.getRow();
thisColumn = lrec.getColumn();
value = lrec.getValue().trim();
value = value.equals("") ? " " : value;
this.rowlist.add(thisColumn, value);
break;
case LabelSSTRecord.sid: // 单元格为字符串类型
LabelSSTRecord lsrec = (LabelSSTRecord) record;
curRow = thisRow = lsrec.getRow();
thisColumn = lsrec.getColumn();
if (sstRecord == null) {
rowlist.add(thisColumn, " ");
} else {
value = sstRecord.getString(lsrec.getSSTIndex()).toString().trim();
value = value.equals("") ? " " : value;
rowlist.add(thisColumn, value);
break;
default:
break;
}
break;
case NumberRecord.sid: // 单元格为数字类型
NumberRecord numrec = (NumberRecord) record;
curRow = thisRow = numrec.getRow();
thisColumn = numrec.getColumn();
value = formatListener.formatNumberDateCell(numrec).trim();
value = value.equals("") ? " " : value;
// 向容器加入列值
rowlist.add(thisColumn, value);
break;
default:
break;
}
// 遇到新行的操作
......@@ -244,7 +243,7 @@ public class Excel2003Reader implements HSSFListener{
MissingCellDummyRecord mc = (MissingCellDummyRecord) record;
curRow = thisRow = mc.getRow();
thisColumn = mc.getColumn();
rowlist.add(thisColumn," " );
rowlist.add(thisColumn, " ");
}
// 更新行和列的值
......@@ -263,10 +262,10 @@ public class Excel2003Reader implements HSSFListener{
}
lastColumnNumber = -1;
// 每行结束时, 调用getRows() 方法
rowReader.getRows(sheetIndex,curRow, rowlist, excelReadRuntime );
rowReader.getRows(sheetIndex, curRow, rowlist, excelReadRuntime);
// 清空容器
rowlist.clear();
}
}
}
......@@ -22,48 +22,49 @@ import org.xml.sax.helpers.XMLReaderFactory;
/**
* 抽象Excel2007读取器,excel2007的底层数据结构是xml文件,采用SAX的事件驱动的方法解析
* xml,需要继承DefaultHandler,在遇到文件内容时,事件会触发,这种做法可以大大降低
* 内存的耗费,特别使用于大数据量的文件。
* xml,需要继承DefaultHandler,在遇到文件内容时,事件会触发,这种做法可以大大降低 内存的耗费,特别使用于大数据量的文件。
*
*/
public class Excel2007Reader extends DefaultHandler {
//共享字符串表
// 共享字符串表
private SharedStringsTable sst;
//上一次的内容
// 上一次的内容
private String lastContents;
private boolean nextIsString;
private int sheetIndex = -1;
//当前行
// 当前行
private int curRow = 0;
//当前列
// 当前列
private int curCol = 0;
//日期标志
// 日期标志
private boolean dateFlag;
//数字标志
// 数字标志
private boolean numberFlag;
private boolean isTElement;
private ExcelReadRuntime excelReadRuntime;
private IRowReader rowReader;
private List<String> rowlist = new ArrayList<String>();
public void setRowReader(IRowReader rowReader, ExcelReadRuntime excelReadRuntime ){
public void setRowReader(IRowReader rowReader, ExcelReadRuntime excelReadRuntime) {
this.rowReader = rowReader;
this.excelReadRuntime = excelReadRuntime;
}
/**只遍历一个电子表格,其中sheetId为要遍历的sheet索引,从1开始,1-3
/**
* 只遍历一个电子表格,其中sheetId为要遍历的sheet索引,从1开始,1-3
*
* @param filename
* @param sheetId
* @throws Exception
*/
public void processOneSheet(String filename,int sheetId) throws Exception {
public void processOneSheet(String filename, int sheetId) throws Exception {
OPCPackage pkg = OPCPackage.open(filename);
XSSFReader r = new XSSFReader(pkg);
SharedStringsTable sst = r.getSharedStringsTable();
XMLReader parser = fetchSheetParser(sst);
// 根据 rId# 或 rSheet# 查找sheet
InputStream sheet2 = r.getSheet( "rId"+sheetId);
InputStream sheet2 = r.getSheet("rId" + sheetId);
sheetIndex++;
InputSource sheetSource = new InputSource(sheet2);
parser.parse(sheetSource);
......@@ -72,12 +73,13 @@ public class Excel2007Reader extends DefaultHandler {
/**
* 遍历工作簿中所有的电子表格
*
* @param filename
* @param fileKey
* @param fileKey
* @throws Exception
*/
public void process( String filename ) throws Exception {
OPCPackage pkg = OPCPackage.open( filename );
public void process(String filename) throws Exception {
OPCPackage pkg = OPCPackage.open(filename);
XSSFReader r = new XSSFReader(pkg);
SharedStringsTable sst = r.getSharedStringsTable();
XMLReader parser = fetchSheetParser(sst);
......@@ -87,19 +89,21 @@ public class Excel2007Reader extends DefaultHandler {
sheetIndex++;
InputStream sheet = sheets.next();
InputSource sheetSource = new InputSource(sheet);
parser.parse( sheetSource );
parser.parse(sheetSource);
sheet.close();
}
//数据读取完成
// 数据读取完成
}
/**
* 遍历工作簿中所有的电子表格
*
* @param is
* @param fileKey
* @param fileKey
* @throws Exception
*/
public void process( InputStream is ) throws Exception {
OPCPackage pkg = OPCPackage.open( is );
public void process(InputStream is) throws Exception {
OPCPackage pkg = OPCPackage.open(is);
XSSFReader r = new XSSFReader(pkg);
SharedStringsTable sst = r.getSharedStringsTable();
XMLReader parser = fetchSheetParser(sst);
......@@ -109,118 +113,116 @@ public class Excel2007Reader extends DefaultHandler {
sheetIndex++;
InputStream sheet = sheets.next();
InputSource sheetSource = new InputSource(sheet);
parser.parse( sheetSource );
parser.parse(sheetSource);
sheet.close();
}
//数据读取完成
// 数据读取完成
}
public XMLReader fetchSheetParser(SharedStringsTable sst) throws SAXException {
XMLReader parser = XMLReaderFactory.createXMLReader( "org.apache.xerces.parsers.SAXParser" );
XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
this.sst = sst;
parser.setContentHandler(this);
return parser;
}
public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
// c => 单元格
if ( "c".equals(name)) {
if ("c".equals(name)) {
// 如果下一个元素是 SST 的索引,则将nextIsString标记为true
String cellType = attributes.getValue( "t" );
if ( "s".equals(cellType)) {
String cellType = attributes.getValue("t");
if ("s".equals(cellType)) {
nextIsString = true;
} else {
nextIsString = false;
}
//日期格式
String cellDateType = attributes.getValue( "s" );
if ( "1".equals(cellDateType)){
// 日期格式
String cellDateType = attributes.getValue("s");
if ("1".equals(cellDateType)) {
dateFlag = true;
} else {
dateFlag = false;
}
String cellNumberType = attributes.getValue( "s" );
if( "2".equals(cellNumberType)){
String cellNumberType = attributes.getValue("s");
if ("2".equals(cellNumberType)) {
numberFlag = true;
} else {
numberFlag = false;
}
}
//当元素为t时
if( "t".equals(name)){
// 当元素为t时
if ("t".equals(name)) {
isTElement = true;
} else {
isTElement = false;
}
// 置空
lastContents = "";
}
@SuppressWarnings("deprecation")
public void endElement(String uri, String localName, String name)
throws SAXException {
public void endElement(String uri, String localName, String name) throws SAXException {
// 根据SST的索引值的到单元格的真正要存储的字符串
// 这时characters()方法可能会被调用多次
if (nextIsString) {
try {
int idx = Integer.parseInt(lastContents);
lastContents = new XSSFRichTextString(sst.getEntryAt(idx))
.toString();
lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
} catch (Exception e) {
e.printStackTrace();
}
}
//t元素也包含字符串
if(isTElement){
}
// t元素也包含字符串
if (isTElement) {
String value = lastContents.trim();
rowlist.add(curCol, value);
curCol++;
isTElement = false;
// v => 单元格的值,如果单元格是字符串则v标签的值为该字符串在SST中的索引
// 将单元格内容加入rowlist中,在这之前先去掉字符串前后的空白符
} else if ( "v".equals(name)) {
} else if ("v".equals(name)) {
String value = lastContents.trim();
value = value.equals( "" )?" ":value;
//日期格式处理
if(dateFlag){
try{
value = value.equals("") ? " " : value;
// 日期格式处理
if (dateFlag) {
try {
Date date = HSSFDateUtil.getJavaDate(Double.valueOf(value));
SimpleDateFormat dateFormat = new SimpleDateFormat( "dd/MM/yyyy" );
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
value = dateFormat.format(date);
}catch(Exception e){
} catch (Exception e) {
e.printStackTrace();
}
}
//数字类型处理
if(numberFlag){
try{
}
// 数字类型处理
if (numberFlag) {
try {
BigDecimal bd = new BigDecimal(value);
value = bd.setScale(3,BigDecimal.ROUND_UP).toString();
}catch(Exception e){
value = bd.setScale(3, BigDecimal.ROUND_UP).toString();
} catch (Exception e) {
e.printStackTrace();
}
}
rowlist.add(curCol, value);
curCol++;
}else {
//如果标签名称为 row ,这说明已到行尾,调用 optRows() 方法
if (name.equals( "row" )) {
rowReader.getRows(sheetIndex,curRow,rowlist, this.excelReadRuntime );
} else {
// 如果标签名称为 row ,这说明已到行尾,调用 optRows() 方法
if (name.equals("row")) {
rowReader.getRows(sheetIndex, curRow, rowlist, this.excelReadRuntime);
rowlist.clear();
curRow++;
curCol = 0;
}
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
//得到单元格内容的值
public void characters(char[] ch, int start, int length) throws SAXException {
// 得到单元格内容的值
lastContents += new String(ch, start, length);
}
}
......@@ -10,219 +10,226 @@ import java.util.HashMap;
*/
public class FileUtil {
// 缓存文件头信息-文件头信息
public static final HashMap<String, String> mFileTypes = new HashMap<String, String>();
static {
// images
mFileTypes.put("FFD8FF", "jpg");
mFileTypes.put("89504E47", "png");
mFileTypes.put("47494638", "gif");
mFileTypes.put("49492A00", "tif");
mFileTypes.put("424D", "bmp");
//
mFileTypes.put("41433130", "dwg"); // CAD
mFileTypes.put("38425053", "psd");
mFileTypes.put("7B5C727466", "rtf"); // 日记本
mFileTypes.put("3C3F786D6C", "xml");
mFileTypes.put("68746D6C3E", "html");
mFileTypes.put("44656C69766572792D646174653A", "eml"); // 邮件
mFileTypes.put("D0CF11E0", "doc");
mFileTypes.put("D0CF11E0", "xls");//excel2003版本文件
mFileTypes.put("5374616E64617264204A", "mdb");
mFileTypes.put("252150532D41646F6265", "ps");
mFileTypes.put("255044462D312E", "pdf");
mFileTypes.put("504B0304", "docx");
mFileTypes.put("504B0304", "xlsx");//excel2007以上版本文件
mFileTypes.put("52617221", "rar");
mFileTypes.put("57415645", "wav");
mFileTypes.put("41564920", "avi");
mFileTypes.put("2E524D46", "rm");
mFileTypes.put("000001BA", "mpg");
mFileTypes.put("000001B3", "mpg");
mFileTypes.put("6D6F6F76", "mov");
mFileTypes.put("3026B2758E66CF11", "asf");
mFileTypes.put("4D546864", "mid");
mFileTypes.put("1F8B08", "gz");
}
// 缓存文件头信息-文件头信息
public static final HashMap<String, String> mFileTypes = new HashMap<String, String>();
static {
// images
mFileTypes.put("FFD8FF", "jpg");
mFileTypes.put("89504E47", "png");
mFileTypes.put("47494638", "gif");
mFileTypes.put("49492A00", "tif");
mFileTypes.put("424D", "bmp");
//
mFileTypes.put("41433130", "dwg"); // CAD
mFileTypes.put("38425053", "psd");
mFileTypes.put("7B5C727466", "rtf"); // 日记本
mFileTypes.put("3C3F786D6C", "xml");
mFileTypes.put("68746D6C3E", "html");
mFileTypes.put("44656C69766572792D646174653A", "eml"); // 邮件
mFileTypes.put("D0CF11E0", "doc");
mFileTypes.put("D0CF11E0", "xls");// excel2003版本文件
mFileTypes.put("5374616E64617264204A", "mdb");
mFileTypes.put("252150532D41646F6265", "ps");
mFileTypes.put("255044462D312E", "pdf");
mFileTypes.put("504B0304", "docx");
mFileTypes.put("504B0304", "xlsx");// excel2007以上版本文件
mFileTypes.put("52617221", "rar");
mFileTypes.put("57415645", "wav");
mFileTypes.put("41564920", "avi");
mFileTypes.put("2E524D46", "rm");
mFileTypes.put("000001BA", "mpg");
mFileTypes.put("000001B3", "mpg");
mFileTypes.put("6D6F6F76", "mov");
mFileTypes.put("3026B2758E66CF11", "asf");
mFileTypes.put("4D546864", "mid");
mFileTypes.put("1F8B08", "gz");
}
/**
* <p>Title:getFileType </p>
* <p>Description: 根据文件路径获取文件头信息</p>
* @param filePath 文件路径
* @return 文件头信息
*/
public static String getFileType(String filePath) {
System.out.println(getFileHeader(filePath)); //返回十六进制 如:504B0304
//System.out.println(mFileTypes.get(getFileHeader(filePath))); //xlsx
return mFileTypes.get(getFileHeader(filePath));
}
/**
* <p>Title:getFileTypeByFileInputStream </p>
* <p>Description: 根据文件流获取文件头信息</p>
* @param is 文件流
* @return 文件头信息
*/
public static String getFileTypeByFileInputStream(FileInputStream is) {
return mFileTypes.get(getFileHeaderByFileInputStream(is));
}
/**
* <p>
* Title:getFileType
* </p>
* <p>
* Description: 根据文件路径获取文件头信息
* </p>
*
* @param filePath 文件路径
* @return 文件头信息
*/
public static String getFileType(String filePath) {
System.out.println(getFileHeader(filePath)); // 返回十六进制 如:504B0304
// System.out.println(mFileTypes.get(getFileHeader(filePath))); //xlsx
return mFileTypes.get(getFileHeader(filePath));
}
/**
* <p>Title:getFileHeader </p>
* <p>Description: 根据文件路径获取文件头信息 </p>
* @param filePath 文件路径
* @return 十六进制文件头信息
*/
public static String getFileHeader(String filePath) {
FileInputStream is = null;
String value = null;
try {
is = new FileInputStream(filePath);
byte[] b = new byte[7];
/*
* int read() 从此输入流中读取一个数据字节。int read(byte[] b) 从此输入流中将最多 b.length
* 个字节的数据读入一个 byte 数组中。 int read(byte[] b, int off, int len)
* 从此输入流中将最多 len 个字节的数据读入一个 byte 数组中。
*/
is.read(b, 0, b.length);
value = bytesToHexString(b);
} catch (Exception e) {
} finally {
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return value;
}
/**
* <p>Title:getFileHeaderByFileInputStream </p>
* <p>Description: 根据文件流获取文件头信息</p>
* @param is 文件流
* @return 十六进制文件头信息
*/
public static String getFileHeaderByFileInputStream(FileInputStream is) {
String value = null;
try {
byte[] b = new byte[7];
/*
* int read() 从此输入流中读取一个数据字节。int read(byte[] b) 从此输入流中将最多 b.length
* 个字节的数据读入一个 byte 数组中。 int read(byte[] b, int off, int len)
* 从此输入流中将最多 len 个字节的数据读入一个 byte 数组中。
*/
is.read(b, 0, b.length);
value = bytesToHexString(b);
} catch (Exception e) {
} finally {
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println(value);
return value;
}
/**
* <p>
* Title:getFileTypeByFileInputStream
* </p>
* <p>
* Description: 根据文件流获取文件头信息
* </p>
*
* @param is 文件流
* @return 文件头信息
*/
public static String getFileTypeByFileInputStream(FileInputStream is) {
return mFileTypes.get(getFileHeaderByFileInputStream(is));
}
/**
* <p>Title:bytesToHexString </p>
* <p>Description: 将要读取文件头信息的文件的byte数组转换成string类型表示 </p>
* @param src 要读取文件头信息的文件的byte数组
* @return 文件头信息
*/
private static String bytesToHexString(byte[] src) {
StringBuilder builder = new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
String hv;
for (int i = 0; i < src.length; i++) {
// 以十六进制(基数 16)无符号整数形式返回一个整数参数的字符串表示形式,并转换为大写
hv = Integer.toHexString(src[i] & 0xFF).toUpperCase();
if (hv.length() < 2) {
builder.append(0);
}
builder.append(hv);
}
//System.out.println(builder.toString());
return builder.toString();
}
/**
* <p>
* Title:getFileHeader
* </p>
* <p>
* Description: 根据文件路径获取文件头信息
* </p>
*
* @param filePath 文件路径
* @return 十六进制文件头信息
*/
public static String getFileHeader(String filePath) {
FileInputStream is = null;
String value = null;
try {
is = new FileInputStream(filePath);
byte[] b = new byte[7];
/*
* int read() 从此输入流中读取一个数据字节。int read(byte[] b) 从此输入流中将最多 b.length 个字节的数据读入一个
* byte 数组中。 int read(byte[] b, int off, int len) 从此输入流中将最多 len 个字节的数据读入一个 byte
* 数组中。
*/
is.read(b, 0, b.length);
value = bytesToHexString(b);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return value;
}
/**
* <p>Title:main </p>
* <p>Description: 测试</p>
* @param args
* @throws Exception
* @author 鲁东顺
* @date 2016-11-23上午10:11:37
*/
public static void main(String[] args) throws Exception {
/*//测试1...根据文件全路径
final String fileType = getFileType("E:\\服务申请模板.xlsx");
System.out.println(fileType); */
/**
* <p>
* Title:getFileHeaderByFileInputStream
* </p>
* <p>
* Description: 根据文件流获取文件头信息
* </p>
*
* @param is 文件流
* @return 十六进制文件头信息
*/
public static String getFileHeaderByFileInputStream(FileInputStream is) {
String value = null;
try {
byte[] b = new byte[7];
/*
* int read() 从此输入流中读取一个数据字节。int read(byte[] b) 从此输入流中将最多 b.length 个字节的数据读入一个
* byte 数组中。 int read(byte[] b, int off, int len) 从此输入流中将最多 len 个字节的数据读入一个 byte
* 数组中。
*/
is.read(b, 0, b.length);
value = bytesToHexString(b);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return value;
}
//测试2...根据流
FileInputStream is = null;
is = new FileInputStream("C:\\temp\\WechatIMG149.jpeg");
final String fileType2 = getFileTypeByFileInputStream(is);
System.out.println(fileType2);
}
/**
* <p>
* Title:bytesToHexString
* </p>
* <p>
* Description: 将要读取文件头信息的文件的byte数组转换成string类型表示
* </p>
*
* @param src 要读取文件头信息的文件的byte数组
* @return 文件头信息
*/
private static String bytesToHexString(byte[] src) {
StringBuilder builder = new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
String hv;
for (int i = 0; i < src.length; i++) {
// 以十六进制(基数 16)无符号整数形式返回一个整数参数的字符串表示形式,并转换为大写
hv = Integer.toHexString(src[i] & 0xFF).toUpperCase();
if (hv.length() < 2) {
builder.append(0);
}
builder.append(hv);
}
return builder.toString();
}
/**
* 获取指定文件的大小
*/
public static long getFileSize(File file) throws Exception {
long size = 0;
if (file.exists()) {
FileInputStream fis = null;
fis = new FileInputStream(file);
size = fis.available();
} else {
file.createNewFile();
}
return size;
}
/**
* 获取指定文件的大小
*/
public static long getFileSize(File file) throws Exception {
long size = 0;
if (file.exists()) {
try (FileInputStream fis = new FileInputStream(file)) {
size = fis.available();
}
} else {
file.createNewFile();
}
return size;
}
/**
* 压缩后的文件名
*/
private static String zipName(String name) {
String prefix = "";
if (name.indexOf(".") != -1) {
prefix = name.substring(0, name.lastIndexOf("."));
} else {
prefix = name;
}
return prefix + ".zip";
}
/**
* 压缩后的文件名
*/
private static String zipName(String name) {
String prefix = "";
if (name.indexOf(".") != -1) {
prefix = name.substring(0, name.lastIndexOf("."));
} else {
prefix = name;
}
return prefix + ".zip";
}
/**
* 获取文件的 MD5
*/
public static String getFileMD5(byte[] bytes) {
if (bytes == null) {
return null;
}
MessageDigest digest = null;
InputStream in = null;
byte buffer[] = new byte[1024];
int len;
try {
digest = MessageDigest.getInstance("MD5");
in = new ByteArrayInputStream(bytes);
while ((len = in.read(buffer, 0, 1024)) != -1) {
digest.update(buffer, 0, len);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
BigInteger bigInt = new BigInteger(1, digest.digest());
return bigInt.toString(16);
}
/**
* 获取文件的 MD5
*/
public static String getFileMD5(byte[] bytes) {
if (bytes == null) {
return null;
}
MessageDigest digest = null;
InputStream in = null;
byte buffer[] = new byte[1024];
int len;
try {
digest = MessageDigest.getInstance("MD5");
in = new ByteArrayInputStream(bytes);
while ((len = in.read(buffer, 0, 1024)) != -1) {
digest.update(buffer, 0, len);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
BigInteger bigInt = new BigInteger(1, digest.digest());
return bigInt.toString(16);
}
}
\ No newline at end of file
package com.x.file.assemble.control.jaxrs.attachment2;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.apache.commons.lang3.StringUtils;
import com.google.gson.JsonElement;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
......@@ -10,20 +20,16 @@ import com.x.base.core.project.bean.WrapCopierFactory;
import com.x.base.core.project.gson.GsonPropertyObject;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.file.assemble.control.Business;
import com.x.file.core.entity.open.FileStatus;
import com.x.file.core.entity.personal.Attachment2;
import com.x.file.core.entity.personal.Attachment2_;
import org.apache.commons.lang3.StringUtils;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;
class ActionListFileTypePaging extends BaseAction {
private static Logger logger = LoggerFactory.getLogger(ActionListFileTypePaging.class);
ActionResult<List<Wo>> execute(EffectivePerson effectivePerson, Integer page, Integer size, JsonElement jsonElement)
throws Exception {
......@@ -42,6 +48,7 @@ class ActionListFileTypePaging extends BaseAction {
try {
wo.setPath(business.folder2().getSupPath(wo.getFolder()));
} catch (Exception e) {
logger.error(e);
}
});
result.setData(wos);
......
......@@ -8,6 +8,8 @@ import com.x.base.core.project.bean.WrapCopier;
import com.x.base.core.project.bean.WrapCopierFactory;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.SortTools;
import com.x.file.assemble.control.Business;
import com.x.file.core.entity.personal.Attachment2;
......@@ -16,16 +18,19 @@ import java.util.List;
class ActionListWithFilter extends BaseAction {
private static Logger logger = LoggerFactory.getLogger(ActionListWithFilter.class);
ActionResult<List<Wo>> execute(EffectivePerson effectivePerson, String name) throws Exception {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<List<Wo>> result = new ActionResult<>();
Business business = new Business(emc);
List<String> ids = business.attachment2().listWithName(effectivePerson.getDistinguishedName(),name);
List<String> ids = business.attachment2().listWithName(effectivePerson.getDistinguishedName(), name);
List<Wo> wos = Wo.copier.copy(emc.list(Attachment2.class, ids));
wos.stream().forEach(wo -> {
try {
wo.setPath(business.folder2().getSupPath(wo.getFolder()));
} catch (Exception e) {
logger.error(e);
}
});
SortTools.desc(wos, false, "createTime");
......
......@@ -159,7 +159,9 @@ public class ActiveMQ implements MQInterface {
java.security.GeneralSecurityException, java.security.cert.CertificateException, java.io.IOException,
java.security.UnrecoverableKeyException {
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(keyStore), keyStorePassword.toCharArray());
try (FileInputStream fis = new FileInputStream(keyStore)) {
ks.load(new FileInputStream(keyStore), keyStorePassword.toCharArray());
}
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, keyStorePassword.toCharArray());
return kmf.getKeyManagers();
......
......@@ -14,11 +14,16 @@ import com.x.base.core.project.bean.WrapCopier;
import com.x.base.core.project.bean.WrapCopierFactory;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.ListTools;
import com.x.processplatform.core.entity.element.Application;
import com.x.processplatform.core.entity.element.Script;
class ActionListPaging extends BaseAction {
private static Logger logger = LoggerFactory.getLogger(ActionListPaging.class);
ActionResult<List<Wo>> execute(EffectivePerson effectivePerson, Integer page, Integer size) throws Exception {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<List<Wo>> result = new ActionResult<>();
......@@ -33,6 +38,7 @@ class ActionListPaging extends BaseAction {
wo.setApplicationName(app.getName());
}
} catch (Exception e) {
logger.error(e);
}
});
result.setData(wos);
......
......@@ -3,7 +3,6 @@ package com.x.processplatform.assemble.surface.jaxrs.attachment;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
......@@ -27,6 +26,8 @@ import com.x.base.core.project.gson.GsonPropertyObject;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.jaxrs.WoId;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.DocumentTools;
import com.x.processplatform.assemble.surface.Business;
import com.x.processplatform.assemble.surface.ThisApplication;
......@@ -35,14 +36,17 @@ import com.x.processplatform.core.entity.content.Work;
class ActionDocToWord extends BaseAction {
private static Logger logger = LoggerFactory.getLogger(ActionDocToWord.class);
ActionResult<Wo> execute(EffectivePerson effectivePerson, String workId, JsonElement jsonElement) throws Exception {
ActionResult<Wo> result = new ActionResult<>();
Wi wi = this.convertToWrapIn(jsonElement, Wi.class);
if(StringUtils.isNotBlank(wi.getContent())){
if (StringUtils.isNotBlank(wi.getContent())) {
try {
String decodedContent = URLDecoder.decode(wi.getContent(), StandardCharsets.UTF_8.name());
wi.setContent(decodedContent);
} catch (Exception e) {
logger.error(e);
}
}
Work work = null;
......
......@@ -71,6 +71,7 @@ class ActionUploadWorkInfo extends BaseAction {
try {
workHtml = URLDecoder.decode(workHtml, StandardCharsets.UTF_8.name());
} catch (Exception e) {
logger.error(e);
}
if (workHtml.toLowerCase().indexOf("<html") == -1) {
workHtml = "<html><head></head><body>" + workHtml + "</body></html>";
......
......@@ -99,6 +99,7 @@ class ActionListMyFilterPaging extends BaseAction {
try {
urgeTime = Integer.parseInt(wi.getUrgeTime());
} catch (NumberFormatException e) {
logger.error(e);
}
p = cb.and(p, cb.lessThanOrEqualTo(root.get(Task_.urgeTime),
DateTools.getAdjustTimeDay(null, 0, -urgeTime, 0, 0)));
......@@ -170,6 +171,7 @@ class ActionListMyFilterPaging extends BaseAction {
try {
urgeTime = Integer.parseInt(wi.getUrgeTime());
} catch (NumberFormatException e) {
logger.error(e);
}
p = cb.and(p, cb.lessThanOrEqualTo(root.get(Task_.urgeTime),
DateTools.getAdjustTimeDay(null, 0, -urgeTime, 0, 0)));
......
......@@ -27,185 +27,182 @@ import java.util.HashMap;
import java.util.Map;
/**
* android 打包
* Created by fancyLou on 6/15/21.
* Copyright © 2021 O2. All rights reserved.
* android 打包 Created by fancyLou on 6/15/21. Copyright © 2021 O2. All rights
* reserved.
*/
public class ActionAndroidPack extends BaseAction {
private static Logger logger = LoggerFactory.getLogger(ActionAndroidPack.class);
ActionResult<Wo> execute(String token, String appName, String o2ServerProtocol, String o2ServerHost, String o2ServerPort,
String o2ServerContext, String fileName, byte[] bytes, FormDataContentDisposition disposition) throws Exception {
ActionResult<Wo> result = new ActionResult<Wo>();
if (StringUtils.isEmpty(token)) {
throw new ExceptionNoToken();
}
if (StringUtils.isEmpty(appName)) {
throw new ExceptionEmptyProperty("appName");
}
if (appName.length() > 6) {
throw new ExceptionAppNameMax6();
}
if (StringUtils.isEmpty(o2ServerProtocol)) {
throw new ExceptionEmptyProperty("o2ServerProtocol");
}
if (StringUtils.isEmpty(o2ServerHost)) {
throw new ExceptionEmptyProperty("o2ServerHost");
}
if (StringUtils.isEmpty(o2ServerPort)) {
throw new ExceptionEmptyProperty("o2ServerPort");
}
if (StringUtils.isEmpty(o2ServerContext)) {
throw new ExceptionEmptyProperty("o2ServerContext");
}
/** 文件名编码转换 */
if (StringUtils.isEmpty(fileName)) {
try {
fileName = new String(disposition.getFileName().getBytes(DefaultCharset.charset_iso_8859_1),
DefaultCharset.charset);
} catch (Exception e) {
logger.error(e);
}
}
fileName = FilenameUtils.getName(fileName);
if (StringUtils.isEmpty(fileName)) {
throw new ExceptionFileNameEmpty();
}
if (!fileName.toLowerCase().endsWith("png")) {
throw new ExceptionFileNotPng();
}
String s = postFormData(token, appName, o2ServerProtocol, o2ServerHost, o2ServerPort, o2ServerContext, fileName, bytes);
Type type = new TypeToken<AppPackResult<IdValue>>() {
}.getType();
AppPackResult<IdValue> appPackResult = XGsonBuilder.instance().fromJson(s, type);
Wo wo = new Wo();
if (appPackResult.getResult().equals(AppPackResult.result_failure)) {
wo.setValue(false);
result.setMessage(appPackResult.getMessage());
} else {
wo.setValue(true);
}
result.setData(wo);
return result;
}
/**
* formData 提交打包信息
* @param token
* @param appName
* @param o2ServerProtocol
* @param o2ServerHost
* @param o2ServerPort
* @param o2ServerContext
* @param fileName
* @param bytes
* @return
* @throws Exception
*/
private String postFormData(String token, String appName, String o2ServerProtocol, String o2ServerHost, String o2ServerPort,
String o2ServerContext, String fileName, byte[] bytes) throws Exception {
logger.info("发起打包请求,form : " + token + " ," + appName + " ,"+ o2ServerProtocol + " ,"+ o2ServerHost + " ,"+ o2ServerPort + " ,"+ o2ServerContext + " ,"+ fileName);
String boundary = "abcdefghijk";
String end = "\r\n";
String twoHyphens = "--";
String address = Config.collect().appPackServerApi(Collect.ADDRESS_APPPACK_SAVE);
logger.info("发起打包请求,url " + address);
URL url = new URL(address);
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setUseCaches(false);
httpUrlConnection.setRequestMethod(ConnectionAction.METHOD_POST);
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setDoInput(true);
// heads
Map<String, String> map = new HashMap<>();
map.put(ConnectionAction.ACCESS_CONTROL_ALLOW_CREDENTIALS,
ConnectionAction.ACCESS_CONTROL_ALLOW_CREDENTIALS_VALUE);
map.put(ConnectionAction.ACCESS_CONTROL_ALLOW_HEADERS,
"x-requested-with, x-request, Content-Type, x-cipher, x-client, x-token, token");
map.put(ConnectionAction.ACCESS_CONTROL_ALLOW_METHODS, ConnectionAction.ACCESS_CONTROL_ALLOW_METHODS_VALUE);
map.put(ConnectionAction.CACHE_CONTROL, ConnectionAction.CACHE_CONTROL_VALUE);
map.put(ConnectionAction.CONTENT_TYPE, "multipart/form-data;boundary=" + boundary);
// 设置字符编码连接参数
map.put("Connection", "Keep-Alive");
map.put("Charset", "UTF-8");
map.put("token", token);
for (Map.Entry<String, String> en : map.entrySet()) {
if (StringUtils.isNotEmpty(en.getValue())) {
httpUrlConnection.setRequestProperty(en.getKey(), en.getValue());
}
}
// form data
DataOutputStream ds = new DataOutputStream(httpUrlConnection.getOutputStream());
// properties
writeFormProperties("appName", appName, boundary, end, twoHyphens, ds);
writeFormProperties("o2ServerProtocol", o2ServerProtocol, boundary, end, twoHyphens, ds);
writeFormProperties("o2ServerHost", o2ServerHost, boundary, end, twoHyphens, ds);
writeFormProperties("o2ServerPort", o2ServerPort, boundary, end, twoHyphens, ds);
writeFormProperties("o2ServerContext", o2ServerContext, boundary, end, twoHyphens, ds);
writeFormProperties("collectName", Config.collect().getName(), boundary, end, twoHyphens, ds);
// file
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; " + "name=\"file\";filename=\"" + URLEncoder.encode(fileName, DefaultCharset.name) + "\"" + end);
ds.writeBytes(end);
ds.write(bytes, 0, bytes.length);
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary+twoHyphens + end);
/* close streams */
ds.flush();
String result = "";
try (InputStream input = httpUrlConnection.getInputStream()) {
result = IOUtils.toString(input, StandardCharsets.UTF_8);
}
int code = httpUrlConnection.getResponseCode();
if (code != 200) {
throw new Exception("connection{url:" + httpUrlConnection.getURL() + "}, response error{responseCode:" + code
+ "}, response:" + result + ".");
}
httpUrlConnection.disconnect();
try {
ds.close();
} catch (IOException e) {
logger.error(e);
}
logger.info("打包请求返回,result : "+result);
return result;
}
private void writeFormProperties(String name, String value, String boundary, String end, String twoHyphens, DataOutputStream ds) throws IOException {
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; name=\""+name+"\"");
ds.writeBytes(end);
ds.writeBytes("Content-Length:"+value.length());
ds.writeBytes(end);
ds.writeBytes(end);
ds.write(value.getBytes(StandardCharsets.UTF_8));
ds.writeBytes(end);
}
public static class IdValue {
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
public static class Wo extends WrapBoolean {
}
public class ActionAndroidPack extends BaseAction {
private static Logger logger = LoggerFactory.getLogger(ActionAndroidPack.class);
ActionResult<Wo> execute(String token, String appName, String o2ServerProtocol, String o2ServerHost,
String o2ServerPort, String o2ServerContext, String fileName, byte[] bytes,
FormDataContentDisposition disposition) throws Exception {
ActionResult<Wo> result = new ActionResult<Wo>();
if (StringUtils.isEmpty(token)) {
throw new ExceptionNoToken();
}
if (StringUtils.isEmpty(appName)) {
throw new ExceptionEmptyProperty("appName");
}
if (appName.length() > 6) {
throw new ExceptionAppNameMax6();
}
if (StringUtils.isEmpty(o2ServerProtocol)) {
throw new ExceptionEmptyProperty("o2ServerProtocol");
}
if (StringUtils.isEmpty(o2ServerHost)) {
throw new ExceptionEmptyProperty("o2ServerHost");
}
if (StringUtils.isEmpty(o2ServerPort)) {
throw new ExceptionEmptyProperty("o2ServerPort");
}
if (StringUtils.isEmpty(o2ServerContext)) {
throw new ExceptionEmptyProperty("o2ServerContext");
}
/** 文件名编码转换 */
if (StringUtils.isEmpty(fileName)) {
try {
fileName = new String(disposition.getFileName().getBytes(DefaultCharset.charset_iso_8859_1),
DefaultCharset.charset);
} catch (Exception e) {
logger.error(e);
}
}
fileName = FilenameUtils.getName(fileName);
if (StringUtils.isEmpty(fileName)) {
throw new ExceptionFileNameEmpty();
}
if (!fileName.toLowerCase().endsWith("png")) {
throw new ExceptionFileNotPng();
}
String s = postFormData(token, appName, o2ServerProtocol, o2ServerHost, o2ServerPort, o2ServerContext, fileName,
bytes);
Type type = new TypeToken<AppPackResult<IdValue>>() {
}.getType();
AppPackResult<IdValue> appPackResult = XGsonBuilder.instance().fromJson(s, type);
Wo wo = new Wo();
if (appPackResult.getResult().equals(AppPackResult.result_failure)) {
wo.setValue(false);
result.setMessage(appPackResult.getMessage());
} else {
wo.setValue(true);
}
result.setData(wo);
return result;
}
/**
* formData 提交打包信息
*
* @param token
* @param appName
* @param o2ServerProtocol
* @param o2ServerHost
* @param o2ServerPort
* @param o2ServerContext
* @param fileName
* @param bytes
* @return
* @throws Exception
*/
private String postFormData(String token, String appName, String o2ServerProtocol, String o2ServerHost,
String o2ServerPort, String o2ServerContext, String fileName, byte[] bytes) throws Exception {
logger.info("发起打包请求,form : " + token + " ," + appName + " ," + o2ServerProtocol + " ," + o2ServerHost + " ,"
+ o2ServerPort + " ," + o2ServerContext + " ," + fileName);
String boundary = "abcdefghijk";
String end = "\r\n";
String twoHyphens = "--";
String address = Config.collect().appPackServerApi(Collect.ADDRESS_APPPACK_SAVE);
logger.info("发起打包请求,url " + address);
URL url = new URL(address);
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setUseCaches(false);
httpUrlConnection.setRequestMethod(ConnectionAction.METHOD_POST);
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setDoInput(true);
// heads
Map<String, String> map = new HashMap<>();
map.put(ConnectionAction.ACCESS_CONTROL_ALLOW_CREDENTIALS,
ConnectionAction.ACCESS_CONTROL_ALLOW_CREDENTIALS_VALUE);
map.put(ConnectionAction.ACCESS_CONTROL_ALLOW_HEADERS,
"x-requested-with, x-request, Content-Type, x-cipher, x-client, x-token, token");
map.put(ConnectionAction.ACCESS_CONTROL_ALLOW_METHODS, ConnectionAction.ACCESS_CONTROL_ALLOW_METHODS_VALUE);
map.put(ConnectionAction.CACHE_CONTROL, ConnectionAction.CACHE_CONTROL_VALUE);
map.put(ConnectionAction.CONTENT_TYPE, "multipart/form-data;boundary=" + boundary);
// 设置字符编码连接参数
map.put("Connection", "Keep-Alive");
map.put("Charset", "UTF-8");
map.put("token", token);
for (Map.Entry<String, String> en : map.entrySet()) {
if (StringUtils.isNotEmpty(en.getValue())) {
httpUrlConnection.setRequestProperty(en.getKey(), en.getValue());
}
}
// form data
try (DataOutputStream ds = new DataOutputStream(httpUrlConnection.getOutputStream())) {
// properties
writeFormProperties("appName", appName, boundary, end, twoHyphens, ds);
writeFormProperties("o2ServerProtocol", o2ServerProtocol, boundary, end, twoHyphens, ds);
writeFormProperties("o2ServerHost", o2ServerHost, boundary, end, twoHyphens, ds);
writeFormProperties("o2ServerPort", o2ServerPort, boundary, end, twoHyphens, ds);
writeFormProperties("o2ServerContext", o2ServerContext, boundary, end, twoHyphens, ds);
writeFormProperties("collectName", Config.collect().getName(), boundary, end, twoHyphens, ds);
// file
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; " + "name=\"file\";filename=\""
+ URLEncoder.encode(fileName, DefaultCharset.name) + "\"" + end);
ds.writeBytes(end);
ds.write(bytes, 0, bytes.length);
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
/* close streams */
ds.flush();
}
String result = "";
try (InputStream input = httpUrlConnection.getInputStream()) {
result = IOUtils.toString(input, StandardCharsets.UTF_8);
}
int code = httpUrlConnection.getResponseCode();
if (code != 200) {
throw new Exception("connection{url:" + httpUrlConnection.getURL() + "}, response error{responseCode:"
+ code + "}, response:" + result + ".");
}
httpUrlConnection.disconnect();
logger.info("打包请求返回,result : " + result);
return result;
}
private void writeFormProperties(String name, String value, String boundary, String end, String twoHyphens,
DataOutputStream ds) throws IOException {
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"");
ds.writeBytes(end);
ds.writeBytes("Content-Length:" + value.length());
ds.writeBytes(end);
ds.writeBytes(end);
ds.write(value.getBytes(StandardCharsets.UTF_8));
ds.writeBytes(end);
}
public static class IdValue {
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
public static class Wo extends WrapBoolean {
private static final long serialVersionUID = 1L;
}
}
......@@ -192,7 +192,7 @@ public class DingTalkEncryptor {
try {
clazz = Class.forName(className);
} catch (Exception var3) {
var3.printStackTrace(System.out);
var3.printStackTrace();
}
return clazz;
......@@ -219,7 +219,7 @@ public class DingTalkEncryptor {
Security.setProperty("crypto.policy", "limited");
RemoveCryptographyRestrictions();
} catch (Exception var1) {
var1.printStackTrace(System.out);
var1.printStackTrace();
}
}
......
package com.x.program.center.jaxrs.market;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.entity.enums.CommonStatus;
import com.x.base.core.project.*;
import com.x.base.core.project.Applications;
import com.x.base.core.project.x_cms_assemble_control;
import com.x.base.core.project.x_portal_assemble_designer;
import com.x.base.core.project.x_processplatform_assemble_designer;
import com.x.base.core.project.x_query_assemble_designer;
import com.x.base.core.project.annotation.FieldDescribe;
import com.x.base.core.project.bean.NameValuePair;
import com.x.base.core.project.config.Collect;
......@@ -23,7 +43,11 @@ import com.x.base.core.project.jaxrs.WoId;
import com.x.base.core.project.jaxrs.WrapBoolean;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.*;
import com.x.base.core.project.tools.Crypto;
import com.x.base.core.project.tools.DefaultCharset;
import com.x.base.core.project.tools.FileTools;
import com.x.base.core.project.tools.JarTools;
import com.x.base.core.project.tools.ListTools;
import com.x.cms.core.entity.element.wrap.WrapCms;
import com.x.portal.core.entity.wrap.WrapPortal;
import com.x.processplatform.core.entity.element.wrap.WrapProcessPlatform;
......@@ -36,16 +60,6 @@ import com.x.program.center.core.entity.wrap.WrapAgent;
import com.x.program.center.core.entity.wrap.WrapInvoke;
import com.x.program.center.core.entity.wrap.WrapServiceModule;
import com.x.query.core.entity.wrap.WrapQuery;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.net.Socket;
import java.util.*;
class ActionInstallOrUpdate extends BaseAction {
......@@ -59,20 +73,21 @@ class ActionInstallOrUpdate extends BaseAction {
if (null == app) {
throw new ExceptionEntityNotExist(id, Application.class);
}
if(!hasAuth(effectivePerson, null)){
if (!hasAuth(effectivePerson, null)) {
throw new ExceptionAccessDenied(effectivePerson, app);
}
logger.print("{}发起安装或更新应用:{}", effectivePerson.getDistinguishedName(), app.getName());
Wo wo = new Wo();
wo.setValue(false);
if(BooleanUtils.isTrue(Config.collect().getEnable())) {
if (BooleanUtils.isTrue(Config.collect().getEnable())) {
String token = business.loginCollect();
if(StringUtils.isNotEmpty(token)){
byte[] bytes = ConnectionAction.getFile(Config.collect().url(Collect.ADDRESS_COLLECT_APPLICATION_DOWN + "/" + id),
if (StringUtils.isNotEmpty(token)) {
byte[] bytes = ConnectionAction.getFile(
Config.collect().url(Collect.ADDRESS_COLLECT_APPLICATION_DOWN + "/" + id),
ListTools.toList(new NameValuePair(Collect.COLLECT_TOKEN, token)));
if(bytes!=null){
if (bytes != null) {
InstallData installData = this.install(id, bytes);
if(installData!=null) {
if (installData != null) {
wo.setValue(true);
emc.beginTransaction(InstallLog.class);
InstallLog installLog = emc.find(id, InstallLog.class);
......@@ -91,7 +106,7 @@ class ActionInstallOrUpdate extends BaseAction {
installLog.setInstallTime(new Date());
installLog.setUnInstallPerson(null);
installLog.setUnInstallTime(null);
if(!exist){
if (!exist) {
emc.persist(installLog);
}
emc.commit();
......@@ -105,39 +120,43 @@ class ActionInstallOrUpdate extends BaseAction {
}
}
private InstallData install(String id, byte[] bytes) throws Exception{
private InstallData install(String id, byte[] bytes) throws Exception {
InstallData installData = new InstallData();
File tempFile = new File(Config.base(), "local/temp/install");
FileTools.forceMkdir(tempFile);
FileUtils.cleanDirectory(tempFile);
File zipFile = new File(tempFile.getAbsolutePath(), id+".zip");
File zipFile = new File(tempFile.getAbsolutePath(), id + ".zip");
FileUtils.writeByteArrayToFile(zipFile, bytes);
File dist = new File(tempFile.getAbsolutePath(), "data");
FileTools.forceMkdir(dist);
JarTools.unjar(zipFile, new ArrayList<>(), dist, true);
File[] files = dist.listFiles();
for(File file : files){
if(!file.isDirectory()){
if(file.getName().toLowerCase().endsWith(".xapp")){
//过滤必要的文件
File[] files = dist.listFiles(new FileFilter() {
public boolean accept(File pathname) {
return true;
}
});
for (File file : files) {
if (!file.isDirectory()) {
if (file.getName().toLowerCase().endsWith(".xapp")) {
String json = FileUtils.readFileToString(file, DefaultCharset.charset);
Gson gson = new Gson();
JsonElement jsonElement = gson.fromJson(json, JsonElement.class);
WrapModule module = this.convertToWrapIn(jsonElement, WrapModule.class);
this.installModule(module);
installData.setWrapModule(module);
}else if(file.getName().toLowerCase().endsWith(".app.zip")){
} else if (file.getName().toLowerCase().endsWith(".app.zip")) {
logger.print("开始安装自定义应用:{}", file.getName());
this.installCustomApp(file.getName(), FileUtils.readFileToByteArray(file));
installData.setCustomApp(file.getName());
logger.print("完成自定义应用安装:{}", file.getName());
}else if(file.getName().toLowerCase().endsWith(".zip")){
} else if (file.getName().toLowerCase().endsWith(".zip")) {
logger.print("开始安装静态资源");
try {
Business.dispatch(false, file.getName(), "", FileUtils.readFileToByteArray(file));
installData.setStaticResource(file.getName());
} catch (Exception e) {
logger.print("模块安装成功但静态资源安装失败:{}",e.getMessage());
logger.print("模块安装成功但静态资源安装失败:{}", e.getMessage());
}
}
}
......@@ -146,16 +165,14 @@ class ActionInstallOrUpdate extends BaseAction {
return installData;
}
private InstallWo installModule(WrapModule module) throws Exception{
private InstallWo installModule(WrapModule module) throws Exception {
InstallWo wo = new InstallWo();
logger.print("开始安装应用");
if(module.getProcessPlatformList()!=null) {
if (module.getProcessPlatformList() != null) {
for (WrapProcessPlatform obj : module.getProcessPlatformList()) {
wo.getProcessPlatformList()
.add(ThisApplication.context().applications()
.putQuery(x_processplatform_assemble_designer.class,
Applications.joinQueryUri("input", "cover"), obj)
.getData(WoId.class).getId());
wo.getProcessPlatformList().add(
ThisApplication.context().applications().putQuery(x_processplatform_assemble_designer.class,
Applications.joinQueryUri("input", "cover"), obj).getData(WoId.class).getId());
obj.setIcon(null);
obj.setApplicationDictList(null);
obj.setFileList(null);
......@@ -164,13 +181,11 @@ class ActionInstallOrUpdate extends BaseAction {
obj.setScriptList(null);
}
}
if(module.getCmsList()!=null) {
if (module.getCmsList() != null) {
for (WrapCms obj : module.getCmsList()) {
wo.getCmsList()
.add(ThisApplication.context().applications()
.putQuery(x_cms_assemble_control.class,
Applications.joinQueryUri("input", "cover"), obj)
.getData(WoId.class).getId());
wo.getCmsList().add(ThisApplication.context().applications()
.putQuery(x_cms_assemble_control.class, Applications.joinQueryUri("input", "cover"), obj)
.getData(WoId.class).getId());
obj.setAppIcon(null);
obj.setAppDictList(null);
obj.setCategoryInfoList(null);
......@@ -179,13 +194,11 @@ class ActionInstallOrUpdate extends BaseAction {
obj.setScriptList(null);
}
}
if(module.getPortalList()!=null) {
if (module.getPortalList() != null) {
for (WrapPortal obj : module.getPortalList()) {
wo.getPortalList()
.add(ThisApplication.context().applications()
.putQuery(x_portal_assemble_designer.class,
Applications.joinQueryUri("input", "cover"), obj)
.getData(WoId.class).getId());
wo.getPortalList().add(ThisApplication.context().applications()
.putQuery(x_portal_assemble_designer.class, Applications.joinQueryUri("input", "cover"), obj)
.getData(WoId.class).getId());
obj.setIcon(null);
obj.setFileList(null);
obj.setPageList(null);
......@@ -193,13 +206,11 @@ class ActionInstallOrUpdate extends BaseAction {
obj.setWidgetList(null);
}
}
if(module.getQueryList()!=null){
if (module.getQueryList() != null) {
for (WrapQuery obj : module.getQueryList()) {
wo.getQueryList()
.add(ThisApplication.context().applications()
.putQuery(x_query_assemble_designer.class,
Applications.joinQueryUri("input", "cover"), obj)
.getData(WoId.class).getId());
wo.getQueryList().add(ThisApplication.context().applications()
.putQuery(x_query_assemble_designer.class, Applications.joinQueryUri("input", "cover"), obj)
.getData(WoId.class).getId());
obj.setIcon(null);
obj.setRevealList(null);
obj.setViewList(null);
......@@ -209,11 +220,10 @@ class ActionInstallOrUpdate extends BaseAction {
}
}
if(module.getServiceModuleList()!=null) {
if (module.getServiceModuleList() != null) {
for (WrapServiceModule obj : module.getServiceModuleList()) {
wo.getServiceModuleList()
.add(CipherConnectionAction.put(false,
Config.url_x_program_center_jaxrs("input", "cover"), obj)
.add(CipherConnectionAction.put(false, Config.url_x_program_center_jaxrs("input", "cover"), obj)
.getData(WoId.class).getId());
if (obj.getAgentList() != null) {
for (WrapAgent agent : obj.getAgentList()) {
......@@ -221,7 +231,7 @@ class ActionInstallOrUpdate extends BaseAction {
}
}
if (obj.getInvokeList() != null) {
for(WrapInvoke invoke : obj.getInvokeList()){
for (WrapInvoke invoke : obj.getInvokeList()) {
invoke.setText(null);
}
}
......@@ -231,16 +241,16 @@ class ActionInstallOrUpdate extends BaseAction {
return wo;
}
private void installCustomApp(String fileName, byte[] bytes) throws Exception{
private void installCustomApp(String fileName, byte[] bytes) throws Exception {
Nodes nodes = Config.nodes();
for (String node : nodes.keySet()){
if(nodes.get(node).getApplication().getEnable()) {
logger.print("socket deploy custom app{} to {}:{}",fileName, node, nodes.get(node).nodeAgentPort());
for (String node : nodes.keySet()) {
if (nodes.get(node).getApplication().getEnable()) {
logger.print("socket deploy custom app{} to {}:{}", fileName, node, nodes.get(node).nodeAgentPort());
try (Socket socket = new Socket(node, nodes.get(node).nodeAgentPort())) {
socket.setKeepAlive(true);
socket.setSoTimeout(10000);
try (DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
DataInputStream dis = new DataInputStream(socket.getInputStream())) {
DataInputStream dis = new DataInputStream(socket.getInputStream())) {
Map<String, Object> commandObject = new HashMap<>();
commandObject.put("command", "redeploy:customZip");
commandObject.put("credential", Crypto.rsaEncrypt("o2@", Config.publicKey()));
......
package com.x.query.assemble.surface.jaxrs.table;
import com.x.attendance.assemble.control.service.UserManagerService;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.entity.JpaObject;
......@@ -9,6 +10,8 @@ import com.x.base.core.project.bean.WrapCopierFactory;
import com.x.base.core.project.exception.ExceptionAccessDenied;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
......@@ -20,6 +23,9 @@ import com.x.query.core.entity.Query;
import com.x.query.core.entity.schema.Table;
class ActionListPaging extends BaseAction {
private static Logger logger = LoggerFactory.getLogger(ActionListPaging.class);
ActionResult<List<Wo>> execute(EffectivePerson effectivePerson, Integer page, Integer size) throws Exception {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<List<Wo>> result = new ActionResult<>();
......@@ -34,11 +40,12 @@ class ActionListPaging extends BaseAction {
wos.stream().forEach(wo -> {
try {
Query query = emc.find(wo.getQuery(), Query.class);
if(query != null){
if (query != null) {
wo.setQueryName(query.getName());
wo.setQueryAlias(query.getAlias());
}
} catch (Exception e) {
logger.error(e);
}
});
result.setData(wos);
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册