提交 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,19 +61,18 @@ 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;
......@@ -81,45 +80,49 @@ public class Excel2003Reader implements HSSFListener{
/**
* 遍历excel下所有的sheet
*
* @param fileKey
* @throws IOException
*/
public void process(String fileName ) throws IOException {
public void process(String fileName) throws IOException {
this.fs = new POIFSFileSystem(new FileInputStream(fileName));
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener( this);
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 );
if (outputFormulaValues) {
request.addListenerForAllRecords(formatListener);
} else {
workbookBuildingListener = new SheetRecordCollectingListener( formatListener);
workbookBuildingListener = new SheetRecordCollectingListener(formatListener);
request.addListenerForAllRecords(workbookBuildingListener);
}
factory.processWorkbookEvents(request, fs);
//数据读取完成
}
// 数据读取完成
}
/**
* 遍历excel下所有的sheet
*
* @param fileKey
* @throws IOException
*/
public void process( InputStream is ) throws IOException {
this.fs = new POIFSFileSystem( is );
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener( this);
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 );
if (outputFormulaValues) {
request.addListenerForAllRecords(formatListener);
} else {
workbookBuildingListener = new SheetRecordCollectingListener( formatListener);
workbookBuildingListener = new SheetRecordCollectingListener(formatListener);
request.addListenerForAllRecords(workbookBuildingListener);
}
factory.processWorkbookEvents(request, fs);
//数据读取完成
}
// 数据读取完成
}
/**
......@@ -140,14 +143,12 @@ public class Excel2003Reader implements HSSFListener{
if (br.getType() == BOFRecord.TYPE_WORKSHEET) {
// 如果有需要,则建立子工作薄
if (workbookBuildingListener != null && stubWorkbook == null) {
stubWorkbook = workbookBuildingListener
.getStubHSSFWorkbook();
stubWorkbook = workbookBuildingListener.getStubHSSFWorkbook();
}
sheetIndex++;
if (orderedBSRs == null) {
orderedBSRs = BoundSheetRecord
.orderByBofPosition(boundSheetRecords);
orderedBSRs = BoundSheetRecord.orderByBofPosition(boundSheetRecords);
}
sheetName = orderedBSRs[sheetIndex].getSheetname();
}
......@@ -164,15 +165,15 @@ public class Excel2003Reader implements HSSFListener{
thisStr = "";
rowlist.add(thisColumn, thisStr);
break;
case BoolErrRecord.sid: //单元格为布尔类型
case BoolErrRecord.sid: // 单元格为布尔类型
BoolErrRecord berec = (BoolErrRecord) record;
thisRow = berec.getRow();
thisColumn = berec.getColumn();
thisStr = berec.getBooleanValue()+"";
thisStr = berec.getBooleanValue() + "";
rowlist.add(thisColumn, thisStr);
break;
case FormulaRecord.sid: //单元格为公式类型
case FormulaRecord.sid: // 单元格为公式类型
FormulaRecord frec = (FormulaRecord) record;
thisRow = frec.getRow();
thisColumn = frec.getColumn();
......@@ -189,9 +190,9 @@ public class Excel2003Reader implements HSSFListener{
} else {
thisStr = '"' + HSSFFormulaParser.toFormulaString(stubWorkbook, frec.getParsedExpression()) + '"';
}
rowlist.add(thisColumn,thisStr);
rowlist.add(thisColumn, thisStr);
break;
case StringRecord.sid://单元格中公式的字符串
case StringRecord.sid:// 单元格中公式的字符串
if (outputNextStringRecord) {
// String for formula
StringRecord srec = (StringRecord) record;
......@@ -206,28 +207,27 @@ public class Excel2003Reader implements HSSFListener{
curRow = thisRow = lrec.getRow();
thisColumn = lrec.getColumn();
value = lrec.getValue().trim();
value = value.equals("")?" ":value;
value = value.equals("") ? " " : value;
this.rowlist.add(thisColumn, value);
break;
case LabelSSTRecord.sid: //单元格为字符串类型
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);
value = sstRecord.getString(lsrec.getSSTIndex()).toString().trim();
value = value.equals("") ? " " : value;
rowlist.add(thisColumn, value);
}
break;
case NumberRecord.sid: //单元格为数字类型
case NumberRecord.sid: // 单元格为数字类型
NumberRecord numrec = (NumberRecord) record;
curRow = thisRow = numrec.getRow();
thisColumn = numrec.getColumn();
value = formatListener.formatNumberDateCell(numrec).trim();
value = value.equals("")?" ":value;
value = value.equals("") ? " " : value;
// 向容器加入列值
rowlist.add(thisColumn, value);
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, " ");
}
// 更新行和列的值
......@@ -265,7 +265,7 @@ 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");
try (FileOutputStream os = new FileOutputStream("template.xlsx")) {
wb.write(os);
os.close();
}
// 生成xml文件
File tmp = File.createTempFile("sheet", ".xml");
Writer fw = new FileWriter(tmp);
try (Writer fw = new FileWriter(tmp)) {
sw = new SpreadsheetWriter(fw);
generate();
fw.close();
}
// 使用产生的数据替换模板
File templateFile = new File("template.xlsx");
FileOutputStream out = new FileOutputStream(fileName);
try (FileOutputStream out = new FileOutputStream(fileName)) {
substitute(templateFile, tmp, sheetRef.substring(1), out);
out.close();
// 删除文件之前调用一下垃圾回收器,否则无法删除模板文件
System.gc();
}
// 删除临时模板文件
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,19 +62,18 @@ 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;
......@@ -82,53 +81,55 @@ public class Excel2003Reader implements HSSFListener{
/**
* 遍历excel下所有的sheet
*
* @param fileKey
* @throws IOException
*/
public void process( String fileName ) throws IOException {
public void process(String fileName) throws IOException {
this.fs = new POIFSFileSystem( new FileInputStream(fileName) );
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener( this);
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 );
if (outputFormulaValues) {
request.addListenerForAllRecords(formatListener);
} else {
workbookBuildingListener = new SheetRecordCollectingListener( formatListener);
workbookBuildingListener = new SheetRecordCollectingListener(formatListener);
request.addListenerForAllRecords(workbookBuildingListener);
}
factory.processWorkbookEvents(request, fs);
//数据读取完成
// 数据读取完成
}
}
/**
* 遍历excel下所有的sheet
*
* @param fileKey
* @throws IOException
*/
public void process( InputStream is ) throws IOException {
this.fs = new POIFSFileSystem( is );
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener( this);
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 );
if (outputFormulaValues) {
request.addListenerForAllRecords(formatListener);
} else {
workbookBuildingListener = new SheetRecordCollectingListener( formatListener);
workbookBuildingListener = new SheetRecordCollectingListener(formatListener);
request.addListenerForAllRecords(workbookBuildingListener);
}
factory.processWorkbookEvents(request, fs);
//数据读取完成
// 数据读取完成
}
}
/**
* HSSFListener 监听方法,处理 Record
*/
@SuppressWarnings( "unchecked" )
@SuppressWarnings("unchecked")
public void processRecord(Record record) {
int thisRow = -1;
int thisColumn = -1;
......@@ -143,14 +144,12 @@ public class Excel2003Reader implements HSSFListener{
if (br.getType() == BOFRecord.TYPE_WORKSHEET) {
// 如果有需要,则建立子工作薄
if (workbookBuildingListener != null && stubWorkbook == null) {
stubWorkbook = workbookBuildingListener
.getStubHSSFWorkbook();
stubWorkbook = workbookBuildingListener.getStubHSSFWorkbook();
}
sheetIndex++;
if (orderedBSRs == null) {
orderedBSRs = BoundSheetRecord
.orderByBofPosition(boundSheetRecords);
orderedBSRs = BoundSheetRecord.orderByBofPosition(boundSheetRecords);
}
sheetName = orderedBSRs[sheetIndex].getSheetname();
}
......@@ -167,15 +166,15 @@ public class Excel2003Reader implements HSSFListener{
thisStr = "";
rowlist.add(thisColumn, thisStr);
break;
case BoolErrRecord.sid: //单元格为布尔类型
case BoolErrRecord.sid: // 单元格为布尔类型
BoolErrRecord berec = (BoolErrRecord) record;
thisRow = berec.getRow();
thisColumn = berec.getColumn();
thisStr = berec.getBooleanValue()+"";
thisStr = berec.getBooleanValue() + "";
rowlist.add(thisColumn, thisStr);
break;
case FormulaRecord.sid: //单元格为公式类型
case FormulaRecord.sid: // 单元格为公式类型
FormulaRecord frec = (FormulaRecord) record;
thisRow = frec.getRow();
thisColumn = frec.getColumn();
......@@ -192,9 +191,9 @@ public class Excel2003Reader implements HSSFListener{
} else {
thisStr = '"' + HSSFFormulaParser.toFormulaString(stubWorkbook, frec.getParsedExpression()) + '"';
}
rowlist.add(thisColumn,thisStr);
rowlist.add(thisColumn, thisStr);
break;
case StringRecord.sid://单元格中公式的字符串
case StringRecord.sid:// 单元格中公式的字符串
if (outputNextStringRecord) {
// String for formula
StringRecord srec = (StringRecord) record;
......@@ -209,28 +208,27 @@ public class Excel2003Reader implements HSSFListener{
curRow = thisRow = lrec.getRow();
thisColumn = lrec.getColumn();
value = lrec.getValue().trim();
value = value.equals( "" )?" ":value;
value = value.equals("") ? " " : value;
this.rowlist.add(thisColumn, value);
break;
case LabelSSTRecord.sid: //单元格为字符串类型
case LabelSSTRecord.sid: // 单元格为字符串类型
LabelSSTRecord lsrec = (LabelSSTRecord) record;
curRow = thisRow = lsrec.getRow();
thisColumn = lsrec.getColumn();
if (sstRecord == null) {
rowlist.add(thisColumn, " " );
rowlist.add(thisColumn, " ");
} else {
value = sstRecord
.getString(lsrec.getSSTIndex()).toString().trim();
value = value.equals( "" )?" ":value;
rowlist.add(thisColumn,value);
value = sstRecord.getString(lsrec.getSSTIndex()).toString().trim();
value = value.equals("") ? " " : value;
rowlist.add(thisColumn, value);
}
break;
case NumberRecord.sid: //单元格为数字类型
case NumberRecord.sid: // 单元格为数字类型
NumberRecord numrec = (NumberRecord) record;
curRow = thisRow = numrec.getRow();
thisColumn = numrec.getColumn();
value = formatListener.formatNumberDateCell(numrec).trim();
value = value.equals( "" )?" ":value;
value = value.equals("") ? " " : value;
// 向容器加入列值
rowlist.add(thisColumn, value);
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, " ");
}
// 更新行和列的值
......@@ -268,7 +266,7 @@ 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,14 +22,13 @@ 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;
......@@ -37,13 +36,13 @@ public class Excel2007Reader extends DefaultHandler {
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;
......@@ -52,25 +51,27 @@ public class Excel2007Reader extends DefaultHandler {
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
* @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
* @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,13 +120,14 @@ 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;
......@@ -131,31 +136,31 @@ public class Excel2007Reader extends DefaultHandler {
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;
......@@ -165,57 +170,55 @@ public class Excel2007Reader extends DefaultHandler {
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" )) {
} else {
// 如果标签名称为 row ,这说明已到行尾,调用 optRows() 方法
if (name.equals("row")) {
rowReader.getRows(sheetIndex,curRow,rowlist, this.fileKey, this.startRow );
rowReader.getRows(sheetIndex, curRow, rowlist, this.fileKey, this.startRow);
rowlist.clear();
curRow++;
curCol = 0;
......@@ -224,9 +227,8 @@ public class Excel2007Reader extends DefaultHandler {
}
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");
try (FileOutputStream os = new FileOutputStream("template.xlsx")) {
wb.write(os);
os.close();
}
// 生成xml文件
File tmp = File.createTempFile("sheet", ".xml");
Writer fw = new FileWriter(tmp);
try (Writer fw = new FileWriter(tmp)) {
sw = new SpreadsheetWriter(fw);
generate();
fw.close();
}
// 使用产生的数据替换模板
File templateFile = new File("template.xlsx");
FileOutputStream out = new FileOutputStream(fileName);
try (FileOutputStream out = new FileOutputStream(fileName)){
substitute(templateFile, tmp, sheetRef.substring(1), out);
out.close();
// 删除文件之前调用一下垃圾回收器,否则无法删除模板文件
System.gc();
}
// 删除临时模板文件
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())){
if (ListTools.isEmpty(wi.getAppIdList())) {
wos = emc.fetchAll(Script.class, Wo.copier);
}else{
} 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,69 +62,71 @@ 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
* @throws IOException
*/
public void process( String fileName ) throws IOException {
public void process(String fileName) throws IOException {
this.fs = new POIFSFileSystem( new FileInputStream(fileName) );
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener( this);
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 );
if (outputFormulaValues) {
request.addListenerForAllRecords(formatListener);
} else {
workbookBuildingListener = new SheetRecordCollectingListener( formatListener);
workbookBuildingListener = new SheetRecordCollectingListener(formatListener);
request.addListenerForAllRecords(workbookBuildingListener);
}
factory.processWorkbookEvents(request, fs);
//数据读取完成
// 数据读取完成
}
}
/**
* 遍历excel下所有的sheet
*
* @param fileKey
* @throws IOException
*/
public void process( InputStream is ) throws IOException {
this.fs = new POIFSFileSystem( is );
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener( this);
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 );
if (outputFormulaValues) {
request.addListenerForAllRecords(formatListener);
} else {
workbookBuildingListener = new SheetRecordCollectingListener( formatListener);
workbookBuildingListener = new SheetRecordCollectingListener(formatListener);
request.addListenerForAllRecords(workbookBuildingListener);
}
factory.processWorkbookEvents(request, fs);
//数据读取完成
// 数据读取完成
}
}
/**
* HSSFListener 监听方法,处理 Record
*/
@SuppressWarnings( "unchecked" )
@SuppressWarnings("unchecked")
public void processRecord(Record record) {
int thisRow = -1;
int thisColumn = -1;
......@@ -139,14 +141,12 @@ public class Excel2003Reader implements HSSFListener{
if (br.getType() == BOFRecord.TYPE_WORKSHEET) {
// 如果有需要,则建立子工作薄
if (workbookBuildingListener != null && stubWorkbook == null) {
stubWorkbook = workbookBuildingListener
.getStubHSSFWorkbook();
stubWorkbook = workbookBuildingListener.getStubHSSFWorkbook();
}
sheetIndex++;
if (orderedBSRs == null) {
orderedBSRs = BoundSheetRecord
.orderByBofPosition(boundSheetRecords);
orderedBSRs = BoundSheetRecord.orderByBofPosition(boundSheetRecords);
}
sheetName = orderedBSRs[sheetIndex].getSheetname();
}
......@@ -163,15 +163,15 @@ public class Excel2003Reader implements HSSFListener{
thisStr = "";
rowlist.add(thisColumn, thisStr);
break;
case BoolErrRecord.sid: //单元格为布尔类型
case BoolErrRecord.sid: // 单元格为布尔类型
BoolErrRecord berec = (BoolErrRecord) record;
thisRow = berec.getRow();
thisColumn = berec.getColumn();
thisStr = berec.getBooleanValue()+"";
thisStr = berec.getBooleanValue() + "";
rowlist.add(thisColumn, thisStr);
break;
case FormulaRecord.sid: //单元格为公式类型
case FormulaRecord.sid: // 单元格为公式类型
FormulaRecord frec = (FormulaRecord) record;
thisRow = frec.getRow();
thisColumn = frec.getColumn();
......@@ -188,9 +188,9 @@ public class Excel2003Reader implements HSSFListener{
} else {
thisStr = '"' + HSSFFormulaParser.toFormulaString(stubWorkbook, frec.getParsedExpression()) + '"';
}
rowlist.add(thisColumn,thisStr);
rowlist.add(thisColumn, thisStr);
break;
case StringRecord.sid://单元格中公式的字符串
case StringRecord.sid:// 单元格中公式的字符串
if (outputNextStringRecord) {
// String for formula
StringRecord srec = (StringRecord) record;
......@@ -205,28 +205,27 @@ public class Excel2003Reader implements HSSFListener{
curRow = thisRow = lrec.getRow();
thisColumn = lrec.getColumn();
value = lrec.getValue().trim();
value = value.equals( "" )?" ":value;
value = value.equals("") ? " " : value;
this.rowlist.add(thisColumn, value);
break;
case LabelSSTRecord.sid: //单元格为字符串类型
case LabelSSTRecord.sid: // 单元格为字符串类型
LabelSSTRecord lsrec = (LabelSSTRecord) record;
curRow = thisRow = lsrec.getRow();
thisColumn = lsrec.getColumn();
if (sstRecord == null) {
rowlist.add(thisColumn, " " );
rowlist.add(thisColumn, " ");
} else {
value = sstRecord
.getString(lsrec.getSSTIndex()).toString().trim();
value = value.equals( "" )?" ":value;
rowlist.add(thisColumn,value);
value = sstRecord.getString(lsrec.getSSTIndex()).toString().trim();
value = value.equals("") ? " " : value;
rowlist.add(thisColumn, value);
}
break;
case NumberRecord.sid: //单元格为数字类型
case NumberRecord.sid: // 单元格为数字类型
NumberRecord numrec = (NumberRecord) record;
curRow = thisRow = numrec.getRow();
thisColumn = numrec.getColumn();
value = formatListener.formatNumberDateCell(numrec).trim();
value = value.equals( "" )?" ":value;
value = value.equals("") ? " " : value;
// 向容器加入列值
rowlist.add(thisColumn, value);
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,7 +262,7 @@ 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
* @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
* @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,13 +113,14 @@ 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;
......@@ -124,31 +129,31 @@ public class Excel2007Reader extends DefaultHandler {
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;
......@@ -159,57 +164,55 @@ public class Excel2007Reader extends DefaultHandler {
}
@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" )) {
} else {
// 如果标签名称为 row ,这说明已到行尾,调用 optRows() 方法
if (name.equals("row")) {
rowReader.getRows(sheetIndex,curRow,rowlist, this.excelReadRuntime );
rowReader.getRows(sheetIndex, curRow, rowlist, this.excelReadRuntime);
rowlist.clear();
curRow++;
curCol = 0;
......@@ -218,9 +221,8 @@ public class Excel2007Reader extends DefaultHandler {
}
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);
}
}
......@@ -27,12 +27,12 @@ public class FileUtil {
mFileTypes.put("68746D6C3E", "html");
mFileTypes.put("44656C69766572792D646174653A", "eml"); // 邮件
mFileTypes.put("D0CF11E0", "doc");
mFileTypes.put("D0CF11E0", "xls");//excel2003版本文件
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("504B0304", "xlsx");// excel2007以上版本文件
mFileTypes.put("52617221", "rar");
mFileTypes.put("57415645", "wav");
mFileTypes.put("41564920", "avi");
......@@ -46,19 +46,30 @@ public class FileUtil {
}
/**
* <p>Title:getFileType </p>
* <p>Description: 根据文件路径获取文件头信息</p>
* <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
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>
* <p>
* Title:getFileTypeByFileInputStream
* </p>
* <p>
* Description: 根据文件流获取文件头信息
* </p>
*
* @param is 文件流
* @return 文件头信息
*/
......@@ -67,8 +78,13 @@ public class FileUtil {
}
/**
* <p>Title:getFileHeader </p>
* <p>Description: 根据文件路径获取文件头信息 </p>
* <p>
* Title:getFileHeader
* </p>
* <p>
* Description: 根据文件路径获取文件头信息
* </p>
*
* @param filePath 文件路径
* @return 十六进制文件头信息
*/
......@@ -79,13 +95,14 @@ public class FileUtil {
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 数组中。
* 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 {
......@@ -97,9 +114,15 @@ public class FileUtil {
}
return value;
}
/**
* <p>Title:getFileHeaderByFileInputStream </p>
* <p>Description: 根据文件流获取文件头信息</p>
* <p>
* Title:getFileHeaderByFileInputStream
* </p>
* <p>
* Description: 根据文件流获取文件头信息
* </p>
*
* @param is 文件流
* @return 十六进制文件头信息
*/
......@@ -108,13 +131,14 @@ public class FileUtil {
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 数组中。
* 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 {
......@@ -124,13 +148,17 @@ public class FileUtil {
}
}
}
System.out.println(value);
return value;
}
/**
* <p>Title:bytesToHexString </p>
* <p>Description: 将要读取文件头信息的文件的byte数组转换成string类型表示 </p>
* <p>
* Title:bytesToHexString
* </p>
* <p>
* Description: 将要读取文件头信息的文件的byte数组转换成string类型表示
* </p>
*
* @param src 要读取文件头信息的文件的byte数组
* @return 文件头信息
*/
......@@ -148,39 +176,18 @@ public class FileUtil {
}
builder.append(hv);
}
//System.out.println(builder.toString());
return builder.toString();
}
/**
* <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); */
//测试2...根据流
FileInputStream is = null;
is = new FileInputStream("C:\\temp\\WechatIMG149.jpeg");
final String fileType2 = getFileTypeByFileInputStream(is);
System.out.println(fileType2);
}
/**
* 获取指定文件的大小
*/
public static long getFileSize(File file) throws Exception {
long size = 0;
if (file.exists()) {
FileInputStream fis = null;
fis = new FileInputStream(file);
try (FileInputStream fis = new FileInputStream(file)) {
size = fis.available();
}
} else {
file.createNewFile();
}
......
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,21 +20,17 @@ 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 {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
......@@ -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");
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,17 +27,16 @@ 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> 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();
......@@ -76,7 +75,8 @@ public class ActionAndroidPack extends BaseAction {
if (!fileName.toLowerCase().endsWith("png")) {
throw new ExceptionFileNotPng();
}
String s = postFormData(token, appName, o2ServerProtocol, o2ServerHost, o2ServerPort, o2ServerContext, fileName, bytes);
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);
......@@ -93,6 +93,7 @@ public class ActionAndroidPack extends BaseAction {
/**
* formData 提交打包信息
*
* @param token
* @param appName
* @param o2ServerProtocol
......@@ -104,9 +105,10 @@ public class ActionAndroidPack extends BaseAction {
* @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);
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 = "--";
......@@ -138,7 +140,7 @@ public class ActionAndroidPack extends BaseAction {
}
}
// form data
DataOutputStream ds = new DataOutputStream(httpUrlConnection.getOutputStream());
try (DataOutputStream ds = new DataOutputStream(httpUrlConnection.getOutputStream())) {
// properties
writeFormProperties("appName", appName, boundary, end, twoHyphens, ds);
writeFormProperties("o2ServerProtocol", o2ServerProtocol, boundary, end, twoHyphens, ds);
......@@ -146,50 +148,45 @@ public class ActionAndroidPack extends BaseAction {
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("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);
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 + ".");
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);
logger.info("打包请求返回,result : " + result);
return result;
}
private void writeFormProperties(String name, String value, String boundary, String end, String twoHyphens, DataOutputStream ds) throws IOException {
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("Content-Disposition: form-data; name=\"" + name + "\"");
ds.writeBytes(end);
ds.writeBytes("Content-Length:"+value.length());
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;
......@@ -203,9 +200,9 @@ public class ActionAndroidPack extends BaseAction {
}
}
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,12 +181,10 @@ 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)
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);
......@@ -179,12 +194,10 @@ 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)
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);
......@@ -193,12 +206,10 @@ 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)
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);
......@@ -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,11 +241,11 @@ 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);
......
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.
先完成此消息的编辑!
想要评论请 注册