提交 2aee8bc9 编写于 作者: Z zhourui

移除okr

上级 39816f78
......@@ -29,7 +29,6 @@
<module>x_meeting_core_entity</module>
<module>x_message_core_entity</module>
<module>x_mind_core_entity</module>
<module>x_okr_core_entity</module>
<module>x_organization_core_entity</module>
<module>x_portal_core_entity</module>
<module>x_processplatform_core_entity</module>
......@@ -50,7 +49,6 @@
<module>x_meeting_assemble_control</module>
<module>x_message_assemble_communicate</module>
<module>x_mind_assemble_control</module>
<module>x_okr_assemble_control</module>
<module>x_organization_assemble_authentication</module>
<module>x_organization_assemble_control</module>
<module>x_organization_assemble_express</module>
......@@ -929,11 +927,6 @@
<artifactId>x_mind_core_entity</artifactId>
<version>5</version>
</dependency>
<dependency>
<groupId>o2oa</groupId>
<artifactId>x_okr_core_entity</artifactId>
<version>5</version>
</dependency>
<dependency>
<groupId>o2oa</groupId>
<artifactId>x_organization_core_entity</artifactId>
......
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>o2oa</groupId>
<artifactId>o2server</artifactId>
<version>5</version>
</parent>
<artifactId>x_okr_assemble_control</artifactId>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>o2oa</groupId>
<artifactId>x_base_core_project</artifactId>
</dependency>
<dependency>
<groupId>o2oa</groupId>
<artifactId>x_organization_core_express</artifactId>
</dependency>
<dependency>
<groupId>o2oa</groupId>
<artifactId>x_okr_core_entity</artifactId>
</dependency>
<dependency>
<groupId>o2oa</groupId>
<artifactId>x_processplatform_core_entity</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<id>describeBuilder</id>
<phase>prepare-package</phase>
<goals>
<goal>java</goal>
</goals>
<configuration>
<addOutputToClasspath>true</addOutputToClasspath>
<includePluginDependencies>true</includePluginDependencies>
<includeProjectDependencies>true</includeProjectDependencies>
<mainClass>com.x.base.core.project.annotation.DescribeBuilder</mainClass>
<arguments>
<argument>${basedir}</argument>
<argument>${project.build.sourceDirectory}</argument>
</arguments>
</configuration>
</execution>
<execution>
<id>apiBuilder</id>
<phase>prepare-package</phase>
<goals>
<goal>java</goal>
</goals>
<configuration>
<addOutputToClasspath>true</addOutputToClasspath>
<includePluginDependencies>true</includePluginDependencies>
<includeProjectDependencies>true</includeProjectDependencies>
<mainClass>com.x.base.core.project.annotation.ApiBuilder</mainClass>
<arguments>
<argument>${basedir}</argument>
<argument>${project.build.sourceDirectory}</argument>
</arguments>
</configuration>
</execution>
<execution>
<id>checkAssemble</id>
<phase>prepare-package</phase>
<goals>
<goal>java</goal>
</goals>
<configuration>
<addOutputToClasspath>true</addOutputToClasspath>
<includePluginDependencies>true</includePluginDependencies>
<includeProjectDependencies>true</includeProjectDependencies>
<mainClass>com.x.base.core.project.build.CheckAssemble</mainClass>
</configuration>
</execution>
<execution>
<id>createWebXml</id>
<phase>prepare-package</phase>
<goals>
<goal>java</goal>
</goals>
<configuration>
<addOutputToClasspath>true</addOutputToClasspath>
<includePluginDependencies>true</includePluginDependencies>
<includeProjectDependencies>true</includeProjectDependencies>
<mainClass>com.x.base.core.project.build.CreateWebXml</mainClass>
<arguments>
<argument>${basedir}</argument>
<argument>${project.artifactId}</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>copy-war</id>
<phase>verify</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>../store</outputDirectory>
<resources>
<resource>
<directory>target</directory>
<includes>
<include>${project.artifactId}.war</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
package com.x.okr.assemble.common.date;
import java.util.Date;
public class MonthOfYear {
private Date startDate = null;
private Date endDate = null;
private String startDateString = null;
private String endDateString = null;
private Integer month = 1;
private Integer year = 1;
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getStartDateString() {
return startDateString;
}
public void setStartDateString(String startDateString) {
this.startDateString = startDateString;
}
public String getEndDateString() {
return endDateString;
}
public void setEndDateString(String endDateString) {
this.endDateString = endDateString;
}
public Integer getMonth() {
return month;
}
public void setMonth(Integer month) {
this.month = month;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
public String toString(){
return this.year + "年" +this.month + "月:" + this.startDateString + " -- " + this.endDateString;
}
}
package com.x.okr.assemble.common.date;
import java.util.Date;
public class WeekOfYear {
private Date startDate = null;
private Date endDate = null;
private String startDateString = null;
private String endDateString = null;
private Integer weekNo = 1;
private Integer year = 1;
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getStartDateString() {
return startDateString;
}
public void setStartDateString(String startDateString) {
this.startDateString = startDateString;
}
public String getEndDateString() {
return endDateString;
}
public void setEndDateString(String endDateString) {
this.endDateString = endDateString;
}
public Integer getWeekNo() {
return weekNo;
}
public void setWeekNo(Integer weekNo) {
this.weekNo = weekNo;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
public String toString(){
return this.year + "年第"+this.weekNo + "周:" + this.startDateString + " -- " + this.endDateString;
}
}
package com.x.okr.assemble.common.excel.reader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.eventusermodel.EventWorkbookBuilder.SheetRecordCollectingListener;
import org.apache.poi.hssf.eventusermodel.FormatTrackingHSSFListener;
import org.apache.poi.hssf.eventusermodel.HSSFEventFactory;
import org.apache.poi.hssf.eventusermodel.HSSFListener;
import org.apache.poi.hssf.eventusermodel.HSSFRequest;
import org.apache.poi.hssf.eventusermodel.MissingRecordAwareHSSFListener;
import org.apache.poi.hssf.eventusermodel.dummyrecord.LastCellOfRowDummyRecord;
import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingCellDummyRecord;
import org.apache.poi.hssf.model.HSSFFormulaParser;
import org.apache.poi.hssf.record.BOFRecord;
import org.apache.poi.hssf.record.BlankRecord;
import org.apache.poi.hssf.record.BoolErrRecord;
import org.apache.poi.hssf.record.BoundSheetRecord;
import org.apache.poi.hssf.record.FormulaRecord;
import org.apache.poi.hssf.record.LabelRecord;
import org.apache.poi.hssf.record.LabelSSTRecord;
import org.apache.poi.hssf.record.NumberRecord;
import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.SSTRecord;
import org.apache.poi.hssf.record.StringRecord;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
/**
* 抽象Excel2003读取器,通过实现HSSFListener监听器,采用事件驱动模式解析excel2003
* 中的内容,遇到特定事件才会触发,大大减少了内存的使用。
*
*/
public class Excel2003Reader implements HSSFListener{
private int minColumns = -1;
private POIFSFileSystem fs;
private int lastRowNumber;
private int lastColumnNumber;
/** Should we output the formula, or the value it has? */
private boolean outputFormulaValues = true;
/** For parsing Formulas */
private SheetRecordCollectingListener workbookBuildingListener;
//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")
private ArrayList boundSheetRecords = new ArrayList();
// For handling formulas with string results
private int nextRow;
private int nextColumn;
private boolean outputNextStringRecord;
//当前行
private int curRow = 0;
//存储行记录的容器
private List<String> rowlist = new ArrayList<String>();;
@SuppressWarnings( "unused" )
private String sheetName;
private String fileKey;
private int startRow;
private IRowReader rowReader;
public void setRowReader(IRowReader rowReader, String fileKey, int startRow ){
this.rowReader = rowReader;
this.fileKey = fileKey;
this.startRow = startRow;
}
/**
* 遍历excel下所有的sheet
* @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);
}
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);
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);
//数据读取完成
}
/**
* HSSFListener 监听方法,处理 Record
*/
@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()) + '"';
}
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;
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;
}
// 遇到新行的操作
if (thisRow != -1 && thisRow != lastRowNumber) {
lastColumnNumber = -1;
}
// 空值的操作
if (record instanceof MissingCellDummyRecord) {
MissingCellDummyRecord mc = (MissingCellDummyRecord) record;
curRow = thisRow = mc.getRow();
thisColumn = mc.getColumn();
rowlist.add(thisColumn," " );
}
// 更新行和列的值
if (thisRow > -1)
lastRowNumber = thisRow;
if (thisColumn > -1)
lastColumnNumber = thisColumn;
// 行结束时的操作
if (record instanceof LastCellOfRowDummyRecord) {
if (minColumns > 0) {
// 列值重新置空
if (lastColumnNumber == -1) {
lastColumnNumber = 0;
}
}
lastColumnNumber = -1;
// 每行结束时, 调用getRows() 方法
rowReader.getRows(sheetIndex,curRow, rowlist, this.fileKey, this.startRow );
// 清空容器
rowlist.clear();
}
}
}
package com.x.okr.assemble.common.excel.reader;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
/**
* 抽象Excel2007读取器,excel2007的底层数据结构是xml文件,采用SAX的事件驱动的方法解析
* 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){
this.rowReader = rowReader;
this.fileKey = fileKey;
this.startRow = startRow;
}
/**只遍历一个电子表格,其中sheetId为要遍历的sheet索引,从1开始,1-3
* @param filename
* @param 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);
sheetIndex++;
InputSource sheetSource = new InputSource(sheet2);
parser.parse(sheetSource);
sheet2.close();
}
/**
* 遍历工作簿中所有的电子表格
* @param filename
* @param fileKey
* @throws Exception
*/
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);
Iterator<InputStream> sheets = r.getSheetsData();
while (sheets.hasNext()) {
curRow = 0;
sheetIndex++;
InputStream sheet = sheets.next();
InputSource sheetSource = new InputSource(sheet);
parser.parse( sheetSource );
sheet.close();
}
//数据读取完成
}
/**
* 遍历工作簿中所有的电子表格
* @param is
* @param fileKey
* @throws Exception
*/
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);
Iterator<InputStream> sheets = r.getSheetsData();
while (sheets.hasNext()) {
curRow = 0;
sheetIndex++;
InputStream sheet = sheets.next();
InputSource sheetSource = new InputSource(sheet);
parser.parse( sheetSource );
sheet.close();
}
//数据读取完成
}
public XMLReader fetchSheetParser(SharedStringsTable sst) throws SAXException {
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)) {
// 如果下一个元素是 SST 的索引,则将nextIsString标记为true
String cellType = attributes.getValue( "t" );
if ( "s".equals(cellType)) {
nextIsString = true;
} else {
nextIsString = false;
}
//日期格式
String cellDateType = attributes.getValue( "s" );
if ( "1".equals(cellDateType)){
dateFlag = true;
} else {
dateFlag = false;
}
String cellNumberType = attributes.getValue( "s" );
if( "2".equals(cellNumberType)){
numberFlag = true;
} else {
numberFlag = false;
}
}
//当元素为t时
if( "t".equals(name)){
isTElement = true;
} else {
isTElement = false;
}
// 置空
lastContents = "";
}
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();
} catch (Exception e) {
}
}
//t元素也包含字符串
if(isTElement){
String value = lastContents.trim();
rowlist.add(curCol, value);
curCol++;
isTElement = false;
// v => 单元格的值,如果单元格是字符串则v标签的值为该字符串在SST中的索引
// 将单元格内容加入rowlist中,在这之前先去掉字符串前后的空白符
} else if ( "v".equals(name)) {
String value = lastContents.trim();
value = value.equals( "" )?" ":value;
//日期格式处理
if(dateFlag){
try{
Date date = HSSFDateUtil.getJavaDate(Double.valueOf(value));
SimpleDateFormat dateFormat = new SimpleDateFormat( "dd/MM/yyyy" );
value = dateFormat.format(date);
}catch(Exception e){
}
}
//数字类型处理
if(numberFlag){
try{
BigDecimal bd = new BigDecimal(value);
value = bd.setScale(3,BigDecimal.ROUND_UP).toString();
}catch(Exception e){
}
}
rowlist.add(curCol, value);
curCol++;
}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 {
//得到单元格内容的值
lastContents += new String(ch, start, length);
}
}
package com.x.okr.assemble.common.excel.reader;
import java.io.InputStream;
public class ExcelReaderUtil {
//excel2003扩展名
public static final String EXCEL03_EXTENSION = ".xls";
//excel2007扩展名
public static final String EXCEL07_EXTENSION = ".xlsx";
/**
* 读取Excel文件,可能是03也可能是07版本
* @param excel03
* @param excel07
* @param fileName
* @throws Exception
*/
public static void readExcel(IRowReader reader, String fileName, String fileKey, int startRow ) throws Exception{
// 处理excel2003文件
if (fileName.endsWith(EXCEL03_EXTENSION)){
Excel2003Reader excel03 = new Excel2003Reader();
excel03.setRowReader(reader, fileKey, startRow);
excel03.process(fileName);
// 处理excel2007文件
} else if (fileName.endsWith(EXCEL07_EXTENSION)){
Excel2007Reader excel07 = new Excel2007Reader();
excel07.setRowReader(reader, fileKey, startRow);
excel07.process(fileName);
} else {
throw new Exception( "文件格式错误,fileName的扩展名只能是xls或xlsx。" );
}
}
/**
* 读取Excel文件,可能是03也可能是07版本
* @param excel03
* @param excel07
* @param fileName
* @throws Exception
*/
public static void readExcel(IRowReader reader,String fileName, InputStream inputStream, String fileKey, int startRow ) throws Exception{
// 处理excel2003文件
if (fileName.endsWith( EXCEL03_EXTENSION )){
Excel2003Reader excel03 = new Excel2003Reader();
excel03.setRowReader(reader, fileKey, startRow);
excel03.process(inputStream);
// 处理excel2007文件
} else if (fileName.endsWith(EXCEL07_EXTENSION)){
Excel2007Reader excel07 = new Excel2007Reader();
excel07.setRowReader(reader, fileKey, startRow);
excel07.process(inputStream);
} else {
throw new Exception( "文件格式错误,fileName的扩展名只能是xls或xlsx。" );
}
}
}
\ No newline at end of file
package com.x.okr.assemble.common.excel.reader;
import java.util.List;
public interface IRowReader {
/**业务逻辑实现方法
* @param sheetIndex
* @param curRow
* @param rowlist
*/
public void getRows( int sheetIndex, int curRow, List<String> rowlist, String fileKey, int startRow );
}
package com.x.okr.assemble.common.excel.reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.hssf.eventusermodel.EventWorkbookBuilder.SheetRecordCollectingListener;
import org.apache.poi.hssf.eventusermodel.HSSFListener;
import org.apache.poi.hssf.record.BOFRecord;
import org.apache.poi.hssf.record.BlankRecord;
import org.apache.poi.hssf.record.BoolErrRecord;
import org.apache.poi.hssf.record.BoundSheetRecord;
import org.apache.poi.hssf.record.FormulaRecord;
import org.apache.poi.hssf.record.LabelSSTRecord;
import org.apache.poi.hssf.record.NumberRecord;
import org.apache.poi.hssf.record.RowRecord;
import org.apache.poi.hssf.record.SSTRecord;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
/**
* 基于POI HSSF的eventmodel 模型的时间解析方式
* 优点:解析数据相当快。
* 缺点:1.仅仅支持97~2003版本的excel,不支持2007版本的excel。
* 2.只能读Excel中一个Sheet页面。
*
* @Title:
* @Description: 实现TODO
* @Copyright:Copyright (c) 2011
* @Date:2012-6-14
* @author longgangbai
* @version 1.0
*/
public class UserModelEventListener implements HSSFListener {
private static Logger logger=LoggerFactory.getLogger(UserModelEventListener.class);
private SSTRecord sstrec;
/** Should we output the formula, or the value it has? */
@SuppressWarnings("unused")
private boolean outputFormulaValues = true;
/** For parsing Formulas */
@SuppressWarnings("unused")
private SheetRecordCollectingListener workbookBuildingListener;
//当前Sheet的内容
private List<Map<String,Object>> currentSheetDataMap=new ArrayList<Map<String,Object>>();
//列对应的字段
private static String[] trianListheadTitle=new String[]{"trainCode","firstStation","lastStation","startStation","arriveStation","startTime","arriveTime","fistLevelPrice","secondLevelPrice","km","useDate"};
//一行记录
private Map<String,Object> currentSheetRowDataMap=new HashMap<String,Object>();
private int curRowNum=0;
private int ignoreRowNum=1;
@SuppressWarnings("unused")
private int sheetNo=0;
@SuppressWarnings({ "static-access", "unused" })
@Override
public void processRecord(org.apache.poi.hssf.record.Record record) {
switch (record.getSid()) {
case BOFRecord.sid:
BOFRecord bof = (BOFRecord) record;
//顺序进入新的Workbook
if (bof.getType() == bof.TYPE_WORKBOOK) {
//logger.debug( "开始解析excel 文档....." );
//顺序进入新的Worksheet,因为Event API不会把Excel文件里的所有数据结构都关联起来,
//所以这儿一定要记录现在进入第几个sheet了。
} else if (bof.getType() == bof.TYPE_WORKSHEET) {
//读取新的一个Sheet页
//logger.debug( "开始解析sheet页面内容..." );
//System.out.println( "sheetNo="+sheetNo);
sheetNo++;
currentSheetDataMap=new ArrayList<Map<String,Object>>();
}
break;
//开始解析Sheet的信息,记录sheet,这儿会把所有的sheet都顺序打印出来,如果有多个sheet的话,可以顺序记入到一个List里
case BoundSheetRecord.sid:
BoundSheetRecord bsr = (BoundSheetRecord) record;
//System.out.println( "sheetName="+bsr.getSheetname());
//logger.debug( "New sheet named: " + bsr.getSheetname());
break;
//执行行记录事件
case RowRecord.sid:
RowRecord rowrec = (RowRecord) record;
//logger.debug( "记录开始, first column at "
// + rowrec.getFirstCol() + " last column at "
// + rowrec.getLastCol());
break;
// SSTRecords store a array of unique strings used in Excel.
case SSTRecord.sid:
sstrec = (SSTRecord) record;
for (int k = 0; k < sstrec.getNumUniqueStrings(); k++) {
//logger.debug( "String table value " + k + " = "
// + sstrec.getString(k));
}
break;
//发现数字类型的cell,因为数字和日期都是用这个格式,所以下面一定要判断是不是日期格式,另外默认的数字也会被视为日期格式,所以如果是数字的话,一定要明确指定格式!!!!!!!
case NumberRecord.sid:
NumberRecord nr = (NumberRecord) record;
//HSSFDateUtil.isInternalDateFormat(nr.getXFIndex()) 判断是否为时间列
int column=nr.getColumn();
if(column==5||column==6){
addDataAndrChangeRow(nr.getRow(),nr.getColumn(),getTime(nr.getValue()));
}else{
addDataAndrChangeRow(nr.getRow(),nr.getColumn(),(int)nr.getValue());
}
break;
//发现字符串类型,这儿要取字符串的值的话,跟据其index去字符串表里读取
case LabelSSTRecord.sid:
LabelSSTRecord lsr = (LabelSSTRecord)record;
addDataAndrChangeRow(lsr.getRow(),lsr.getColumn(), sstrec.getString(lsr.getSSTIndex()));
//logger.debug( "文字列:"+sstrec.getString(lsr.getSSTIndex())+", 行:"+lsr.getRow()+", 列:"+lsr.getColumn());
break;
case BoolErrRecord.sid: //解析boolean错误信息
BoolErrRecord ber = (BoolErrRecord)record;
if(ber.isBoolean()){
addDataAndrChangeRow(ber.getRow(),ber.getColumn(), ber.getBooleanValue());
//logger.debug( "Boolean:"+ber.getBooleanValue()+", 行:"+ber.getRow()+", 列:"+ber.getColumn());
}
if(ber.isError()){
//logger.debug( "Error:"+ber.getErrorValue()+", 行:"+ber.getRow()+", 列:"+ber.getColumn());
}
break;
//空白记录的信息
case BlankRecord.sid:
BlankRecord br = (BlankRecord)record;
addDataAndrChangeRow(br.getRow(),br.getColumn(), "" );
//logger.debug( "空。 行:"+br.getRow()+", 列:"+br.getColumn());
break;
case FormulaRecord.sid: //数式
FormulaRecord fr = (FormulaRecord)record;
addDataAndrChangeRow(fr.getRow(),fr.getColumn(), fr.getValue());
//logger.debug( "数字 。 行:"+fr.getRow()+", 列:"+fr.getColumn());
break;
}
}
/**
* HH:MM格式时间的数字转换方法</li>
* @param sNum
* @return
*/
private static String getTime(double daynum)
{
double totalSeconds=daynum*86400.0D;
//总的分钟数
int seconds =(int)totalSeconds/60;
//实际小时数
int hours =seconds/60;
int minutes = seconds-hours*60;
//剩余的实际分钟数
StringBuffer sb=new StringBuffer();
if(String.valueOf(hours).length()==1){
sb.append( "0"+hours);
}else{
sb.append(hours);
}
sb.append( ":" );
if(String.valueOf(minutes).length()==1){
sb.append( "0"+minutes);
}else{
sb.append(minutes);
}
return sb.toString();
}
/**
* 添加数据记录并检查是否换行
* @param row 实际当前行号
* @param col 实际记录当前列
* @param value 当前cell的值
*/
public void addDataAndrChangeRow(int row,int col,Object value){
//当前行如果大于实际行表示改行忽略,不记录
if(curRowNum!=row){
if(CollectionUtils.isEmpty(currentSheetDataMap)){
currentSheetDataMap=new ArrayList<Map<String,Object>>();
}
currentSheetDataMap.add(currentSheetRowDataMap);
//logger.debug( "行号:"+curRowNum +" 行内容:"+currentSheetRowDataMap.toString());
//logger.debug( "\n" );
currentSheetRowDataMap=new HashMap<String,Object>();
currentSheetRowDataMap.put(trianListheadTitle[col], value);
logger.debug(row+":"+col+" "+value+"\r" );
curRowNum=row;
}else{
currentSheetRowDataMap.put(trianListheadTitle[col], value);
//logger.debug(row+":"+col+" "+value+"\r" );
}
}
public List<Map<String, Object>> getCurrentSheetDataMap() {
return currentSheetDataMap;
}
public void setCurrentSheetDataMap(List<Map<String, Object>> currentSheetDataMap) {
this.currentSheetDataMap = currentSheetDataMap;
}
public Map<String, Object> getCurrentSheetRowDataMap() {
return currentSheetRowDataMap;
}
public void setCurrentSheetRowDataMap(Map<String, Object> currentSheetRowDataMap) {
this.currentSheetRowDataMap = currentSheetRowDataMap;
}
public int getCurRowNum() {
return curRowNum;
}
public void setCurRowNum(int curRowNum) {
this.curRowNum = curRowNum;
}
public int getIgnoreRowNum() {
return ignoreRowNum;
}
public void setIgnoreRowNum(int ignoreRowNum) {
this.ignoreRowNum = ignoreRowNum;
}
}
package com.x.okr.assemble.common.excel.writer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* 抽象excel2007读入器,先构建.xlsx一张模板,改写模板中的sheet.xml,使用这种方法
* 写入.xlsx文件,不需要太大的内存
*
*/
public abstract class AbstractExcel2007Writer {
private SpreadsheetWriter sw;
/**
* 写入电子表格的主要流程
* @param fileName
* @throws Exception
*/
@SuppressWarnings("resource")
public void process( String fileName ) throws Exception{
// 建立工作簿和电子表格对象
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet( "sheet1" );
// 持有电子表格数据的xml文件名 例如 /xl/worksheets/sheet1.xml
String sheetRef = sheet.getPackagePart().getPartName().getName();
// 保存模板
FileOutputStream os = new FileOutputStream( "template.xlsx" );
wb.write(os);
os.close();
// 生成xml文件
File tmp = File.createTempFile( "sheet", ".xml" );
Writer fw = new FileWriter(tmp);
sw = new SpreadsheetWriter(fw);
generate();
fw.close();
// 使用产生的数据替换模板
File templateFile = new File( "template.xlsx" );
FileOutputStream out = new FileOutputStream(fileName);
substitute(templateFile, tmp, sheetRef.substring(1), out);
out.close();
//删除文件之前调用一下垃圾回收器,否则无法删除模板文件
System.gc();
// 删除临时模板文件
if (templateFile.isFile()&&templateFile.exists()){
templateFile.delete();
}
}
/**
* 写入电子表格的主要流程
* @param fileName
* @throws Exception
*/
@SuppressWarnings("resource")
public void process( OutputStream out ) throws Exception{
// 建立工作簿和电子表格对象
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet( "sheet1" );
// 持有电子表格数据的xml文件名 例如 /xl/worksheets/sheet1.xml
String sheetRef = sheet.getPackagePart().getPartName().getName();
// 保存模板
FileOutputStream os = new FileOutputStream( "template.xlsx" );
wb.write(os);
os.close();
// 生成xml文件
File tmp = File.createTempFile( "sheet", ".xml" );
Writer fw = new FileWriter(tmp);
sw = new SpreadsheetWriter(fw);
generate();
fw.close();
// 使用产生的数据替换模板
File templateFile = new File( "template.xlsx" );
substitute(templateFile, tmp, sheetRef.substring(1), out);
out.close();
//删除文件之前调用一下垃圾回收器,否则无法删除模板文件
System.gc();
// 删除临时模板文件
if (templateFile.isFile()&&templateFile.exists()){
templateFile.delete();
}
}
/**
* 类使用者应该使用此方法进行写操作
* @throws Exception
*/
public abstract void generate() throws Exception;
public void beginSheet() throws IOException {
sw.beginSheet();
}
public void insertRow(int rowNum) throws IOException {
sw.insertRow(rowNum);
}
public void createCell(int columnIndex, String value) throws IOException {
sw.createCell(columnIndex, value, -1);
}
public void createCell(int columnIndex, double value) throws IOException {
sw.createCell(columnIndex, value, -1);
}
public void endRow() throws IOException {
sw.endRow();
}
public void endSheet() throws IOException {
sw.endSheet();
}
/**
*
* @param zipfile the template file
* @param tmpfile the XML file with the sheet data
* @param entry the name of the sheet entry to substitute, e.g. xl/worksheets/sheet1.xml
* @param out the stream to write the result to
*/
@SuppressWarnings("resource")
private static void substitute(File zipfile, File tmpfile, String entry,
OutputStream out) throws IOException {
ZipFile zip = new ZipFile(zipfile);
ZipOutputStream zos = new ZipOutputStream(out);
@SuppressWarnings( "unchecked" )
Enumeration<ZipEntry> en = (Enumeration<ZipEntry>) zip.entries();
while (en.hasMoreElements()) {
ZipEntry ze = en.nextElement();
if (!ze.getName().equals(entry)) {
zos.putNextEntry(new ZipEntry(ze.getName()));
InputStream is = zip.getInputStream(ze);
copyStream(is, zos);
is.close();
}
}
zos.putNextEntry(new ZipEntry(entry));
InputStream is = new FileInputStream(tmpfile);
copyStream(is, zos);
is.close();
zos.close();
}
private static void copyStream(InputStream in, OutputStream out)
throws IOException {
byte[] chunk = new byte[1024];
int count;
while ((count = in.read(chunk)) >= 0) {
out.write(chunk, 0, count);
}
}
/**
* 在写入器中写入电子表格
*
*/
public static class SpreadsheetWriter {
private final Writer _out;
private int _rownum;
private static String LINE_SEPARATOR = System.getProperty( "line.separator" );
public SpreadsheetWriter(Writer out) {
_out = out;
}
public void beginSheet() throws IOException {
_out.write( "<?xml version=\"1.0\" encoding=\"GB2312\"?>"
+ "<worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">" );
_out.write( "<sheetData>"+LINE_SEPARATOR);
}
public void endSheet() throws IOException {
_out.write( "</sheetData>" );
_out.write( "</worksheet>" );
}
/**
* 插入新行
*
* @param rownum 以0开始
*/
public void insertRow(int rownum) throws IOException {
_out.write( "<row r=\"" + (rownum + 1) + "\">"+LINE_SEPARATOR);
this._rownum = rownum;
}
/**
* 插入行结束标志
*/
public void endRow() throws IOException {
_out.write( "</row>"+LINE_SEPARATOR);
}
/**
* 插入新列
* @param columnIndex
* @param value
* @param styleIndex
* @throws IOException
*/
public void createCell(int columnIndex, String value, int styleIndex)
throws IOException {
String ref = new CellReference(_rownum, columnIndex)
.formatAsString();
_out.write( "<c r=\"" + ref + "\" t=\"inlineStr\"" );
if (styleIndex != -1)
_out.write( " s=\"" + styleIndex + "\"" );
_out.write( ">" );
_out.write( "<is><t>"+XMLEncoder.encode(value)+"</t></is>" );
_out.write( "</c>" );
}
public void createCell(int columnIndex, String value)
throws IOException {
createCell(columnIndex, value, -1);
}
public void createCell(int columnIndex, double value, int styleIndex)
throws IOException {
String ref = new CellReference(_rownum, columnIndex)
.formatAsString();
_out.write( "<c r=\"" + ref + "\" t=\"n\"" );
if (styleIndex != -1)
_out.write( " s=\"" + styleIndex + "\"" );
_out.write( ">" );
_out.write( "<v>" + value + "</v>" );
_out.write( "</c>" );
}
public void createCell(int columnIndex, double value)
throws IOException {
createCell(columnIndex, value, -1);
}
public void createCell(int columnIndex, Calendar value, int styleIndex)
throws IOException {
createCell(columnIndex, DateUtil.getExcelDate(value, false),
styleIndex);
}
}
}
\ No newline at end of file
package com.x.okr.assemble.common.excel.writer;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
public class Excel2003Writer {
/**
* @param args
*/
public static void main(String[] args) {
try{
//System.out.println( "开始写入excel2003...." );
writeExcel( "tes2003.xls" );
//System.out.println( "写完xcel2003" );
} catch (IOException e) {
}
}
/**
* 写入excel并填充内容,一个sheet只能写65536行以下,超出会报异常,写入时建议使用AbstractExcel2007Writer
* @param fileName
* @throws IOException
*/
@SuppressWarnings("resource")
public static void writeExcel(String fileName) throws IOException{
// 创建excel2003对象
Workbook wb = new HSSFWorkbook();
// 设置文件放置路径和文件名
FileOutputStream fileOut = new FileOutputStream(fileName);
// 创建新的表单
Sheet sheet = wb.createSheet( "newsheet" );
// 创建新行
for(int i=0;i<20000;i++){
Row row = sheet.createRow(i);
// 创建单元格
Cell cell = row.createCell(0);
// 设置单元格值
cell.setCellValue(1);
row.createCell(1).setCellValue(1+i);
row.createCell(2).setCellValue(true);
row.createCell(3).setCellValue(0.43d);
row.createCell(4).setCellValue('d');
row.createCell(5).setCellValue( "" );
row.createCell(6).setCellValue( "第七列"+i);
row.createCell(7).setCellValue( "第八列"+i);
}
wb.write(fileOut);
fileOut.close();
}
}
package com.x.okr.assemble.common.excel.writer;
public class Excel2007WriterImpl extends AbstractExcel2007Writer{
/*
* 可根据需求重写此方法,对于单元格的小数或者日期格式,会出现精度问题或者日期格式转化问题,建议使用字符串插入方法
* @see com.excel.ver2.AbstractExcel2007Writer#generate()
*/
@Override
public void generate()throws Exception {
//电子表格开始
beginSheet();
for (int rownum = 0; rownum < 100; rownum++) {
//插入新行
insertRow(rownum);
//建立新单元格,索引值从0开始,表示第一列
createCell(0, "中国<" + rownum + "!" );
createCell(1, 34343.123456789);
createCell(2, "23.67%" );
createCell(3, "12:12:23" );
createCell(4, "2010-10-11 12:12:23" );
createCell(5, "true" );
createCell(6, "false" );
//结束行
endRow();
}
//电子表格结束
endSheet();
}
}
package com.x.okr.assemble.common.excel.writer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.x.base.core.project.gson.XGsonBuilder;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.okr.assemble.common.date.DateOperation;
import com.x.okr.assemble.control.jaxrs.statistic.BaseAction.WoOkrStatisticReportContent;
import com.x.okr.assemble.control.jaxrs.statistic.BaseAction.WoOkrStatisticReportContentCenter;
import com.x.okr.assemble.control.schedule.entity.WorkReportProcessOpinionEntity;
import com.x.okr.assemble.control.service.OkrWorkDetailInfoService;
import com.x.okr.entity.OkrWorkDetailInfo;
public class WorkReportContentExportExcelWriter {
private static Logger logger = LoggerFactory.getLogger(WorkReportContentExportExcelWriter.class);
private OkrWorkDetailInfoService okrWorkDetailInfoService = new OkrWorkDetailInfoService();
private Integer currentRowNumber = 0;
/**
* 写入excel并填充内容,一个sheet只能写65536行以下,超出会报异常,写入时建议大量数据时使用AbstractExcel2007Writer
*
* @param fileOut
* @throws IOException
*/
public String writeExcel(List<WoOkrStatisticReportContentCenter> exportDataList) {
String centerTitle = null;
Integer workCountInCenter = 0;
Workbook wb = new HSSFWorkbook();// 创建excel2003对象
Sheet sheet = wb.createSheet("工作汇报情况统计表");// 创建新的工作表
Row row = null;
Cell cell = null;
// 表头//////////////////////////////////////////////////////////////
row = sheet.createRow(currentRowNumber);
row.createCell(0).setCellValue("工作类别");
row.createCell(1).setCellValue("重点事项");// 中心工作内容
row.createCell(2).setCellValue("责任组织");
row.createCell(3).setCellValue("事项分解及描述");// 具体工作内容
row.createCell(4).setCellValue("工作汇报情况");
row.createCell(5).setCellValue("工作汇报形式");
row.createCell(6).setCellValue("具体行动举措");
row.createCell(7).setCellValue("预期里程碑/阶段性结果标志");
row.createCell(8).setCellValue("截止目前完成情况");
row.createCell(9).setCellValue("下一步工作要点及需求");
row.createCell(10).setCellValue("督办评价");
row.createCell(11).setCellValue("领导评价");
currentRowNumber++;// 表头占一行
if (exportDataList != null && !exportDataList.isEmpty()) {
for (WoOkrStatisticReportContentCenter contentForCenter : exportDataList) {
if (contentForCenter.getContents() != null && !contentForCenter.getContents().isEmpty()) {
// 中心工作中所有工作的数量
workCountInCenter = contentForCenter.getContents().size();
centerTitle = contentForCenter.getTitle();
logger.info(">>>>中心工作[" + centerTitle + "]:" + currentRowNumber + " --> "
+ (currentRowNumber + workCountInCenter - 1));
sheet.addMergedRegion(
new CellRangeAddress(currentRowNumber, (currentRowNumber + workCountInCenter - 1), 0, 0));
sheet.addMergedRegion(
new CellRangeAddress(currentRowNumber, (currentRowNumber + workCountInCenter - 1), 1, 1));
for (WoOkrStatisticReportContent wrapOutOkrStatisticReportContent : contentForCenter
.getContents()) {
row = sheet.createRow(currentRowNumber);
row.createCell(0).setCellValue(wrapOutOkrStatisticReportContent.getWorkType());// "工作类别"
row.createCell(1).setCellValue(centerTitle);// "中心工作事项"
composeWorkToExcel(sheet, row, wrapOutOkrStatisticReportContent);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////// 单元格样式设计 //////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
sheet.setDefaultColumnWidth(20);
sheet.setDefaultRowHeightInPoints(20);
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER); // 居中
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 居中
sheet.setColumnWidth(0, 10 * 256);
sheet.setColumnWidth(1, 50 * 256);
sheet.setColumnWidth(2, 20 * 256);
sheet.setColumnWidth(3, 50 * 256);
sheet.setColumnWidth(4, 10 * 256);
sheet.setColumnWidth(5, 10 * 256);
sheet.setColumnWidth(6, 50 * 256);
sheet.setColumnWidth(7, 50 * 256);
sheet.setColumnWidth(8, 50 * 256);
sheet.setColumnWidth(9, 50 * 256);
sheet.setColumnWidth(10, 50 * 256);
sheet.setColumnWidth(11, 50 * 256);
Iterator<Row> rowIterator = sheet.rowIterator();
Iterator<Cell> cellIterator = null;
while (rowIterator.hasNext()) {
row = rowIterator.next();
row.setHeight((short) (40 * 20));
cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
cell = cellIterator.next();
cell.setCellStyle(cellStyle);
}
}
}
try {
String timeFlag = new DateOperation().getNowTimeChar();
File dir = new File("download/temp");
if (!dir.exists()) {
dir.mkdirs();
}
FileOutputStream fos = new FileOutputStream("download/temp/export_" + timeFlag + ".xls");
wb.write(fos);
fos.close();
wb.close();
return timeFlag;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "none";
}
private void composeWorkToExcel(Sheet sheet, Row row,
WoOkrStatisticReportContent wrapOutOkrStatisticReportContent) {
if (wrapOutOkrStatisticReportContent == null) {
return;
}
List<WorkReportProcessOpinionEntity> opinions = null;
OkrWorkDetailInfo detail = null;
String opinionContent = null;
Gson gson = XGsonBuilder.instance();
String opinion = null;
row.createCell(2).setCellValue(wrapOutOkrStatisticReportContent.getResponsibilityUnitName());// "责任组织"
row.createCell(5).setCellValue(wrapOutOkrStatisticReportContent.getCycleType());// "工作汇报形式"
row.createCell(8).setCellValue(wrapOutOkrStatisticReportContent.getProgressDescription());// "截止目前完成情况"
row.createCell(9).setCellValue(wrapOutOkrStatisticReportContent.getWorkPlan());// "下一步工作要点及需求"
row.createCell(10).setCellValue(wrapOutOkrStatisticReportContent.getAdminSuperviseInfo());// "督办评价"
try {
detail = okrWorkDetailInfoService.get(wrapOutOkrStatisticReportContent.getWorkId());
} catch (Exception e) {
logger.warn("system get work detail with work id got an exception.");
logger.error(e);
}
if (detail != null) {
row.createCell(6).setCellValue(detail.getProgressAction());// "具体行动举措"
row.createCell(7).setCellValue(detail.getLandmarkDescription());// "预期里程碑/阶段性结果标志"
row.createCell(3).setCellValue(detail.getWorkDetail());// "事项分解及描述"
}
row.createCell(4).setCellValue(wrapOutOkrStatisticReportContent.getReportStatus());// "工作汇报情况"
opinionContent = wrapOutOkrStatisticReportContent.getOpinion();
if (opinionContent != null) {
opinion = "";
opinions = gson.fromJson(opinionContent, new TypeToken<List<WorkReportProcessOpinionEntity>>() {
}.getType());
if (opinions != null) {
for (WorkReportProcessOpinionEntity workReportProcessOpinionEntity : opinions) {
opinion = opinion + workReportProcessOpinionEntity.getProcessorName() + ":"
+ workReportProcessOpinionEntity.getOpinion() + "\n";
}
row.createCell(11).setCellValue(opinion);// "领导评价"
} else {
row.createCell(11).setCellValue("");// "领导评价"
}
}
currentRowNumber++;
if (wrapOutOkrStatisticReportContent.getSubWork() != null
&& !wrapOutOkrStatisticReportContent.getSubWork().isEmpty()) {
for (WoOkrStatisticReportContent subWorks : wrapOutOkrStatisticReportContent.getSubWork()) {
row = sheet.createRow(currentRowNumber);
composeWorkToExcel(sheet, row, subWorks);
}
}
}
}
package com.x.okr.assemble.common.excel.writer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import com.x.okr.assemble.common.date.DateOperation;
import com.x.okr.assemble.control.jaxrs.statistic.BaseAction.WoOkrStatisticReportStatusEntity;
import com.x.okr.assemble.control.jaxrs.statistic.BaseAction.WoOkrStatisticReportStatusHeader;
import com.x.okr.assemble.control.jaxrs.statistic.BaseAction.WoOkrStatisticReportStatusTable;
public class WorkReportStatusExportExcelWriter {
private Integer currentRowNumber = 0;
/**
* 写入excel并填充内容,一个sheet只能写65536行以下,超出会报异常,写入时建议大量数据时使用AbstractExcel2007Writer
* @param fileOut
* @throws IOException
*/
public String writeExcel( WoOkrStatisticReportStatusTable wrapOutOkrStatisticReportStatusTable ) {
String unitName = null;
String centerTitle = null;
Integer centerCount = 0;
Integer workCount = 0;
List<WoOkrStatisticReportStatusHeader> headers = null;
List<WoOkrStatisticReportStatusEntity> contents = null;
Workbook wb = new HSSFWorkbook();// 创建excel2003对象
Sheet sheet = wb.createSheet( "工作汇报情况统计表" );// 创建新的工作表
Row row = null;
Cell cell = null;
if( wrapOutOkrStatisticReportStatusTable != null ){
headers = wrapOutOkrStatisticReportStatusTable.getHeader();
contents = wrapOutOkrStatisticReportStatusTable.getContent();
//表头//////////////////////////////////////////////////////////////
row = sheet.createRow( currentRowNumber );
if( headers != null && !headers.isEmpty() ){
for( int i = 0; i<headers.size(); i++ ){
row.createCell( i ).setCellValue( headers.get( i ).getTitle() );//具体工作内容
}
}
currentRowNumber++;//表头占一行
if( contents != null && !contents.isEmpty() ){
for( WoOkrStatisticReportStatusEntity unitEntity : contents ){
unitName = unitEntity.getTitle();
centerCount = unitEntity.getRowCount();
//logger.info( "|------------"+ currentRowNumber + " --> " + ( currentRowNumber + centerCount -1 )+ ": 组织["+ unitName +"]" );
sheet.addMergedRegion( new CellRangeAddress( currentRowNumber, ( currentRowNumber + centerCount -1 ), 0, 0 ));
for( WoOkrStatisticReportStatusEntity centerEntity : unitEntity.getArray() ){
centerTitle = centerEntity.getTitle();
workCount = centerEntity.getRowCount();
//logger.info( "--|------" + currentRowNumber + " --> " + ( currentRowNumber + workCount -1 ) + ": 中心工作["+ centerTitle +"]");
sheet.addMergedRegion( new CellRangeAddress( currentRowNumber, ( currentRowNumber + workCount -1 ), 1, 1 ));
for( WoOkrStatisticReportStatusEntity workEntity : centerEntity.getArray() ){
row = sheet.createRow( currentRowNumber );
row.createCell(0).setCellValue( unitName );
row.createCell(1).setCellValue( centerTitle );
//logger.info( "----|--"+ currentRowNumber +": 具体工作["+ workEntity.getTitle() +"]" );
row.createCell(2).setCellValue( workEntity.getTitle() );
if( workEntity.getFields() != null && !workEntity.getFields().isEmpty() ){
for( int i = 0; i<workEntity.getFields().size(); i++ ){
if( workEntity.getFields().get( i ).getReportStatus() == 0 ){
row.createCell( i+3 ).setCellValue("无内容");
}else if( workEntity.getFields().get( i ).getReportStatus() == 1 ){
row.createCell( i+3 ).setCellValue("有内容");
}else if( workEntity.getFields().get( i ).getReportStatus() == -1 ){
row.createCell( i+3 ).setCellValue("'--");
}else{
row.createCell( i+3 ).setCellValue("'--");
}
}
}
currentRowNumber++;
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////// 单元格样式设计 //////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
sheet.setDefaultColumnWidth( 20 );
sheet.setDefaultRowHeightInPoints( 20 );
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setWrapText(true);
cellStyle.setAlignment( HorizontalAlignment.CENTER ); // 居中
cellStyle.setVerticalAlignment( VerticalAlignment.CENTER ); // 居中
if( headers != null && !headers.isEmpty() ){
for( int i = 0; i<headers.size(); i++ ){
if( i == 0 ){
sheet.setColumnWidth( 0, 10*256 );
}else if( i == 1 ){
sheet.setColumnWidth( 1, 50*256 );
}else if( i == 2 ){
sheet.setColumnWidth( 2, 50*256 );
}else{
sheet.setColumnWidth( i, 10*256 );
}
}
}
Iterator<Row> rowIterator = sheet.rowIterator();
Iterator<Cell> cellIterator = null;
while( rowIterator.hasNext() ){
row = rowIterator.next();
row.setHeight( (short) ( 40 * 20 ) );
cellIterator = row.cellIterator();
while( cellIterator.hasNext() ){
cell = cellIterator.next();
cell.setCellStyle( cellStyle );
}
}
}
try {
String timeFlag = new DateOperation().getNowTimeChar();
File dir = new File("download/temp");
if( !dir.exists() ){
dir.mkdirs();
}
FileOutputStream fos = new FileOutputStream("download/temp/export_"+timeFlag+".xls");
wb.write( fos );
fos.close();
wb.close();
return timeFlag;
} catch (IOException e) {
e.printStackTrace();
}
}
return "none";
}
}
package com.x.okr.assemble.common.excel.writer;
public class XMLEncoder {
private static final String[] xmlCode = new String[256];
static {
// Special characters
xmlCode['\''] = "'";
xmlCode['\"'] = "\""; // double quote
xmlCode['&'] = "&"; // ampersand
xmlCode['<'] = "<"; // lower than
xmlCode['>'] = ">"; // greater than
}
/**
* <p>
* Encode the given text into xml.
* </p>
*
* @param string the text to encode
* @return the encoded string
*/
public static String encode(String string) {
if (string == null) return "";
int n = string.length();
char character;
String xmlchar;
StringBuffer buffer = new StringBuffer();
// loop over all the characters of the String.
for (int i = 0; i < n; i++) {
character = string.charAt(i);
// the xmlcode of these characters are added to a StringBuffer one by one
try {
xmlchar = xmlCode[character];
if (xmlchar == null) {
buffer.append(character);
} else {
buffer.append(xmlCode[character]);
}
} catch (ArrayIndexOutOfBoundsException aioobe) {
buffer.append(character);
}
}
return buffer.toString();
}
}
package com.x.okr.assemble.control;
import com.x.base.core.container.EntityManagerContainer;
public abstract class AbstractFactory {
private Business business;
public AbstractFactory( Business business ) throws Exception {
try {
if ( null == business ) {
throw new Exception( "business can not be null. " );
}
this.business = business;
} catch ( Exception e ) {
throw new Exception( "can not instantiating factory." );
}
}
public EntityManagerContainer entityManagerContainer() throws Exception {
return this.business.entityManagerContainer();
}
}
\ No newline at end of file
package com.x.okr.assemble.control;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import com.x.base.core.project.Context;
@WebListener
public class ApplicationServletContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
try {
ThisApplication.context = Context.concrete(servletContextEvent);
ThisApplication.init();
ThisApplication.context().regist();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
try {
ThisApplication.destroy();
ThisApplication.context.destrory(servletContextEvent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
\ No newline at end of file
package com.x.okr.assemble.control;
import com.x.base.core.container.EntityManagerContainer;
import com.x.okr.assemble.control.factory.OkrAttachmentFileInfoFactory;
import com.x.okr.assemble.control.factory.OkrCenterWorkInfoFactory;
import com.x.okr.assemble.control.factory.OkrConfigSecretaryFactory;
import com.x.okr.assemble.control.factory.OkrConfigSystemFactory;
import com.x.okr.assemble.control.factory.OkrConfigWorkLevelFactory;
import com.x.okr.assemble.control.factory.OkrConfigWorkTypeFactory;
import com.x.okr.assemble.control.factory.OkrErrorSystemIdentityInfoFactory;
import com.x.okr.assemble.control.factory.OkrStatisticReportContentFactory;
import com.x.okr.assemble.control.factory.OkrStatisticReportStatusFactory;
import com.x.okr.assemble.control.factory.OkrTaskFactory;
import com.x.okr.assemble.control.factory.OkrTaskHandledFactory;
import com.x.okr.assemble.control.factory.OkrUserInfoFactory;
import com.x.okr.assemble.control.factory.OkrWorkAppraiseInfoFactory;
import com.x.okr.assemble.control.factory.OkrWorkAuthorizeRecordFactory;
import com.x.okr.assemble.control.factory.OkrWorkBaseInfoFactory;
import com.x.okr.assemble.control.factory.OkrWorkChatFactory;
import com.x.okr.assemble.control.factory.OkrWorkDetailInfoFactory;
import com.x.okr.assemble.control.factory.OkrWorkDynamicsFactory;
import com.x.okr.assemble.control.factory.OkrWorkPersonFactory;
import com.x.okr.assemble.control.factory.OkrWorkPersonSearchFactory;
import com.x.okr.assemble.control.factory.OkrWorkReportBaseInfoFactory;
import com.x.okr.assemble.control.factory.OkrWorkReportDetailInfoFactory;
import com.x.okr.assemble.control.factory.OkrWorkReportPersonLinkFactory;
import com.x.okr.assemble.control.factory.OkrWorkReportProcessLogFactory;
import com.x.organization.core.express.Organization;
public class Business {
private EntityManagerContainer emc;
public Business(EntityManagerContainer emc) throws Exception {
this.emc = emc;
}
public EntityManagerContainer entityManagerContainer() {
return this.emc;
}
//人员组织业务处理类
private Organization organization;
private OkrStatisticReportContentFactory okrStatisticReportContentFactory;
private OkrStatisticReportStatusFactory okrStatisticReportStatusFactory;
private OkrAttachmentFileInfoFactory okrAttachmentFileInfoFactory;
private OkrCenterWorkInfoFactory okrCenterWorkInfoFactory;
private OkrConfigSecretaryFactory okrConfigSecretaryFactory;
private OkrConfigSystemFactory okrConfigSystemFactory;
private OkrConfigWorkLevelFactory okrConfigWorkLevelFactory;
private OkrConfigWorkTypeFactory okrConfigWorkTypeFactory;
private OkrTaskFactory okrTaskFactory;
private OkrTaskHandledFactory okrTaskHandledFactory;
private OkrWorkAuthorizeRecordFactory okrWorkAuthorizeRecordFactory;
private OkrWorkBaseInfoFactory okrWorkBaseInfoFactory;
private OkrWorkAppraiseInfoFactory okrWorkAppraiseInfoFactory;
private OkrWorkDetailInfoFactory okrWorkDetailInfoFactory;
private OkrWorkDynamicsFactory okrWorkDynamicsFactory;
private OkrWorkPersonFactory okrWorkPersonFactory;
private OkrWorkPersonSearchFactory okrWorkPersonSearchFactory;
private OkrWorkReportBaseInfoFactory okrWorkReportBaseInfoFactory;
private OkrWorkReportDetailInfoFactory okrWorkReportDetailInfoFactory;
private OkrWorkReportPersonLinkFactory okrWorkReportPersonLinkFactory;
private OkrWorkReportProcessLogFactory okrWorkReportProcessLogFactory;
private OkrErrorSystemIdentityInfoFactory okrErrorSystemIdentityInfoFactory;
private OkrUserInfoFactory okrUserInfoFactory;
private OkrWorkChatFactory okrWorkChatFactory;
public Organization organization() throws Exception {
if (null == this.organization) {
this.organization = new Organization(ThisApplication.context());
}
return organization;
}
public OkrWorkAppraiseInfoFactory okrWorkAppraiseInfoFactory() throws Exception {
if (null == this.okrWorkAppraiseInfoFactory) {
this.okrWorkAppraiseInfoFactory = new OkrWorkAppraiseInfoFactory( this );
}
return okrWorkAppraiseInfoFactory;
}
public OkrErrorSystemIdentityInfoFactory okrErrorSystemIdentityInfoFactory() throws Exception {
if (null == this.okrErrorSystemIdentityInfoFactory) {
this.okrErrorSystemIdentityInfoFactory = new OkrErrorSystemIdentityInfoFactory( this );
}
return okrErrorSystemIdentityInfoFactory;
}
public OkrStatisticReportStatusFactory okrStatisticReportStatusFactory() throws Exception {
if (null == this.okrStatisticReportStatusFactory) {
this.okrStatisticReportStatusFactory = new OkrStatisticReportStatusFactory( this );
}
return okrStatisticReportStatusFactory;
}
public OkrUserInfoFactory okrUserInfoFactory() throws Exception {
if (null == this.okrUserInfoFactory) {
this.okrUserInfoFactory = new OkrUserInfoFactory( this );
}
return okrUserInfoFactory;
}
public OkrStatisticReportContentFactory okrStatisticReportContentFactory() throws Exception {
if (null == this.okrStatisticReportContentFactory) {
this.okrStatisticReportContentFactory = new OkrStatisticReportContentFactory( this );
}
return okrStatisticReportContentFactory;
}
public OkrWorkChatFactory okrWorkChatFactory() throws Exception {
if (null == this.okrWorkChatFactory) {
this.okrWorkChatFactory = new OkrWorkChatFactory( this );
}
return okrWorkChatFactory;
}
public OkrAttachmentFileInfoFactory okrAttachmentFileInfoFactory() throws Exception {
if (null == this.okrAttachmentFileInfoFactory) {
this.okrAttachmentFileInfoFactory = new OkrAttachmentFileInfoFactory( this );
}
return okrAttachmentFileInfoFactory;
}
public OkrCenterWorkInfoFactory okrCenterWorkInfoFactory() throws Exception {
if (null == this.okrCenterWorkInfoFactory) {
this.okrCenterWorkInfoFactory = new OkrCenterWorkInfoFactory( this );
}
return okrCenterWorkInfoFactory;
}
public OkrConfigWorkLevelFactory okrConfigWorkLevelFactory() throws Exception {
if (null == this.okrConfigWorkLevelFactory) {
this.okrConfigWorkLevelFactory = new OkrConfigWorkLevelFactory( this );
}
return okrConfigWorkLevelFactory;
}
public OkrConfigSecretaryFactory okrConfigSecretaryFactory() throws Exception {
if (null == this.okrConfigSecretaryFactory) {
this.okrConfigSecretaryFactory = new OkrConfigSecretaryFactory( this );
}
return okrConfigSecretaryFactory;
}
public OkrConfigSystemFactory okrConfigSystemFactory() throws Exception {
if (null == this.okrConfigSystemFactory) {
this.okrConfigSystemFactory = new OkrConfigSystemFactory( this );
}
return okrConfigSystemFactory;
}
public OkrConfigWorkTypeFactory okrConfigWorkTypeFactory() throws Exception {
if (null == this.okrConfigWorkTypeFactory) {
this.okrConfigWorkTypeFactory = new OkrConfigWorkTypeFactory( this );
}
return okrConfigWorkTypeFactory;
}
public OkrTaskFactory okrTaskFactory() throws Exception {
if (null == this.okrTaskFactory) {
this.okrTaskFactory = new OkrTaskFactory( this );
}
return okrTaskFactory;
}
public OkrTaskHandledFactory okrTaskHandledFactory() throws Exception {
if (null == this.okrTaskHandledFactory) {
this.okrTaskHandledFactory = new OkrTaskHandledFactory( this );
}
return okrTaskHandledFactory;
}
public OkrWorkAuthorizeRecordFactory okrWorkAuthorizeRecordFactory() throws Exception {
if (null == this.okrWorkAuthorizeRecordFactory) {
this.okrWorkAuthorizeRecordFactory = new OkrWorkAuthorizeRecordFactory( this );
}
return okrWorkAuthorizeRecordFactory;
}
public OkrWorkBaseInfoFactory okrWorkBaseInfoFactory() throws Exception {
if (null == this.okrWorkBaseInfoFactory) {
this.okrWorkBaseInfoFactory = new OkrWorkBaseInfoFactory( this );
}
return okrWorkBaseInfoFactory;
}
public OkrWorkDetailInfoFactory okrWorkDetailInfoFactory() throws Exception {
if (null == this.okrWorkDetailInfoFactory) {
this.okrWorkDetailInfoFactory = new OkrWorkDetailInfoFactory( this );
}
return okrWorkDetailInfoFactory;
}
public OkrWorkDynamicsFactory okrWorkDynamicsFactory() throws Exception {
if (null == this.okrWorkDynamicsFactory) {
this.okrWorkDynamicsFactory = new OkrWorkDynamicsFactory( this );
}
return okrWorkDynamicsFactory;
}
public OkrWorkPersonFactory okrWorkPersonFactory() throws Exception {
if (null == this.okrWorkPersonFactory) {
this.okrWorkPersonFactory = new OkrWorkPersonFactory( this );
}
return okrWorkPersonFactory;
}
public OkrWorkPersonSearchFactory okrWorkPersonSearchFactory() throws Exception {
if (null == this.okrWorkPersonSearchFactory) {
this.okrWorkPersonSearchFactory = new OkrWorkPersonSearchFactory( this );
}
return okrWorkPersonSearchFactory;
}
public OkrWorkReportBaseInfoFactory okrWorkReportBaseInfoFactory() throws Exception {
if (null == this.okrWorkReportBaseInfoFactory) {
this.okrWorkReportBaseInfoFactory = new OkrWorkReportBaseInfoFactory( this );
}
return okrWorkReportBaseInfoFactory;
}
public OkrWorkReportDetailInfoFactory okrWorkReportDetailInfoFactory() throws Exception {
if (null == this.okrWorkReportDetailInfoFactory) {
this.okrWorkReportDetailInfoFactory = new OkrWorkReportDetailInfoFactory( this );
}
return okrWorkReportDetailInfoFactory;
}
public OkrWorkReportPersonLinkFactory okrWorkReportPersonLinkFactory() throws Exception {
if (null == this.okrWorkReportPersonLinkFactory) {
this.okrWorkReportPersonLinkFactory = new OkrWorkReportPersonLinkFactory( this );
}
return okrWorkReportPersonLinkFactory;
}
public OkrWorkReportProcessLogFactory okrWorkReportProcessLogFactory() throws Exception {
if (null == this.okrWorkReportProcessLogFactory) {
this.okrWorkReportProcessLogFactory = new OkrWorkReportProcessLogFactory( this );
}
return okrWorkReportProcessLogFactory;
}
}
package com.x.okr.assemble.control;
import java.io.Serializable;
import com.x.base.core.project.gson.GsonPropertyObject;
public class OkrUserCache extends GsonPropertyObject implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 操作用户的姓名
*/
private String operationUserName = null;
/**
* 操作用户的组织名称
*/
private String operationUserUnitName = null;
/**
* 操作用户的顶层组织名称
*/
private String operationUserTopUnitName = null;
/**
* 代理用户的身份名称
*/
private String loginIdentityName = null;
/**
* 代理用户的姓名
*/
private String loginUserName = null;
/**
* 代理用户的组织名称
*/
private String loginUserUnitName = null;
/**
* 代理用户的顶层组织名称
*/
private String loginUserTopUnitName = null;
private boolean okrManager = false; //系统管理员
public boolean isOkrManager() {
return okrManager;
}
public void setOkrManager(boolean okrManager) {
this.okrManager = okrManager;
}
public String getOperationUserName() {
return operationUserName;
}
public void setOperationUserName(String operationUserName) {
this.operationUserName = operationUserName;
}
public String getOperationUserUnitName() {
return operationUserUnitName;
}
public void setOperationUserUnitName(String operationUserUnitName) {
this.operationUserUnitName = operationUserUnitName;
}
public String getOperationUserTopUnitName() {
return operationUserTopUnitName;
}
public void setOperationUserTopUnitName(String operationUserTopUnitName) {
this.operationUserTopUnitName = operationUserTopUnitName;
}
public String getLoginIdentityName() {
return loginIdentityName;
}
public void setLoginIdentityName(String loginIdentityName) {
this.loginIdentityName = loginIdentityName;
}
public String getLoginUserName() {
return loginUserName;
}
public void setLoginUserName(String loginUserName) {
this.loginUserName = loginUserName;
}
public String getLoginUserUnitName() {
return loginUserUnitName;
}
public void setLoginUserUnitName(String loginUserUnitName) {
this.loginUserUnitName = loginUserUnitName;
}
public String getLoginUserTopUnitName() {
return loginUserTopUnitName;
}
public void setLoginUserTopUnitName(String loginUserTopUnitName) {
this.loginUserTopUnitName = loginUserTopUnitName;
}
}
package com.x.okr.assemble.control;
import java.util.HashMap;
import java.util.Map;
import com.x.base.core.project.Context;
import com.x.base.core.project.cache.CacheManager;
import com.x.base.core.project.config.Config;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.okr.assemble.control.jaxrs.queue.QueueWorkDynamicRecord;
import com.x.okr.assemble.control.jaxrs.workimport.CacheImportFileStatus;
import com.x.okr.assemble.control.schedule.ErrorIdentityCheckTask;
import com.x.okr.assemble.control.schedule.St_CenterWorkCount;
import com.x.okr.assemble.control.schedule.St_WorkReportContent;
import com.x.okr.assemble.control.schedule.St_WorkReportStatus;
import com.x.okr.assemble.control.schedule.WorkProgressConfirm;
import com.x.okr.assemble.control.schedule.WorkReportCollectCreate;
import com.x.okr.assemble.control.schedule.WorkReportCreate;
import com.x.okr.assemble.control.service.OkrConfigSystemService;
public class ThisApplication {
private ThisApplication() {
// nothing
}
protected static Context context;
public static Map<String, CacheImportFileStatus> importFileStatusMap = new HashMap<String, CacheImportFileStatus>();
public static final String OKRMANAGER = "OKRManager";
public static final QueueWorkDynamicRecord queueWorkDynamicRecord = new QueueWorkDynamicRecord();
public static Context context() {
return context;
}
public static void init() {
try {
CacheManager.init(context.clazz().getSimpleName());
LoggerFactory.setLevel(Config.logLevel().x_okr_assemble_control());
context().startQueue(queueWorkDynamicRecord);
new OkrConfigSystemService().initAllSystemConfig();
// 每天凌晨2点执行一次
context.schedule(St_WorkReportContent.class, "0 0 2 * * ?");
// 每天凌晨2点30执行一次
context.schedule(St_WorkReportStatus.class, "0 30 2 * * ?");
// 每天5点至20点间,每10分钟执行一次
context.schedule(St_CenterWorkCount.class, "0 0/10 5-20 * * ?");
// 每天7点至17点间,每10分钟执行一次
context.schedule(WorkReportCreate.class, "0 0/10 7-17 * * ?");
// 每天7点至17点间,每小时执行一次
context.schedule(WorkProgressConfirm.class, "0 0 7-17/1 * * ?");
// 每天7点至17点间,每10分钟执行一次
context.schedule(WorkReportCollectCreate.class, "0 0/10 7-17 * * ?");
// 每天凌晨2点执行一次
context.schedule(ErrorIdentityCheckTask.class, "0 0 2 * * ?");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void destroy() {
try {
CacheManager.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getOkrUserInfoCacheKey(String personName) {
return "OkrUserInfo.withPerson." + personName;
}
public static Map<String, CacheImportFileStatus> getImportFileStatusMap() {
return importFileStatusMap;
}
public static void setImportFileStatusMap(Map<String, CacheImportFileStatus> importFileStatusMap) {
ThisApplication.importFileStatusMap = importFileStatusMap;
}
/**
* 根据用户姓名,获取一个用户登录信息缓存
*
* @param name
* @return
*/
public static CacheImportFileStatus getCacheImportFileStatusElementByKey(String key) {
if (importFileStatusMap == null) {
importFileStatusMap = new HashMap<String, CacheImportFileStatus>();
}
return importFileStatusMap.get(key);
}
}
package com.x.okr.assemble.control.dataadapter.webservice;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import com.google.gson.JsonElement;
import com.x.okr.assemble.control.ThisApplication;
public class WebservicesClient {
public Object[] jaxws(String wsdl, String method, Object... objects) {
Object[] result = null;
try {
JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
Client client = dcf.createClient(wsdl);
result = client.invoke(method, objects);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public JsonElement jaxrsGet(String applicationName, String uri) throws Exception {
Class<?> clz = Class.forName("com.x.base.core.project." + applicationName);
return ThisApplication.context().applications().getQuery(clz, uri).getData();
}
public JsonElement jaxrsPut(String applicationName, String uri, Object o) throws Exception {
Class<?> clz = Class.forName("com.x.base.core.project." + applicationName);
return ThisApplication.context().applications().putQuery(clz, uri, o).getData();
}
public JsonElement jaxrsPost(String applicationName, String uri, Object o) throws Exception {
Class<?> clz = Class.forName("com.x.base.core.project." + applicationName);
return ThisApplication.context().applications().postQuery(clz, uri, o).getData();
}
public JsonElement jaxrsDelete(String applicationName, String uri, Object o) throws Exception {
Class<?> clz = Class.forName("com.x.base.core.project." + applicationName);
return ThisApplication.context().applications().deleteQuery(clz, uri).getData();
}
}
package com.x.okr.assemble.control.dataadapter.webservice.sms;
public class SmsMessage {
String UNID = null;
String CONTENT = null;
public SmsMessage(String uNID, String cONTENT) {
super();
UNID = uNID;
CONTENT = cONTENT;
}
public String getUNID() {
return UNID;
}
public String getCONTENT() {
return CONTENT;
}
public void setUNID(String uNID) {
UNID = uNID;
}
public void setCONTENT(String cONTENT) {
CONTENT = cONTENT;
}
}
package com.x.okr.assemble.control.dataadapter.webservice.sms;
import org.apache.commons.lang3.StringUtils;
import com.x.okr.assemble.control.dataadapter.webservice.WebservicesClient;
import com.x.okr.assemble.control.service.OkrConfigSystemService;
import com.x.okr.assemble.control.service.OkrUserManagerService;
public class SmsMessageOperator {
public static OkrUserManagerService okrUserManagerService = new OkrUserManagerService();
public static OkrConfigSystemService okrConfigSystemService = new OkrConfigSystemService();
public static Boolean sendWithPersonName( String personName, String message ) {
String unique = null;
try {
unique = okrUserManagerService.getUniqueWithPerson(personName);
sendWithUnique(unique, message);
} catch (Exception e1) {
System.out.println("system query employee unique with person name got an exception!");
e1.printStackTrace();
return false;
}
return false;
}
public static Boolean sendWithUnique( String unique, String message ) {
if( StringUtils.isNotEmpty( unique )) {
String SMS_WSDL = null;
WebservicesClient webservicesClient = new WebservicesClient();
try {
SMS_WSDL = okrConfigSystemService.getValueWithConfigCode("SMS_WSDL");
} catch (Exception e) {
System.out.println("okr system get parameter named 'SMS_WSDL' got an exception!");
e.printStackTrace();
}
message = "O2OA_OKR message: " + message;
if(StringUtils.isNotEmpty(SMS_WSDL) && !"NONE".equalsIgnoreCase( SMS_WSDL )) {
try {
Object result = webservicesClient.jaxws( SMS_WSDL, "SENDSMS", unique, message);
System.out.println("Message send successful! result:" + result.toString());
return true;
} catch (Exception e) {
e.printStackTrace();
}
}else {
System.out.println("Message can not send, because sms wsdl not defind!");
}
}else {
System.out.println("Message can not send, because employee unique is empty!");
}
return false;
}
}
package com.x.okr.assemble.control.dataadapter.wftask;
import org.apache.commons.lang3.StringUtils;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.x.base.core.project.x_processplatform_assemble_surface;
import com.x.base.core.project.annotation.FieldDescribe;
import com.x.base.core.project.connection.ActionResponse;
import com.x.base.core.project.gson.GsonPropertyObject;
import com.x.okr.assemble.control.ThisApplication;
import com.x.okr.assemble.control.service.OkrConfigSystemService;
/**
* 获取指定用户所有的待阅数量信息
*
* @author O2LEE
*/
public class WfReadCountGetter {
public static OkrConfigSystemService okrConfigSystemService = new OkrConfigSystemService();
public Long countWithProcess(String person) throws Exception {
String APPRAISE_WORKFLOW_ID = null;
try {
APPRAISE_WORKFLOW_ID = okrConfigSystemService.getValueWithConfigCode("APPRAISE_WORKFLOW_ID");
} catch (Exception e) {
System.out.println("获取流程ID参数发生异常");
e.printStackTrace();
}
if( StringUtils.isNotEmpty(APPRAISE_WORKFLOW_ID)) {
JsonParser jsonParser = new JsonParser();
String json = "{";
json += "\"credentialList\":[";
json += "'"+person+"'";
json += "],";
json += "\"appliationList\":[],";
json += "\"processList\":[";
json += "'"+APPRAISE_WORKFLOW_ID+"'";
json += "]";
json += "}";
String serviceUri = "read/count/filter";
JsonElement data = jsonParser.parse( json ); // 将json字符串转换成JsonElement
ActionResponse resp = ThisApplication.context().applications().postQuery(
x_processplatform_assemble_surface.class, serviceUri, data
);
Wo wo = resp.getData( Wo.class );
// if( wo != null ){
// System.out.println(">>>>>>>>>>>>>>获取到用户的待阅(READ)数量:" + wo.count + ", 指定流程ID:" + APPRAISE_WORKFLOW_ID );
// }
return wo.count;
}
return 0L;
}
public static class Wo extends GsonPropertyObject {
@FieldDescribe("待办数量")
private Long count = 0L;
public Long getCount() {
return count;
}
public void setCount(Long count) {
this.count = count;
}
}
}
package com.x.okr.assemble.control.dataadapter.wftask;
import org.apache.commons.lang3.StringUtils;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.x.base.core.project.x_processplatform_assemble_surface;
import com.x.base.core.project.annotation.FieldDescribe;
import com.x.base.core.project.connection.ActionResponse;
import com.x.base.core.project.gson.GsonPropertyObject;
import com.x.okr.assemble.control.ThisApplication;
import com.x.okr.assemble.control.service.OkrConfigSystemService;
/**
* 获取指定用户所有的待办数量信息
*
* @author O2LEE
*/
public class WfTaskCountGetter {
public static OkrConfigSystemService okrConfigSystemService = new OkrConfigSystemService();
public Long countWithProcess(String person) throws Exception {
String APPRAISE_WORKFLOW_ID = null;
try {
APPRAISE_WORKFLOW_ID = okrConfigSystemService.getValueWithConfigCode("APPRAISE_WORKFLOW_ID");
} catch (Exception e) {
System.out.println("获取流程ID参数发生异常");
e.printStackTrace();
}
if( StringUtils.isNotEmpty(APPRAISE_WORKFLOW_ID)) {
JsonParser jsonParser = new JsonParser();
String json = "{";
json += "\"credentialList\":[";
json += "'"+person+"'";
json += "],";
json += "\"appliationList\":[],";
json += "\"processList\":[";
json += "'"+APPRAISE_WORKFLOW_ID+"'";
json += "]";
json += "}";
String serviceUri = "task/count/filter";
JsonElement data = jsonParser.parse( json ); // 将json字符串转换成JsonElement
ActionResponse resp = ThisApplication.context().applications().postQuery(
x_processplatform_assemble_surface.class, serviceUri, data
);
Wo wo = resp.getData( Wo.class );
// if( wo != null ){
// System.out.println(">>>>>>>>>>>>>>获取到用户的待办(TASK)数量:" + wo.count + ", 指定流程ID:" + APPRAISE_WORKFLOW_ID );
// }
return wo.count;
}
return 0L;
}
public static class Wo extends GsonPropertyObject {
@FieldDescribe("待办数量")
private Long count = 0L;
public Long getCount() {
return count;
}
public void setCount(Long count) {
this.count = count;
}
}
}
package com.x.okr.assemble.control.dataadapter.workflow;
import java.util.ArrayList;
import java.util.List;
import com.x.base.core.entity.JpaObject;
import com.x.base.core.project.x_processplatform_assemble_surface;
import com.x.base.core.project.annotation.FieldDescribe;
import com.x.base.core.project.bean.WrapCopier;
import com.x.base.core.project.bean.WrapCopierFactory;
import com.x.base.core.project.connection.ActionResponse;
import com.x.base.core.project.gson.GsonPropertyObject;
import com.x.okr.assemble.control.ThisApplication;
import com.x.processplatform.core.entity.content.Read;
import com.x.processplatform.core.entity.content.Task;
import com.x.processplatform.core.entity.content.TaskCompleted;
import com.x.processplatform.core.entity.content.Work;
import com.x.processplatform.core.entity.content.WorkLog;
import com.x.processplatform.core.entity.element.ActivityType;
/**
* 获取工作流状态以及下一步处理人的服务
*
* @author O2LEE
*/
public class WorkComplexGetter {
public Wo getWorkComplex( String workId ) throws Exception {
String serviceUri = "work/" + workId;
ActionResponse resp = ThisApplication.context().applications().getQuery(
x_processplatform_assemble_surface.class, serviceUri
);
Wo wo = resp.getData( Wo.class );
return wo;
}
public static class Wo extends GsonPropertyObject {
@FieldDescribe("活动节点")
private WoActivity activity;
@FieldDescribe("工作")
private WoWork work;
@FieldDescribe("待办对象列表")
private List<WoTask> taskList = new ArrayList<>();
@FieldDescribe("工作日志对象")
private List<WoWorkLog> workLogList = new ArrayList<>();
public WoActivity getActivity() {
return activity;
}
public WoWork getWork() {
return work;
}
public List<WoWorkLog> getWorkLogList() {
return workLogList;
}
public void setActivity(WoActivity activity) {
this.activity = activity;
}
public void setWork(WoWork work) {
this.work = work;
}
public void setWorkLogList(List<WoWorkLog> workLogList) {
this.workLogList = workLogList;
}
public List<WoTask> getTaskList() {
return taskList;
}
public void setTaskList(List<WoTask> taskList) {
this.taskList = taskList;
}
}
public static class WoActivity extends GsonPropertyObject {
private String id;
private String name;
private String description;
private String alias;
private String position;
private ActivityType activityType;
private String resetRange;
private Integer resetCount;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public ActivityType getActivityType() {
return activityType;
}
public void setActivityType(ActivityType activityType) {
this.activityType = activityType;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Integer getResetCount() {
return resetCount;
}
public void setResetCount(Integer resetCount) {
this.resetCount = resetCount;
}
public String getResetRange() {
return resetRange;
}
public void setResetRange(String resetRange) {
this.resetRange = resetRange;
}
}
public static class WoWork extends Work {
private static final long serialVersionUID = 3269592171662996253L;
static WrapCopier<Work, WoWork> copier = WrapCopierFactory.wo(Work.class, WoWork.class, null,
JpaObject.FieldsInvisible);
}
public static class WoWorkLog extends WorkLog {
private static final long serialVersionUID = 1307569946729101786L;
public static WrapCopier<WorkLog, WoWorkLog> copier = WrapCopierFactory.wo(WorkLog.class, WoWorkLog.class, null,
JpaObject.FieldsInvisible);
private List<WoTaskCompleted> taskCompletedList;
private List<WoTask> taskList;
private Integer currentTaskIndex;
public Integer getCurrentTaskIndex() {
return currentTaskIndex;
}
public void setCurrentTaskIndex(Integer currentTaskIndex) {
this.currentTaskIndex = currentTaskIndex;
}
public List<WoTaskCompleted> getTaskCompletedList() {
return taskCompletedList;
}
public void setTaskCompletedList(List<WoTaskCompleted> taskCompletedList) {
this.taskCompletedList = taskCompletedList;
}
public List<WoTask> getTaskList() {
return taskList;
}
public void setTaskList(List<WoTask> taskList) {
this.taskList = taskList;
}
}
public static class WoTask extends Task {
private static final long serialVersionUID = 2279846765261247910L;
public static WrapCopier<Task, WoTask> copier = WrapCopierFactory.wo(Task.class, WoTask.class, null,
JpaObject.FieldsInvisible);
}
public static class WoRead extends Read {
private static final long serialVersionUID = -8067704098385000667L;
public static WrapCopier<Read, WoRead> copier = WrapCopierFactory.wo(Read.class, WoRead.class, null,
JpaObject.FieldsInvisible);
}
public static class WoTaskCompleted extends TaskCompleted {
private static final long serialVersionUID = -7253999118308715077L;
public static WrapCopier<TaskCompleted, WoTaskCompleted> copier = WrapCopierFactory.wo(TaskCompleted.class,
WoTaskCompleted.class, null, JpaObject.FieldsInvisible);
private Long rank;
public Long getRank() {
return rank;
}
public void setRank(Long rank) {
this.rank = rank;
}
}
}
package com.x.okr.assemble.control.dataadapter.workflow;
import java.io.UnsupportedEncodingException;
import java.util.List;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.x.base.core.project.x_processplatform_assemble_surface;
import com.x.base.core.project.connection.ActionResponse;
import com.x.base.core.project.tools.ListTools;
import com.x.okr.assemble.control.ThisApplication;
/**
* 为工作流添加阅读权限
*
* @author O2LEE
*/
public class WorkFlowReaderAdder {
/**
* 为工作流添加阅读权限
* @param data
* @return
* @throws UnsupportedEncodingException
* @throws Exception
*/
public void add( String wf_workId, List<String> identities ) throws UnsupportedEncodingException, Exception {
if( ListTools.isEmpty(identities )) {
return;
}
JsonParser jsonParser = new JsonParser();
String json = "{";
json += "\"notify\": false,";
json += "\"identityList\":[";
for(int i=0; i< identities.size() ; i++ ) {
if(i == 0 ) {
json += "'"+ identities.get(i) +"'";
}else {
json += ", '"+ identities.get(i) +"'";
}
}
json += "]";
json += "}";
/**
* {
* "notify": false,
* "identityList":[
* '叶洪@84f71856-6447-4714-b616-64949e6e21c0@I',
* '金飞@50ab9f6f-6690-4972-ae50-c5c105316481@I',
* '金飞@50ab9f6f-6690-4972-ae50-c5c105316452@I',
* '昌威@0c5e3d66-3271-4815-b7b4-9be2370ce35ef@I',
* '张剑@c59fc8f0-e04c-4c92-92a9-42321c57883f@I'
* ]
* }
*/
JsonElement data = jsonParser.parse( json ); // 将json字符串转换成JsonElement
ActionResponse resp = ThisApplication.context().applications().postQuery(
x_processplatform_assemble_surface.class, "read/work/" + wf_workId , data
);
return ;
}
}
package com.x.okr.assemble.control.dataadapter.workflow;
import java.io.UnsupportedEncodingException;
import com.google.gson.JsonElement;
import com.x.base.core.project.x_processplatform_service_processing;
import com.x.base.core.project.connection.ActionResponse;
import com.x.base.core.project.http.WrapOutId;
import com.x.okr.assemble.control.ThisApplication;
/**
* 启动工作流的服务
*
* @author O2LEE
*/
public class WorkFlowStarter {
/**
* 启动一个工作流程,并且返回工作流实例work的ID
* @param data
* @return String
* @throws UnsupportedEncodingException
* @throws Exception
*
* http://dev.o2oa.io:20020/x_processplatform_service_processing/jaxrs/work
* POST
*/
public String start( JsonElement data ) throws UnsupportedEncodingException, Exception {
ActionResponse resp = ThisApplication.context().applications().postQuery(
x_processplatform_service_processing.class, "work", data
);
WrapOutId wrapOutId = resp.getData( WrapOutId.class );
return wrapOutId.getId();
}
}
package com.x.okr.assemble.control.factory;
import java.util.ArrayList;
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 com.x.base.core.project.exception.ExceptionWhen;
import com.x.okr.assemble.control.AbstractFactory;
import com.x.okr.assemble.control.Business;
import com.x.okr.entity.OkrAttachmentFileInfo;
import com.x.okr.entity.OkrAttachmentFileInfo_;
/**
* 类 名:OkrAttachmentFileInfoFactory<br/>
* 实体类:OkrAttachmentFileInfo<br/>
* 作 者:Liyi<br/>
* 单 位:O2 Team<br/>
* 日 期:2016-05-20 17:17:26
**/
public class OkrAttachmentFileInfoFactory extends AbstractFactory {
public OkrAttachmentFileInfoFactory(Business business) throws Exception {
super(business);
}
//@MethodDescribe( "获取指定Id的OkrAttachmentFileInfo实体信息对象" )
public OkrAttachmentFileInfo get( String id ) throws Exception {
return this.entityManagerContainer().find(id, OkrAttachmentFileInfo.class, ExceptionWhen.none);
}
//@MethodDescribe( "列示全部的OkrAttachmentFileInfo实体信息列表" )
public List<String> listAll() throws Exception {
EntityManager em = this.entityManagerContainer().get(OkrAttachmentFileInfo.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<OkrAttachmentFileInfo> root = cq.from( OkrAttachmentFileInfo.class);
cq.select(root.get(OkrAttachmentFileInfo_.id));
return em.createQuery(cq).getResultList();
}
//@MethodDescribe( "列示指定Id的OkrAttachmentFileInfo实体信息列表" )
public List<OkrAttachmentFileInfo> list(List<String> ids) throws Exception {
if( ids == null || ids.size() == 0 ){
return new ArrayList<OkrAttachmentFileInfo>();
}
EntityManager em = this.entityManagerContainer().get(OkrAttachmentFileInfo.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<OkrAttachmentFileInfo> cq = cb.createQuery(OkrAttachmentFileInfo.class);
Root<OkrAttachmentFileInfo> root = cq.from(OkrAttachmentFileInfo.class);
Predicate p = root.get(OkrAttachmentFileInfo_.id).in(ids);
return em.createQuery(cq.where(p)).getResultList();
}
}
package com.x.okr.assemble.control.factory;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;
import javax.persistence.EntityManager;
import javax.persistence.Query;
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.x.base.core.project.exception.ExceptionWhen;
import com.x.base.core.project.tools.ListTools;
import com.x.okr.assemble.control.AbstractFactory;
import com.x.okr.assemble.control.Business;
import com.x.okr.assemble.control.jaxrs.WorkCommonQueryFilter;
import com.x.okr.entity.OkrCenterWorkInfo;
import com.x.okr.entity.OkrCenterWorkInfo_;
public class OkrCenterWorkInfoFactory extends AbstractFactory {
public OkrCenterWorkInfoFactory( Business business ) throws Exception {
super(business);
}
//@MethodDescribe( "获取指定Id的OkrCenterWorkInfo应用信息对象" )
public OkrCenterWorkInfo get( String id ) throws Exception {
return this.entityManagerContainer().find(id, OkrCenterWorkInfo.class, ExceptionWhen.none);
}
//@MethodDescribe( "列示全部的OkrCenterWorkInfo应用信息列表" )
public List<String> listAll() throws Exception {
EntityManager em = this.entityManagerContainer().get(OkrCenterWorkInfo.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<OkrCenterWorkInfo> root = cq.from( OkrCenterWorkInfo.class);
cq.select(root.get(OkrCenterWorkInfo_.id));
return em.createQuery(cq).getResultList();
}
//@MethodDescribe( "列示指定Id的OkrCenterWorkInfo应用信息列表" )
public List<OkrCenterWorkInfo> list( List<String> ids, List<String> statuses ) throws Exception {
if( ids == null || ids.size() == 0 ){
return new ArrayList<OkrCenterWorkInfo>();
}
EntityManager em = this.entityManagerContainer().get(OkrCenterWorkInfo.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<OkrCenterWorkInfo> cq = cb.createQuery(OkrCenterWorkInfo.class);
Root<OkrCenterWorkInfo> root = cq.from(OkrCenterWorkInfo.class);
Predicate p = root.get(OkrCenterWorkInfo_.id).in(ids);
if( statuses != null && statuses.size() > 0 ){
p = cb.and( p, root.get(OkrCenterWorkInfo_.status ).in(statuses) );
}
return em.createQuery(cq.where(p)).getResultList();
}
/**
* 查询下一页的信息数据
* @param id
* @param count
* @param sequence
* @param wrapIn
* @return
* @throws Exception
*/
@SuppressWarnings( "unchecked" )
public List<OkrCenterWorkInfo> listNextWithFilter( String id, Integer count, Object sequence, WorkCommonQueryFilter wrapIn ) throws Exception {
//先获取上一页最后一条的sequence值,如果有值的话,以此sequence值作为依据取后续的count条数据
EntityManager em = this.entityManagerContainer().get( OkrCenterWorkInfo.class );
String order = wrapIn.getOrder();//排序方式
List<Object> vs = new ArrayList<>();
StringBuffer sql_stringBuffer = new StringBuffer();
if( order == null || order.isEmpty() ){
order = "DESC";
}
Integer index = 1;
sql_stringBuffer.append( "SELECT o FROM "+OkrCenterWorkInfo.class.getCanonicalName()+" o where 1=1" );
if ((null != sequence) ) {
sql_stringBuffer.append( " and o." + wrapIn.getSequenceField()+" " + (StringUtils.equalsIgnoreCase(order, "DESC" ) ? "<" : ">" ) + ( " ?" + (index)));
vs.add(sequence);
index++;
}
if ((null != wrapIn.getDefaultWorkTypes()) && wrapIn.getDefaultWorkTypes().size() > 0) {
sql_stringBuffer.append( " and o.defaultWorkType in ( ?" + (index) + " )" );
vs.add( wrapIn.getDefaultWorkTypes() );
index++;
}
if ((null != wrapIn.getCenterIds()) && wrapIn.getCenterIds().size() > 0) {
sql_stringBuffer.append( " and o.id in ( ?" + (index) + " )" );
vs.add( wrapIn.getCenterIds() );
index++;
}
if (null != wrapIn.getProcessStatusList() && wrapIn.getProcessStatusList().size() > 0 ) {
sql_stringBuffer.append( " and o.processStatus in ( ?" + (index) + " )" );
vs.add( wrapIn.getProcessStatusList() );
index++;
}
if (null != wrapIn.getTitle() && !wrapIn.getTitle().isEmpty() ) {
sql_stringBuffer.append( " and o.title like ?" + (index) );
vs.add( "%"+wrapIn.getTitle()+"%" );
index++;
}
if (null != wrapIn.getQ_statuses() && wrapIn.getQ_statuses().size() > 0 ) {
sql_stringBuffer.append( " and o.status in (?" + (index) + " )" );
vs.add( wrapIn.getQ_statuses() );
index++;
}
sql_stringBuffer.append( " order by o." + wrapIn.getSequenceField() + " " + ( StringUtils.equalsIgnoreCase( order, "DESC" ) ? "DESC" : "ASC" ) );
Query query = em.createQuery( sql_stringBuffer.toString(), OkrCenterWorkInfo.class );
for (int i = 0; i < vs.size(); i++) {
query.setParameter(i + 1, vs.get(i));
}
return query.setMaxResults(count).getResultList();
}
/**
* 查询上一页的信息数据
* @param id
* @param count
* @param sequence
* @param wrapIn
* @return
* @throws Exception
*/
@SuppressWarnings( "unchecked" )
public List<OkrCenterWorkInfo> listPrevWithFilter( String id, Integer count, Object sequence, WorkCommonQueryFilter wrapIn ) throws Exception {
//先获取上一页最后一条的sequence值,如果有值的话,以此sequence值作为依据取后续的count条数据
EntityManager em = this.entityManagerContainer().get( OkrCenterWorkInfo.class );
String order = wrapIn.getOrder();//排序方式
List<Object> vs = new ArrayList<>();
StringBuffer sql_stringBuffer = new StringBuffer();
Integer index = 1;
if( order == null || order.isEmpty() ){
order = "DESC";
}
sql_stringBuffer.append( "SELECT o FROM " + OkrCenterWorkInfo.class.getCanonicalName()+" o where 1=1" );
if ((null != sequence) ) {
sql_stringBuffer.append( " and o."+wrapIn.getSequenceField()+" " + (StringUtils.equalsIgnoreCase(order, "DESC" ) ? ">" : "<" ) + ( " ?" + (index)));
vs.add(sequence);
index++;
}
if ((null != wrapIn.getDefaultWorkTypes()) && wrapIn.getDefaultWorkTypes().size() > 0) {
sql_stringBuffer.append( " and o.defaultWorkType in ( ?" + (index) + " )" );
vs.add( wrapIn.getDefaultWorkTypes() );
index++;
}
if ((null != wrapIn.getCenterIds()) && wrapIn.getCenterIds().size() > 0) {
sql_stringBuffer.append( " and o.id in ( ?" + (index) + " )" );
vs.add( wrapIn.getCenterIds() );
index++;
}
if (null != wrapIn.getProcessStatusList() && wrapIn.getProcessStatusList().size() > 0 ) {
sql_stringBuffer.append( " and o.processStatus in ( ?" + (index) + " )" );
vs.add( wrapIn.getProcessStatusList() );
index++;
}
if (null != wrapIn.getTitle() && !wrapIn.getTitle().isEmpty() ) {
sql_stringBuffer.append( " and o.title like ?" + (index) );
vs.add( "%"+wrapIn.getTitle()+"%" );
index++;
}
if (null != wrapIn.getQ_statuses() && wrapIn.getQ_statuses().size() > 0 ) {
sql_stringBuffer.append( " and o.status in ( ?" + (index) + " )" );
vs.add( wrapIn.getQ_statuses() );
index++;
}
sql_stringBuffer.append( " order by o." + wrapIn.getSequenceField() + " " + ( StringUtils.equalsIgnoreCase( order, "DESC" ) ? "DESC" : "ASC" ) );
//logger.debug( "listIdsNextWithFilter:[" +sql_stringBuffer.toString()+ "]" );
//logger.debug(vs);
Query query = em.createQuery( sql_stringBuffer.toString(), OkrCenterWorkInfo.class );
//为查询设置所有的参数值
for (int i = 0; i < vs.size(); i++) {
query.setParameter(i + 1, vs.get(i));
}
return query.setMaxResults(count).getResultList();
}
/**
* 查询符合的信息总数
* @param id
* @param count
* @param sequence
* @param wrapIn
* @return
* @throws Exception
*/
public long getCountWithFilter( WorkCommonQueryFilter wrapIn ) throws Exception {
//先获取上一页最后一条的sequence值,如果有值的话,以此sequence值作为依据取后续的count条数据
EntityManager em = this.entityManagerContainer().get( OkrCenterWorkInfo.class );
List<Object> vs = new ArrayList<>();
StringBuffer sql_stringBuffer = new StringBuffer();
Integer index = 1;
sql_stringBuffer.append( "SELECT count(o.id) FROM "+OkrCenterWorkInfo.class.getCanonicalName()+" o where 1=1" );
if ((null != wrapIn.getCenterIds()) && wrapIn.getCenterIds().size() > 0) {
sql_stringBuffer.append( " and o.id in ( ?" + (index) + " )" );
vs.add( wrapIn.getCenterIds() );
index++;
}
if (null != wrapIn.getProcessStatusList() && wrapIn.getProcessStatusList().size() > 0 ) {
sql_stringBuffer.append( " and o.processStatus in ( ?" + (index) + " )" );
vs.add( wrapIn.getProcessStatusList() );
index++;
}
if ((null != wrapIn.getDefaultWorkTypes()) && wrapIn.getDefaultWorkTypes().size() > 0) {
sql_stringBuffer.append( " and o.defaultWorkType in ( ?" + (index) + " )" );
vs.add( wrapIn.getDefaultWorkTypes() );
index++;
}
if (null != wrapIn.getTitle() && !wrapIn.getTitle().isEmpty() ) {
sql_stringBuffer.append( " and o.title like ?" + (index) );
vs.add( "%"+wrapIn.getTitle()+"%" );
index++;
}
if (null != wrapIn.getQ_statuses() && wrapIn.getQ_statuses().size() > 0 ) {
sql_stringBuffer.append( " and o.status in ( ?" + (index) + " )" );
vs.add( wrapIn.getQ_statuses() );
index++;
}
Query query = em.createQuery( sql_stringBuffer.toString(), OkrCenterWorkInfo.class );
for (int i = 0; i < vs.size(); i++) {
query.setParameter(i + 1, vs.get(i));
}
return (Long) query.getSingleResult();
}
public List<String> listAllProcessingCenterWorkIds( List<String> processStatus, List<String> status ) throws Exception {
EntityManager em = this.entityManagerContainer().get(OkrCenterWorkInfo.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery( String.class );
Root<OkrCenterWorkInfo> root = cq.from(OkrCenterWorkInfo.class);
cq.select(root.get( OkrCenterWorkInfo_.id ));
Predicate p = root.get(OkrCenterWorkInfo_.processStatus).in( processStatus );
if( status != null && status.size() > 0 ){
p = cb.and( p, root.get( OkrCenterWorkInfo_.status ).in( status ) );
}
return em.createQuery(cq.where(p)).getResultList();
}
public List<OkrCenterWorkInfo> listAllCenterWorks( String status ) throws Exception {
if( status == null || status.isEmpty() ){
throw new Exception("status is null!");
}
EntityManager em = this.entityManagerContainer().get(OkrCenterWorkInfo.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<OkrCenterWorkInfo> cq = cb.createQuery(OkrCenterWorkInfo.class);
Root<OkrCenterWorkInfo> root = cq.from(OkrCenterWorkInfo.class);
Predicate p = cb.equal( root.get( OkrCenterWorkInfo_.status ), status );
return em.createQuery(cq.where(p)).getResultList();
}
/**
* 查询中心工作审核领导身份列表(去重复)
* @param identities_ok 排除身份
* @param identities_error 排除身份
* @return
* @throws Exception
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public List<String> listAllDistinctAuditLeaderIdentity(List<String> identities_ok, List<String> identities_error) throws Exception {
EntityManager em = this.entityManagerContainer().get(OkrCenterWorkInfo.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<OkrCenterWorkInfo> cq = cb.createQuery( OkrCenterWorkInfo.class );
Root<OkrCenterWorkInfo> root = cq.from(OkrCenterWorkInfo.class);
// cq.select(root.get( OkrCenterWorkInfo_.reportAuditLeaderIdentityList ));
List<OkrCenterWorkInfo> centerWorkInfos = em.createQuery(cq).getResultList();
//ListTools.trim(list, ignoreNull, unique, ts);
if(ListTools.isNotEmpty( centerWorkInfos )) {
HashSet hashSet = new HashSet();
for(OkrCenterWorkInfo centerWorkInfo : centerWorkInfos ) {
if( ListTools.isNotEmpty( centerWorkInfo.getReportAuditLeaderIdentityList() ) ) {
for( String identity : centerWorkInfo.getReportAuditLeaderIdentityList() ) {
if( ListTools.isNotEmpty(identities_ok) && identities_ok.contains( identity ) ){
continue;
}
if( ListTools.isNotEmpty(identities_error) && identities_error.contains( identity ) ){
continue;
}
hashSet.add( identity );
}
}
}
List<String> result = new ArrayList<>();
result.addAll(hashSet);
return result;
}
return null;
}
/**
* 查询中心工作创建者身份列表(去重复)
* @param identities_ok 排除身份
* @param identities_error 排除身份
* @return
* @throws Exception
*/
public List<String> listAllDistinctCreatorIdentity(List<String> identities_ok, List<String> identities_error) throws Exception {
EntityManager em = this.entityManagerContainer().get(OkrCenterWorkInfo.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery( String.class );
Root<OkrCenterWorkInfo> root = cq.from(OkrCenterWorkInfo.class);
Predicate p = cb.isNotNull( root.get( OkrCenterWorkInfo_.id ) );
if( identities_ok != null && identities_ok.size() > 0 ){
p = cb.and( p, cb.not(root.get( OkrCenterWorkInfo_.creatorIdentity ).in( identities_ok )) );
}
if( identities_error != null && identities_error.size() > 0 ){
p = cb.and( p, cb.not(root.get( OkrCenterWorkInfo_.creatorIdentity ).in( identities_error )) );
}
cq.select(root.get( OkrCenterWorkInfo_.creatorIdentity ));
return em.createQuery(cq.where(p)).getResultList().stream().distinct().collect(Collectors.toList());
}
/**
* 查询中心工作部署者身份列表(去重复)
* @param identities_ok 排除身份
* @param identities_error 排除身份
* @return
* @throws Exception
*/
public List<String> listAllDistinctDeployerIdentity(List<String> identities_ok, List<String> identities_error) throws Exception {
EntityManager em = this.entityManagerContainer().get(OkrCenterWorkInfo.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery( String.class );
Root<OkrCenterWorkInfo> root = cq.from(OkrCenterWorkInfo.class);
Predicate p = cb.isNotNull( root.get( OkrCenterWorkInfo_.id ) );
if( identities_ok != null && identities_ok.size() > 0 ){
p = cb.and( p, cb.not(root.get( OkrCenterWorkInfo_.deployerIdentity ).in( identities_ok )) );
}
if( identities_error != null && identities_error.size() > 0 ){
p = cb.and( p, cb.not(root.get( OkrCenterWorkInfo_.deployerIdentity ).in( identities_error )) );
}
cq.select(root.get( OkrCenterWorkInfo_.deployerIdentity ));
return em.createQuery(cq.where(p)).getResultList().stream().distinct().collect(Collectors.toList());
}
/**
* 查询中心工作汇报审核领导身份列表(去重复)
* @param identities_ok 排除身份
* @param identities_error 排除身份
* @return
* @throws Exception
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<String> listAllDistinctReportAuditLeaderIdentity(List<String> identities_ok,
List<String> identities_error) throws Exception {
EntityManager em = this.entityManagerContainer().get(OkrCenterWorkInfo.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<OkrCenterWorkInfo> cq = cb.createQuery(OkrCenterWorkInfo.class);
Root<OkrCenterWorkInfo> root = cq.from(OkrCenterWorkInfo.class);
List<OkrCenterWorkInfo> os = em.createQuery(cq.select(root)).getResultList();
List<List> allList = new ArrayList<>();
for (OkrCenterWorkInfo o : os) {
allList.add(o.getReportAuditLeaderIdentityList());
}
if(ListTools.isNotEmpty( allList )) {
HashSet hashSet = new HashSet();
for( List<String> identities : allList ) {
if(ListTools.isNotEmpty( identities )) {
for( String identity : identities ) {
if( ListTools.isNotEmpty(identities_ok) && identities_ok.contains( identity ) ){
continue;
}
if( ListTools.isNotEmpty(identities_error) && identities_error.contains( identity ) ){
continue;
}
hashSet.add( identity );
}
}
}
List<String> result = new ArrayList<>();
result.addAll(hashSet);
return result;
}
return null;
}
/**
* 根据身份名称,从中心工作信息中查询与该身份有关的所有信息列表
* @param identity
* @param recordId
* @return
* @throws Exception
*/
public List<OkrCenterWorkInfo> listErrorIdentitiesInCenterInfo( String identity, String recordId ) throws Exception {
EntityManager em = this.entityManagerContainer().get(OkrCenterWorkInfo.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<OkrCenterWorkInfo> cq = cb.createQuery( OkrCenterWorkInfo.class );
Root<OkrCenterWorkInfo> root = cq.from( OkrCenterWorkInfo.class );
Predicate p = cb.isNotNull(root.get( OkrCenterWorkInfo_.id ));
if( recordId != null && !recordId.isEmpty() && !"all".equals( recordId ) ){
p = cb.and( p, cb.equal( root.get( OkrCenterWorkInfo_.id ), recordId ) );
}
Predicate p_creatorIdentity = cb.isNotNull(root.get( OkrCenterWorkInfo_.creatorIdentity ));
p_creatorIdentity = cb.and( p_creatorIdentity, cb.equal( root.get( OkrCenterWorkInfo_.creatorIdentity ), identity ) );
Predicate p_deployerIdentity = cb.isNotNull(root.get( OkrCenterWorkInfo_.deployerIdentity ));
p_deployerIdentity = cb.and( p_deployerIdentity, cb.equal( root.get( OkrCenterWorkInfo_.deployerIdentity ), identity ) );
Predicate p_reportAuditLeaderIdentity = cb.isNotNull(root.get( OkrCenterWorkInfo_.reportAuditLeaderIdentityList ));
p_reportAuditLeaderIdentity = cb.and( p_reportAuditLeaderIdentity,cb.isMember(identity, root.get( OkrCenterWorkInfo_.reportAuditLeaderIdentityList )));
Predicate p_auditLeaderIdentity = cb.isNotNull(root.get( OkrCenterWorkInfo_.reportAuditLeaderIdentityList ));
p_auditLeaderIdentity = cb.and( p_auditLeaderIdentity, cb.isMember( identity, root.get( OkrCenterWorkInfo_.reportAuditLeaderIdentityList ) ) );
Predicate p_identity = cb.or( p_creatorIdentity, p_deployerIdentity, p_reportAuditLeaderIdentity, p_auditLeaderIdentity );
p = cb.and( p, p_identity );
return em.createQuery(cq.where(p)).getResultList();
}
}
\ No newline at end of file
package com.x.okr.assemble.control.factory;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
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 com.x.base.core.project.exception.ExceptionWhen;
import com.x.okr.assemble.control.AbstractFactory;
import com.x.okr.assemble.control.Business;
import com.x.okr.entity.OkrConfigSecretary;
import com.x.okr.entity.OkrConfigSecretary_;
public class OkrConfigSecretaryFactory extends AbstractFactory {
public OkrConfigSecretaryFactory(Business business) throws Exception {
super(business);
}
//@MethodDescribe( "获取指定Id的OkrConfigSecretary应用信息对象" )
public OkrConfigSecretary get( String id ) throws Exception {
return this.entityManagerContainer().find(id, OkrConfigSecretary.class, ExceptionWhen.none);
}
//@MethodDescribe( "列示全部的OkrConfigSecretary应用信息列表" )
public List<String> listAll() throws Exception {
EntityManager em = this.entityManagerContainer().get(OkrConfigSecretary.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<OkrConfigSecretary> root = cq.from( OkrConfigSecretary.class);
cq.select(root.get(OkrConfigSecretary_.id));
return em.createQuery(cq).getResultList();
}
//@MethodDescribe( "列示指定Id的OkrConfigSecretary应用信息列表" )
public List<OkrConfigSecretary> list(List<String> ids) throws Exception {
if( ids == null || ids.size() == 0 ){
return new ArrayList<OkrConfigSecretary>();
}
EntityManager em = this.entityManagerContainer().get(OkrConfigSecretary.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<OkrConfigSecretary> cq = cb.createQuery(OkrConfigSecretary.class);
Root<OkrConfigSecretary> root = cq.from(OkrConfigSecretary.class);
Predicate p = root.get(OkrConfigSecretary_.id).in(ids);
return em.createQuery(cq.where(p)).getResultList();
}
/**
* 根据秘书姓名查询配置好的秘书信息ID列表
* @param userName
* @return
* @throws Exception
*/
//@MethodDescribe( "根据秘书姓名查询配置好的秘书信息ID列表" )
public List<String> listBySecretaryName( String userName ) throws Exception {
if( userName == null || userName.isEmpty() ){
throw new Exception ( "the parameter: 'userName' is null!" );
}
EntityManager em = this.entityManagerContainer().get( OkrConfigSecretary.class );
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<OkrConfigSecretary> root = cq.from( OkrConfigSecretary.class);
cq.select(root.get(OkrConfigSecretary_.id));
Predicate p = cb.equal( root.get(OkrConfigSecretary_.secretaryName ) , userName);
return em.createQuery(cq.where(p)).getResultList();
}
//@MethodDescribe( "根据秘书姓名和被代理员工姓名查询配置好的秘书信息ID列表" )
public List<String> listIdsByPerson( String name, String leaderName ) throws Exception {
if( name == null || name.isEmpty() ){
throw new Exception ( "the parameter: 'name' is null!" );
}
if( leaderName == null || leaderName.isEmpty() ){
throw new Exception ( "the parameter: 'leaderName' is null!" );
}
EntityManager em = this.entityManagerContainer().get( OkrConfigSecretary.class );
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<OkrConfigSecretary> root = cq.from( OkrConfigSecretary.class);
cq.select(root.get( OkrConfigSecretary_.id ));
Predicate p = cb.equal( root.get( OkrConfigSecretary_.secretaryName ) , name );
p = cb.and( p, cb.equal( root.get( OkrConfigSecretary_.leaderName ), leaderName ));
return em.createQuery(cq.where(p)).getResultList();
}
public List<String> listIdsByLeaderIdentity( String name, String leaderIdentity ) throws Exception {
if( name == null || name.isEmpty() ){
throw new Exception ( "the parameter: 'name' is null!" );
}
if( leaderIdentity == null || leaderIdentity.isEmpty() ){
throw new Exception ( "the parameter: 'leaderIdentity' is null!" );
}
EntityManager em = this.entityManagerContainer().get( OkrConfigSecretary.class );
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery( String.class );
Root<OkrConfigSecretary> root = cq.from( OkrConfigSecretary.class);
cq.select(root.get( OkrConfigSecretary_.id ));
Predicate p = cb.equal( root.get( OkrConfigSecretary_.secretaryName ) , name );
p = cb.and( p, cb.equal( root.get( OkrConfigSecretary_.leaderIdentity ), leaderIdentity ));
return em.createQuery( cq.where(p) ).getResultList();
}
/**
* 查询秘书代理领导身份列表(去重复)
* @param identities_ok 排除身份
* @param identities_error 排除身份
* @return
* @throws Exception
*/
public List<String> listAllDistinctLeaderIdentity(List<String> identities_ok, List<String> identities_error) throws Exception {
EntityManager em = this.entityManagerContainer().get(OkrConfigSecretary.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery( String.class );
Root<OkrConfigSecretary> root = cq.from(OkrConfigSecretary.class);
Predicate p = cb.isNotNull( root.get( OkrConfigSecretary_.id ) );
if( identities_ok != null && identities_ok.size() > 0 ){
p = cb.and( p, cb.not(root.get( OkrConfigSecretary_.leaderIdentity ).in( identities_ok )) );
}
if( identities_error != null && identities_error.size() > 0 ){
p = cb.and( p, cb.not(root.get( OkrConfigSecretary_.leaderIdentity ).in( identities_error )) );
}
cq.select(root.get( OkrConfigSecretary_.leaderIdentity ));
return em.createQuery(cq.where(p)).getResultList().stream().distinct().collect(Collectors.toList());
}
/**
* 根据身份名称,从领导秘书配置信息中查询与该身份有关的所有信息列表
* @param identity
* @param recordId
* @return
* @throws Exception
*/
public List<OkrConfigSecretary> listErrorIdentitiesInConfigSecretary(String identity, String recordId) throws Exception {
EntityManager em = this.entityManagerContainer().get(OkrConfigSecretary.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<OkrConfigSecretary> cq = cb.createQuery( OkrConfigSecretary.class );
Root<OkrConfigSecretary> root = cq.from( OkrConfigSecretary.class );
Predicate p = cb.isNotNull(root.get( OkrConfigSecretary_.id ));
if( recordId != null && !recordId.isEmpty() && !"all".equals( recordId ) ){
p = cb.and( p, cb.equal( root.get( OkrConfigSecretary_.id ), recordId ) );
}
Predicate p_leaderIdentity = cb.isNotNull(root.get( OkrConfigSecretary_.leaderIdentity ));
p_leaderIdentity = cb.and( p_leaderIdentity, cb.equal( root.get( OkrConfigSecretary_.leaderIdentity ), identity ) );
Predicate p_secretaryIdentity = cb.isNotNull(root.get( OkrConfigSecretary_.secretaryIdentity ));
p_secretaryIdentity = cb.and( p_secretaryIdentity, cb.equal( root.get( OkrConfigSecretary_.secretaryIdentity ), identity ) );
Predicate p_identity = cb.or( p_leaderIdentity, p_secretaryIdentity );
p = cb.and( p, p_identity );
return em.createQuery(cq.where(p)).getResultList();
}
public List<String> listIdsByIdentities(List<String> identities) throws Exception {
EntityManager em = this.entityManagerContainer().get(OkrConfigSecretary.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery( String.class );
Root<OkrConfigSecretary> root = cq.from(OkrConfigSecretary.class);
Predicate p = root.get( OkrConfigSecretary_.secretaryName ).in( identities );
cq.select(root.get( OkrConfigSecretary_.id ));
return em.createQuery(cq.where(p)).getResultList();
}
}
\ No newline at end of file
package com.x.okr.assemble.control.factory;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
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 com.x.base.core.project.exception.ExceptionWhen;
import com.x.okr.assemble.control.AbstractFactory;
import com.x.okr.assemble.control.Business;
import com.x.okr.entity.OkrConfigSystem;
import com.x.okr.entity.OkrConfigSystem_;
/**
* 类 名:OkrConfigSystemFactory<br/>
* 实体类:OkrConfigSystem<br/>
* 作 者:Liyi<br/>
* 单 位:O2 Team<br/>
* 日 期:2016-05-20 17:17:26
**/
public class OkrConfigSystemFactory extends AbstractFactory {
public OkrConfigSystemFactory(Business business) throws Exception {
super(business);
}
// @MethodDescribe( "获取指定Id的OkrConfigSystem实体信息对象" )
public OkrConfigSystem get( String id ) throws Exception {
return this.entityManagerContainer().find(id, OkrConfigSystem.class, ExceptionWhen.none);
}
//@MethodDescribe( "列示全部的OkrConfigSystem实体信息列表" )
public List<OkrConfigSystem> listAll() throws Exception {
EntityManager em = this.entityManagerContainer().get(OkrConfigSystem.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<OkrConfigSystem> cq = cb.createQuery(OkrConfigSystem.class);
@SuppressWarnings("unused")
Root<OkrConfigSystem> root = cq.from( OkrConfigSystem.class);
return em.createQuery(cq).getResultList();
}
//@MethodDescribe( "列示指定Id的OkrConfigSystem实体信息列表" )
public List<OkrConfigSystem> list(List<String> ids) throws Exception {
if( ids == null || ids.size() == 0 ){
return new ArrayList<OkrConfigSystem>();
}
EntityManager em = this.entityManagerContainer().get(OkrConfigSystem.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<OkrConfigSystem> cq = cb.createQuery(OkrConfigSystem.class);
Root<OkrConfigSystem> root = cq.from(OkrConfigSystem.class);
Predicate p = root.get(OkrConfigSystem_.id).in(ids);
return em.createQuery(cq.where(p)).getResultList();
}
//@MethodDescribe( "根据指定的配置编码获取配置的值" )
public String getValueWithConfigCode(String configCode) throws Exception {
if( configCode == null || configCode.isEmpty() ){
throw new Exception( "config code is null, can not find any system config!" );
}
EntityManager em = this.entityManagerContainer().get(OkrConfigSystem.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<OkrConfigSystem> root = cq.from(OkrConfigSystem.class);
Predicate p = cb.equal( root.get( OkrConfigSystem_.configCode ), configCode );
cq.select(root.get(OkrConfigSystem_.configValue));
//System.out.println("SQL:" + em.createQuery(cq.where(p)).toString() );
List<String> valueList = em.createQuery(cq.where(p)).getResultList();
if( valueList != null && valueList.size() > 0 ){
//System.out.println("valueList.get(0):" + valueList.get(0) );
return valueList.get(0);
}
return null;
}
public OkrConfigSystem getWithConfigCode(String configCode) throws Exception {
if( configCode == null || configCode.isEmpty() ){
throw new Exception( "config code is null, can not find any system config!" );
}
EntityManager em = this.entityManagerContainer().get(OkrConfigSystem.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<OkrConfigSystem> cq = cb.createQuery(OkrConfigSystem.class);
Root<OkrConfigSystem> root = cq.from(OkrConfigSystem.class);
Predicate p = cb.equal( root.get( OkrConfigSystem_.configCode ), configCode );
List<OkrConfigSystem> valueList = em.createQuery(cq.where(p)).getResultList();
if( valueList != null && valueList.size() > 0 ){
return valueList.get(0);
}
return null;
}
/**
* 查询系统配置值身份列表(去重复)
* @param identities_ok 排除身份
* @param identities_error 排除身份
* @return
* @throws Exception
*/
public List<String> listAllDistinctValueIdentity( List<String> identities_ok, List<String> identities_error ) throws Exception {
EntityManager em = this.entityManagerContainer().get(OkrConfigSystem.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery( String.class );
Root<OkrConfigSystem> root = cq.from(OkrConfigSystem.class);
Predicate p = cb.isNotNull( root.get( OkrConfigSystem_.id ) );
p = cb.and( p, cb.equal( root.get( OkrConfigSystem_.valueType ), "identity") );
if( identities_ok != null && identities_ok.size() > 0 ){
p = cb.and( p, cb.not(root.get( OkrConfigSystem_.configValue ).in( identities_ok )) );
}
if( identities_error != null && identities_error.size() > 0 ){
p = cb.and( p, cb.not(root.get( OkrConfigSystem_.configValue ).in( identities_error )) );
}
cq.select(root.get( OkrConfigSystem_.configValue ));
return em.createQuery(cq.where(p)).getResultList().stream().distinct().collect(Collectors.toList());
}
/**
* 根据身份名称,从系统参数配置信息中查询与该身份有关的所有信息列表
* @param identity
* @param recordId
* @return
* @throws Exception
*/
public List<OkrConfigSystem> listErrorIdentitiesInConfigSystem(String identity, String recordId) throws Exception {
EntityManager em = this.entityManagerContainer().get( OkrConfigSystem.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<OkrConfigSystem> cq = cb.createQuery( OkrConfigSystem.class );
Root<OkrConfigSystem> root = cq.from( OkrConfigSystem.class );
Predicate p = cb.isNotNull(root.get( OkrConfigSystem_.configValue ));
if( recordId != null && !recordId.isEmpty() && !"all".equals( recordId ) ){
p = cb.and( p, cb.equal( root.get( OkrConfigSystem_.id ), recordId ) );
}
//p = cb.and( p, cb.equal( root.get( OkrConfigSystem_.valueType ), "identity") );
p = cb.and( p, cb.like( root.get( OkrConfigSystem_.configValue ), "%"+identity+"%" ) );
return em.createQuery(cq.where(p)).getResultList();
}
}
package com.x.okr.assemble.control.factory;
import java.util.ArrayList;
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 com.x.base.core.project.exception.ExceptionWhen;
import com.x.okr.assemble.control.AbstractFactory;
import com.x.okr.assemble.control.Business;
import com.x.okr.entity.OkrConfigWorkLevel;
import com.x.okr.entity.OkrConfigWorkLevel_;
/**
* 类 名:OkrConfigWorkLevelFactory<br/>
* 实体类:OkrConfigWorkLevel<br/>
* 作 者:Liyi<br/>
* 单 位:O2 Team<br/>
* 日 期:2016-05-20 17:17:26
**/
public class OkrConfigWorkLevelFactory extends AbstractFactory {
public OkrConfigWorkLevelFactory(Business business) throws Exception {
super(business);
}
//@MethodDescribe( "获取指定Id的OkrConfigWorkLevel实体信息对象" )
public OkrConfigWorkLevel get( String id ) throws Exception {
return this.entityManagerContainer().find(id, OkrConfigWorkLevel.class, ExceptionWhen.none);
}
//@MethodDescribe( "列示全部的OkrConfigWorkLevel实体信息列表" )
public List<OkrConfigWorkLevel> listAll() throws Exception {
EntityManager em = this.entityManagerContainer().get(OkrConfigWorkLevel.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<OkrConfigWorkLevel> cq = cb.createQuery(OkrConfigWorkLevel.class);
@SuppressWarnings("unused")
Root<OkrConfigWorkLevel> root = cq.from( OkrConfigWorkLevel.class);
return em.createQuery(cq).getResultList();
}
//@MethodDescribe( "列示指定Id的OkrConfigWorkLevel实体信息列表" )
public List<OkrConfigWorkLevel> list(List<String> ids) throws Exception {
if( ids == null || ids.size() == 0 ){
return new ArrayList<OkrConfigWorkLevel>();
}
EntityManager em = this.entityManagerContainer().get(OkrConfigWorkLevel.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<OkrConfigWorkLevel> cq = cb.createQuery(OkrConfigWorkLevel.class);
Root<OkrConfigWorkLevel> root = cq.from(OkrConfigWorkLevel.class);
Predicate p = root.get(OkrConfigWorkLevel_.id).in(ids);
return em.createQuery(cq.where(p)).getResultList();
}
}
package com.x.okr.assemble.control.factory;
import java.util.ArrayList;
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 com.x.base.core.project.exception.ExceptionWhen;
import com.x.okr.assemble.control.AbstractFactory;
import com.x.okr.assemble.control.Business;
import com.x.okr.entity.OkrConfigWorkType;
import com.x.okr.entity.OkrConfigWorkType_;
/**
* 类 名:OkrConfigWorkTypeFactory<br/>
* 实体类:OkrConfigWorkType<br/>
* 作 者:Liyi<br/>
* 单 位:O2 Team<br/>
* 日 期:2016-05-20 17:17:26
**/
public class OkrConfigWorkTypeFactory extends AbstractFactory {
public OkrConfigWorkTypeFactory(Business business) throws Exception {
super(business);
}
//@MethodDescribe( "获取指定Id的OkrConfigWorkType实体信息对象" )
public OkrConfigWorkType get( String id ) throws Exception {
return this.entityManagerContainer().find(id, OkrConfigWorkType.class, ExceptionWhen.none);
}
//@MethodDescribe( "列示全部的OkrConfigWorkType实体信息列表" )
public List<OkrConfigWorkType> listAll() throws Exception {
EntityManager em = this.entityManagerContainer().get(OkrConfigWorkType.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<OkrConfigWorkType> cq = cb.createQuery(OkrConfigWorkType.class);
@SuppressWarnings("unused")
Root<OkrConfigWorkType> root = cq.from( OkrConfigWorkType.class);
return em.createQuery(cq).getResultList();
}
//@MethodDescribe( "列示指定Id的OkrConfigWorkType实体信息列表" )
public List<OkrConfigWorkType> list(List<String> ids) throws Exception {
if( ids == null || ids.size() == 0 ){
return new ArrayList<OkrConfigWorkType>();
}
EntityManager em = this.entityManagerContainer().get(OkrConfigWorkType.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<OkrConfigWorkType> cq = cb.createQuery(OkrConfigWorkType.class);
Root<OkrConfigWorkType> root = cq.from(OkrConfigWorkType.class);
Predicate p = root.get(OkrConfigWorkType_.id).in(ids);
return em.createQuery(cq.where(p)).getResultList();
}
}
package com.x.okr.assemble.control.factory;
import java.util.ArrayList;
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 com.x.base.core.project.exception.ExceptionWhen;
import com.x.okr.assemble.control.AbstractFactory;
import com.x.okr.assemble.control.Business;
import com.x.okr.entity.OkrUserInfo;
import com.x.okr.entity.OkrUserInfo_;
/**
* 类 名:OkrUserInfoFactory<br/>
* 实体类:OkrUserInfo<br/>
* 作 者:Liyi<br/>
* 单 位:O2 Team<br/>
* 日 期:2016-05-20 17:17:26
**/
public class OkrUserInfoFactory extends AbstractFactory {
public OkrUserInfoFactory(Business business) throws Exception {
super(business);
}
//@MethodDescribe( "获取指定Id的OkrUserInfo实体信息对象" )
public OkrUserInfo get( String id ) throws Exception {
return this.entityManagerContainer().find(id, OkrUserInfo.class, ExceptionWhen.none);
}
//@MethodDescribe( "列示全部的OkrUserInfo实体信息列表" )
public List<OkrUserInfo> listAll() throws Exception {
EntityManager em = this.entityManagerContainer().get(OkrUserInfo.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<OkrUserInfo> cq = cb.createQuery(OkrUserInfo.class);
@SuppressWarnings("unused")
Root<OkrUserInfo> root = cq.from( OkrUserInfo.class);
return em.createQuery(cq).getResultList();
}
public List<String> listAllIds() throws Exception {
EntityManager em = this.entityManagerContainer().get(OkrUserInfo.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<OkrUserInfo> root = cq.from( OkrUserInfo.class);
cq.select(root.get(OkrUserInfo_.id) );
return em.createQuery(cq).getResultList();
}
//@MethodDescribe( "列示指定Id的OkrUserInfo实体信息列表" )
public List<OkrUserInfo> list(List<String> ids) throws Exception {
if( ids == null || ids.size() == 0 ){
return new ArrayList<OkrUserInfo>();
}
EntityManager em = this.entityManagerContainer().get(OkrUserInfo.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<OkrUserInfo> cq = cb.createQuery(OkrUserInfo.class);
Root<OkrUserInfo> root = cq.from(OkrUserInfo.class);
Predicate p = root.get(OkrUserInfo_.id).in(ids);
return em.createQuery(cq.where(p)).getResultList();
}
//@MethodDescribe( "列示指定userName的OkrUserInfo实体信息列表" )
public List<OkrUserInfo> listWithPerson( String userName ) throws Exception {
if( userName == null || userName.isEmpty() ){
throw new Exception("username is null!");
}
EntityManager em = this.entityManagerContainer().get(OkrUserInfo.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<OkrUserInfo> cq = cb.createQuery(OkrUserInfo.class);
Root<OkrUserInfo> root = cq.from(OkrUserInfo.class);
Predicate p = cb.equal( root.get(OkrUserInfo_.userName), userName );
return em.createQuery(cq.where(p)).getResultList();
}
}
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册