提交 d1912c0f 编写于 作者: O o2null

Merge branch 'fix/application_codeSafe' into 'wrdp'

applicationServer codeSafe扫描更新

See merge request o2oa/o2oa!4468
...@@ -3,6 +3,6 @@ ...@@ -3,6 +3,6 @@
"pickPersonWithName": false, "pickPersonWithName": false,
"pickIdentityWithName": false, "pickIdentityWithName": false,
"###unitLevelOrderNumberDigits": "unit中unitLevelOrderNumber扩充位数,\u003c\u003d0不扩充.###", "###unitLevelOrderNumberDigits": "unit中unitLevelOrderNumber扩充位数,\u003c\u003d0不扩充.###",
"###pickPersonWithName": "人员识别过程中过程为先查找 distinguishedName 再查找中间的 unique 如果还是没有查找到是否要通过那么进行查找.###", "###pickPersonWithName": "zhangsan@123@P人员识别过程中过程为先查找 distinguishedName 再查找中间的 unique 如果还是没有查找到是否要通过名称进行查找.###",
"###pickIdentityWithName": "身份识别过程中过程为先查找 distinguishedName 再查找中间的 unique 如果还是没有查找到是否要通过那么进行查找.###" "###pickIdentityWithName": "zhangsan@456@I身份识别过程中过程为先查找 distinguishedName 再查找中间的 unique 如果还是没有查找到是否要通过名称进行查找.###"
} }
\ No newline at end of file
...@@ -20,16 +20,21 @@ import org.xml.sax.XMLReader; ...@@ -20,16 +20,21 @@ import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory; import org.xml.sax.helpers.XMLReaderFactory;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
/** /**
* 抽象Excel2007读取器,excel2007的底层数据结构是xml文件,采用SAX的事件驱动的方法解析 * 抽象Excel2007读取器,excel2007的底层数据结构是xml文件,采用SAX的事件驱动的方法解析
* xml,需要继承DefaultHandler,在遇到文件内容时,事件会触发,这种做法可以大大降低 * xml,需要继承DefaultHandler,在遇到文件内容时,事件会触发,这种做法可以大大降低 内存的耗费,特别使用于大数据量的文件。
* 内存的耗费,特别使用于大数据量的文件。
* *
*/ */
public class Excel2007Reader extends DefaultHandler { public class Excel2007Reader extends DefaultHandler {
//共享字符串表
private static Logger logger = LoggerFactory.getLogger(Excel2007Reader.class);
// 共享字符串表
private SharedStringsTable sst; private SharedStringsTable sst;
//上一次的内容 // 上一次的内容
private String lastContents; private String lastContents;
private boolean nextIsString; private boolean nextIsString;
...@@ -37,13 +42,13 @@ public class Excel2007Reader extends DefaultHandler { ...@@ -37,13 +42,13 @@ public class Excel2007Reader extends DefaultHandler {
private int sheetIndex = -1; private int sheetIndex = -1;
private List<String> rowlist = new ArrayList<String>(); private List<String> rowlist = new ArrayList<String>();
//当前行 // 当前行
private int curRow = 0; private int curRow = 0;
//当前列 // 当前列
private int curCol = 0; private int curCol = 0;
//日期标志 // 日期标志
private boolean dateFlag; private boolean dateFlag;
//数字标志 // 数字标志
private boolean numberFlag; private boolean numberFlag;
private boolean isTElement; private boolean isTElement;
...@@ -52,25 +57,27 @@ public class Excel2007Reader extends DefaultHandler { ...@@ -52,25 +57,27 @@ public class Excel2007Reader extends DefaultHandler {
private int startRow; private int startRow;
private IRowReader rowReader; private IRowReader rowReader;
public void setRowReader( IRowReader rowReader, String fileKey, int startRow ){ public void setRowReader(IRowReader rowReader, String fileKey, int startRow) {
this.rowReader = rowReader; this.rowReader = rowReader;
this.fileKey = fileKey; this.fileKey = fileKey;
this.startRow = startRow; this.startRow = startRow;
} }
/**只遍历一个电子表格,其中sheetId为要遍历的sheet索引,从1开始,1-3 /**
* 只遍历一个电子表格,其中sheetId为要遍历的sheet索引,从1开始,1-3
*
* @param filename * @param filename
* @param sheetId * @param sheetId
* @throws Exception * @throws Exception
*/ */
public void processOneSheet(String filename,int sheetId) throws Exception { public void processOneSheet(String filename, int sheetId) throws Exception {
OPCPackage pkg = OPCPackage.open(filename); OPCPackage pkg = OPCPackage.open(filename);
XSSFReader r = new XSSFReader(pkg); XSSFReader r = new XSSFReader(pkg);
SharedStringsTable sst = r.getSharedStringsTable(); SharedStringsTable sst = r.getSharedStringsTable();
XMLReader parser = fetchSheetParser(sst); XMLReader parser = fetchSheetParser(sst);
// 根据 rId# 或 rSheet# 查找sheet // 根据 rId# 或 rSheet# 查找sheet
InputStream sheet2 = r.getSheet("rId"+sheetId); InputStream sheet2 = r.getSheet("rId" + sheetId);
sheetIndex++; sheetIndex++;
InputSource sheetSource = new InputSource(sheet2); InputSource sheetSource = new InputSource(sheet2);
parser.parse(sheetSource); parser.parse(sheetSource);
...@@ -79,11 +86,12 @@ public class Excel2007Reader extends DefaultHandler { ...@@ -79,11 +86,12 @@ public class Excel2007Reader extends DefaultHandler {
/** /**
* 遍历工作簿中所有的电子表格 * 遍历工作簿中所有的电子表格
*
* @param filename * @param filename
* @param fileKey * @param fileKey
* @throws Exception * @throws Exception
*/ */
public void process( String filename ) throws Exception { public void process(String filename) throws Exception {
OPCPackage pkg = OPCPackage.open(filename); OPCPackage pkg = OPCPackage.open(filename);
XSSFReader r = new XSSFReader(pkg); XSSFReader r = new XSSFReader(pkg);
SharedStringsTable sst = r.getSharedStringsTable(); SharedStringsTable sst = r.getSharedStringsTable();
...@@ -94,20 +102,21 @@ public class Excel2007Reader extends DefaultHandler { ...@@ -94,20 +102,21 @@ public class Excel2007Reader extends DefaultHandler {
sheetIndex++; sheetIndex++;
InputStream sheet = sheets.next(); InputStream sheet = sheets.next();
InputSource sheetSource = new InputSource(sheet); InputSource sheetSource = new InputSource(sheet);
parser.parse( sheetSource ); parser.parse(sheetSource);
sheet.close(); sheet.close();
} }
//数据读取完成 // 数据读取完成
} }
/** /**
* 遍历工作簿中所有的电子表格 * 遍历工作簿中所有的电子表格
*
* @param filename * @param filename
* @param fileKey * @param fileKey
* @throws Exception * @throws Exception
*/ */
public void process( InputStream is ) throws Exception { public void process(InputStream is) throws Exception {
OPCPackage pkg = OPCPackage.open( is ); OPCPackage pkg = OPCPackage.open(is);
XSSFReader r = new XSSFReader(pkg); XSSFReader r = new XSSFReader(pkg);
SharedStringsTable sst = r.getSharedStringsTable(); SharedStringsTable sst = r.getSharedStringsTable();
XMLReader parser = fetchSheetParser(sst); XMLReader parser = fetchSheetParser(sst);
...@@ -117,7 +126,7 @@ public class Excel2007Reader extends DefaultHandler { ...@@ -117,7 +126,7 @@ public class Excel2007Reader extends DefaultHandler {
sheetIndex++; sheetIndex++;
InputStream sheet = sheets.next(); InputStream sheet = sheets.next();
InputSource sheetSource = new InputSource(sheet); InputSource sheetSource = new InputSource(sheet);
parser.parse( sheetSource ); parser.parse(sheetSource);
sheet.close(); sheet.close();
} }
} }
...@@ -140,23 +149,23 @@ public class Excel2007Reader extends DefaultHandler { ...@@ -140,23 +149,23 @@ public class Excel2007Reader extends DefaultHandler {
} else { } else {
nextIsString = false; nextIsString = false;
} }
//日期格式 // 日期格式
String cellDateType = attributes.getValue("s"); String cellDateType = attributes.getValue("s");
if ("1".equals(cellDateType)){ if ("1".equals(cellDateType)) {
dateFlag = true; dateFlag = true;
} else { } else {
dateFlag = false; dateFlag = false;
} }
String cellNumberType = attributes.getValue("s"); String cellNumberType = attributes.getValue("s");
if("2".equals(cellNumberType)){ if ("2".equals(cellNumberType)) {
numberFlag = true; numberFlag = true;
} else { } else {
numberFlag = false; numberFlag = false;
} }
} }
//当元素为t时 // 当元素为t时
if("t".equals(name)){ if ("t".equals(name)) {
isTElement = true; isTElement = true;
} else { } else {
isTElement = false; isTElement = false;
...@@ -166,22 +175,20 @@ public class Excel2007Reader extends DefaultHandler { ...@@ -166,22 +175,20 @@ public class Excel2007Reader extends DefaultHandler {
lastContents = ""; lastContents = "";
} }
public void endElement(String uri, String localName, String name) public void endElement(String uri, String localName, String name) throws SAXException {
throws SAXException {
// 根据SST的索引值的到单元格的真正要存储的字符串 // 根据SST的索引值的到单元格的真正要存储的字符串
// 这时characters()方法可能会被调用多次 // 这时characters()方法可能会被调用多次
if (nextIsString) { if (nextIsString) {
try { try {
int idx = Integer.parseInt(lastContents); int idx = Integer.parseInt(lastContents);
lastContents = new XSSFRichTextString(sst.getEntryAt(idx)) lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
.toString();
} catch (Exception e) { } catch (Exception e) {
logger.error(e);
} }
} }
//t元素也包含字符串 // t元素也包含字符串
if(isTElement){ if (isTElement) {
String value = lastContents.trim(); String value = lastContents.trim();
rowlist.add(curCol, value); rowlist.add(curCol, value);
curCol++; curCol++;
...@@ -190,33 +197,33 @@ public class Excel2007Reader extends DefaultHandler { ...@@ -190,33 +197,33 @@ public class Excel2007Reader extends DefaultHandler {
// 将单元格内容加入rowlist中,在这之前先去掉字符串前后的空白符 // 将单元格内容加入rowlist中,在这之前先去掉字符串前后的空白符
} else if ("v".equals(name)) { } else if ("v".equals(name)) {
String value = lastContents.trim(); String value = lastContents.trim();
value = value.equals("")?" ":value; value = value.equals("") ? " " : value;
//日期格式处理 // 日期格式处理
if(dateFlag){ if (dateFlag) {
try{ try {
Date date = HSSFDateUtil.getJavaDate(Double.valueOf(value)); Date date = HSSFDateUtil.getJavaDate(Double.valueOf(value));
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
value = dateFormat.format(date); value = dateFormat.format(date);
}catch(Exception e){ } catch (Exception e) {
logger.error(e);
} }
} }
//数字类型处理 // 数字类型处理
if(numberFlag){ if (numberFlag) {
try{ try {
BigDecimal bd = new BigDecimal(value); BigDecimal bd = new BigDecimal(value);
value = bd.setScale(3,BigDecimal.ROUND_UP).toString(); value = bd.setScale(3, BigDecimal.ROUND_UP).toString();
}catch(Exception e){ } catch (Exception e) {
logger.error(e);
} }
} }
rowlist.add(curCol, value); rowlist.add(curCol, value);
curCol++; curCol++;
}else { } else {
//如果标签名称为 row ,这说明已到行尾,调用 optRows() 方法 // 如果标签名称为 row ,这说明已到行尾,调用 optRows() 方法
if (name.equals("row")) { if (name.equals("row")) {
rowReader.getRows(sheetIndex,curRow,rowlist, this.fileKey, this.startRow ); rowReader.getRows(sheetIndex, curRow, rowlist, this.fileKey, this.startRow);
rowlist.clear(); rowlist.clear();
curRow++; curRow++;
curCol = 0; curCol = 0;
...@@ -225,9 +232,8 @@ public class Excel2007Reader extends DefaultHandler { ...@@ -225,9 +232,8 @@ public class Excel2007Reader extends DefaultHandler {
} }
public void characters(char[] ch, int start, int length) public void characters(char[] ch, int start, int length) throws SAXException {
throws SAXException { // 得到单元格内容的值
//得到单元格内容的值
lastContents += new String(ch, start, length); lastContents += new String(ch, start, length);
} }
} }
...@@ -20,8 +20,7 @@ import org.apache.poi.xssf.usermodel.XSSFSheet; ...@@ -20,8 +20,7 @@ import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/** /**
* 抽象excel2007读入器,先构建.xlsx一张模板,改写模板中的sheet.xml,使用这种方法 * 抽象excel2007读入器,先构建.xlsx一张模板,改写模板中的sheet.xml,使用这种方法 写入.xlsx文件,不需要太大的内存
* 写入.xlsx文件,不需要太大的内存
* *
*/ */
public abstract class AbstractExcel2007Writer { public abstract class AbstractExcel2007Writer {
...@@ -30,10 +29,11 @@ public abstract class AbstractExcel2007Writer { ...@@ -30,10 +29,11 @@ public abstract class AbstractExcel2007Writer {
/** /**
* 写入电子表格的主要流程 * 写入电子表格的主要流程
*
* @param fileName * @param fileName
* @throws Exception * @throws Exception
*/ */
public void process(String fileName) throws Exception{ public void process(String fileName) throws Exception {
// 建立工作簿和电子表格对象 // 建立工作簿和电子表格对象
XSSFWorkbook wb = new XSSFWorkbook(); XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("sheet1"); XSSFSheet sheet = wb.createSheet("sheet1");
...@@ -57,16 +57,17 @@ public abstract class AbstractExcel2007Writer { ...@@ -57,16 +57,17 @@ public abstract class AbstractExcel2007Writer {
FileOutputStream out = new FileOutputStream(fileName); FileOutputStream out = new FileOutputStream(fileName);
substitute(templateFile, tmp, sheetRef.substring(1), out); substitute(templateFile, tmp, sheetRef.substring(1), out);
out.close(); out.close();
//删除文件之前调用一下垃圾回收器,否则无法删除模板文件 // 删除文件之前调用一下垃圾回收器,否则无法删除模板文件
System.gc(); System.gc();
// 删除临时模板文件 // 删除临时模板文件
if (templateFile.isFile()&&templateFile.exists()){ if (templateFile.isFile() && templateFile.exists()) {
templateFile.delete(); templateFile.delete();
} }
} }
/** /**
* 类使用者应该使用此方法进行写操作 * 类使用者应该使用此方法进行写操作
*
* @throws Exception * @throws Exception
*/ */
public abstract void generate() throws Exception; public abstract void generate() throws Exception;
...@@ -99,13 +100,12 @@ public abstract class AbstractExcel2007Writer { ...@@ -99,13 +100,12 @@ public abstract class AbstractExcel2007Writer {
* *
* @param zipfile the template file * @param zipfile the template file
* @param tmpfile the XML file with the sheet data * @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 entry the name of the sheet entry to substitute, e.g.
* xl/worksheets/sheet1.xml
* @param out the stream to write the result to * @param out the stream to write the result to
*/ */
private static void substitute(File zipfile, File tmpfile, String entry, private static void substitute(File zipfile, File tmpfile, String entry, OutputStream out) throws IOException {
OutputStream out) throws IOException { try (ZipFile zip = new ZipFile(zipfile); ZipOutputStream zos = new ZipOutputStream(out)) {
ZipFile zip = new ZipFile(zipfile);
ZipOutputStream zos = new ZipOutputStream(out);
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Enumeration<ZipEntry> en = (Enumeration<ZipEntry>) zip.entries(); Enumeration<ZipEntry> en = (Enumeration<ZipEntry>) zip.entries();
...@@ -119,14 +119,13 @@ public abstract class AbstractExcel2007Writer { ...@@ -119,14 +119,13 @@ public abstract class AbstractExcel2007Writer {
} }
} }
zos.putNextEntry(new ZipEntry(entry)); zos.putNextEntry(new ZipEntry(entry));
InputStream is = new FileInputStream(tmpfile); try (InputStream is = new FileInputStream(tmpfile)) {
copyStream(is, zos); copyStream(is, zos);
is.close(); }
zos.close(); }
} }
private static void copyStream(InputStream in, OutputStream out) private static void copyStream(InputStream in, OutputStream out) throws IOException {
throws IOException {
byte[] chunk = new byte[1024]; byte[] chunk = new byte[1024];
int count; int count;
while ((count = in.read(chunk)) >= 0) { while ((count = in.read(chunk)) >= 0) {
...@@ -150,7 +149,7 @@ public abstract class AbstractExcel2007Writer { ...@@ -150,7 +149,7 @@ public abstract class AbstractExcel2007Writer {
public void beginSheet() throws IOException { public void beginSheet() throws IOException {
_out.write("<?xml version=\"1.0\" encoding=\"GB2312\"?>" _out.write("<?xml version=\"1.0\" encoding=\"GB2312\"?>"
+ "<worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">"); + "<worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">");
_out.write("<sheetData>"+LINE_SEPARATOR); _out.write("<sheetData>" + LINE_SEPARATOR);
} }
public void endSheet() throws IOException { public void endSheet() throws IOException {
...@@ -164,7 +163,7 @@ public abstract class AbstractExcel2007Writer { ...@@ -164,7 +163,7 @@ public abstract class AbstractExcel2007Writer {
* @param rownum 以0开始 * @param rownum 以0开始
*/ */
public void insertRow(int rownum) throws IOException { public void insertRow(int rownum) throws IOException {
_out.write("<row r=\"" + (rownum + 1) + "\">"+LINE_SEPARATOR); _out.write("<row r=\"" + (rownum + 1) + "\">" + LINE_SEPARATOR);
this._rownum = rownum; this._rownum = rownum;
} }
...@@ -172,37 +171,33 @@ public abstract class AbstractExcel2007Writer { ...@@ -172,37 +171,33 @@ public abstract class AbstractExcel2007Writer {
* 插入行结束标志 * 插入行结束标志
*/ */
public void endRow() throws IOException { public void endRow() throws IOException {
_out.write("</row>"+LINE_SEPARATOR); _out.write("</row>" + LINE_SEPARATOR);
} }
/** /**
* 插入新列 * 插入新列
*
* @param columnIndex * @param columnIndex
* @param value * @param value
* @param styleIndex * @param styleIndex
* @throws IOException * @throws IOException
*/ */
public void createCell(int columnIndex, String value, int styleIndex) public void createCell(int columnIndex, String value, int styleIndex) throws IOException {
throws IOException { String ref = new CellReference(_rownum, columnIndex).formatAsString();
String ref = new CellReference(_rownum, columnIndex)
.formatAsString();
_out.write("<c r=\"" + ref + "\" t=\"inlineStr\""); _out.write("<c r=\"" + ref + "\" t=\"inlineStr\"");
if (styleIndex != -1) if (styleIndex != -1)
_out.write(" s=\"" + styleIndex + "\""); _out.write(" s=\"" + styleIndex + "\"");
_out.write(">"); _out.write(">");
_out.write("<is><t>"+XMLEncoder.encode(value)+"</t></is>"); _out.write("<is><t>" + XMLEncoder.encode(value) + "</t></is>");
_out.write("</c>"); _out.write("</c>");
} }
public void createCell(int columnIndex, String value) public void createCell(int columnIndex, String value) throws IOException {
throws IOException {
createCell(columnIndex, value, -1); createCell(columnIndex, value, -1);
} }
public void createCell(int columnIndex, double value, int styleIndex) public void createCell(int columnIndex, double value, int styleIndex) throws IOException {
throws IOException { String ref = new CellReference(_rownum, columnIndex).formatAsString();
String ref = new CellReference(_rownum, columnIndex)
.formatAsString();
_out.write("<c r=\"" + ref + "\" t=\"n\""); _out.write("<c r=\"" + ref + "\" t=\"n\"");
if (styleIndex != -1) if (styleIndex != -1)
_out.write(" s=\"" + styleIndex + "\""); _out.write(" s=\"" + styleIndex + "\"");
...@@ -211,15 +206,12 @@ public abstract class AbstractExcel2007Writer { ...@@ -211,15 +206,12 @@ public abstract class AbstractExcel2007Writer {
_out.write("</c>"); _out.write("</c>");
} }
public void createCell(int columnIndex, double value) public void createCell(int columnIndex, double value) throws IOException {
throws IOException {
createCell(columnIndex, value, -1); createCell(columnIndex, value, -1);
} }
public void createCell(int columnIndex, Calendar value, int styleIndex) public void createCell(int columnIndex, Calendar value, int styleIndex) throws IOException {
throws IOException { createCell(columnIndex, DateUtil.getExcelDate(value, false), styleIndex);
createCell(columnIndex, DateUtil.getExcelDate(value, false),
styleIndex);
} }
} }
} }
\ No newline at end of file
...@@ -18,7 +18,7 @@ public class Excel2003Writer { ...@@ -18,7 +18,7 @@ public class Excel2003Writer {
try{ try{
writeExcel("tes2003.xls"); writeExcel("tes2003.xls");
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace();
} }
} }
......
package com.x.calendar.assemble.control.service; package com.x.calendar.assemble.control.service;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.time.Duration; import java.time.Duration;
...@@ -9,8 +8,6 @@ import java.util.ArrayList; ...@@ -9,8 +8,6 @@ import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import com.x.base.core.project.tools.StringTools;
import com.x.calendar.core.entity.Calendar_EventComment;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import com.x.base.core.container.EntityManagerContainer; import com.x.base.core.container.EntityManagerContainer;
...@@ -23,12 +20,12 @@ import com.x.base.core.project.tools.ListTools; ...@@ -23,12 +20,12 @@ import com.x.base.core.project.tools.ListTools;
import com.x.calendar.assemble.control.Business; import com.x.calendar.assemble.control.Business;
import com.x.calendar.common.date.DateOperation; import com.x.calendar.common.date.DateOperation;
import com.x.calendar.core.entity.Calendar_Event; import com.x.calendar.core.entity.Calendar_Event;
import com.x.calendar.core.entity.Calendar_EventComment;
import com.x.calendar.core.entity.Calendar_EventRepeatMaster; import com.x.calendar.core.entity.Calendar_EventRepeatMaster;
import net.fortuna.ical4j.data.CalendarOutputter; import net.fortuna.ical4j.data.CalendarOutputter;
import net.fortuna.ical4j.model.Calendar; import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.DateTime; import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.Dur;
import net.fortuna.ical4j.model.Recur; import net.fortuna.ical4j.model.Recur;
import net.fortuna.ical4j.model.TimeZone; import net.fortuna.ical4j.model.TimeZone;
import net.fortuna.ical4j.model.TimeZoneRegistry; import net.fortuna.ical4j.model.TimeZoneRegistry;
...@@ -828,12 +825,12 @@ public class Calendar_EventServiceAdv { ...@@ -828,12 +825,12 @@ public class Calendar_EventServiceAdv {
* @throws ValidationException * @throws ValidationException
* @throws IOException * @throws IOException
*/ */
public void writeiCal(Calendar_Event o2_calendar_event, String path) throws ValidationException, IOException { // public void writeiCal(Calendar_Event o2_calendar_event, String path) throws ValidationException, IOException {
Calendar calendar = parseToiCal(o2_calendar_event); // Calendar calendar = parseToiCal(o2_calendar_event);
FileOutputStream fout = new FileOutputStream("D://2.ics"); // FileOutputStream fout = new FileOutputStream("D://2.ics");
CalendarOutputter outputter = new CalendarOutputter(); // CalendarOutputter outputter = new CalendarOutputter();
outputter.output(calendar, fout); // outputter.output(calendar, fout);
} // }
/** /**
* 将一个日程事件写为一个ical文件 * 将一个日程事件写为一个ical文件
...@@ -859,10 +856,11 @@ public class Calendar_EventServiceAdv { ...@@ -859,10 +856,11 @@ public class Calendar_EventServiceAdv {
public String getiCalContent(Calendar_Event o2_calendar_event) throws ValidationException, IOException { public String getiCalContent(Calendar_Event o2_calendar_event) throws ValidationException, IOException {
Calendar calendar = parseToiCal(o2_calendar_event); Calendar calendar = parseToiCal(o2_calendar_event);
CalendarOutputter calendarOutputter = new CalendarOutputter(false); CalendarOutputter calendarOutputter = new CalendarOutputter(false);
ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
calendarOutputter.output(calendar, baos); calendarOutputter.output(calendar, baos);
return new String(baos.toByteArray(), "utf-8"); return new String(baos.toByteArray(), "utf-8");
} }
}
/** /**
* 查询需要提醒的日程事件ID列表 * 查询需要提醒的日程事件ID列表
...@@ -877,8 +875,6 @@ public class Calendar_EventServiceAdv { ...@@ -877,8 +875,6 @@ public class Calendar_EventServiceAdv {
} }
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) { try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
return calendar_EventService.listNeedAlarmEventIds(emc, date); return calendar_EventService.listNeedAlarmEventIds(emc, date);
} catch (Exception e) {
throw e;
} }
} }
...@@ -957,8 +953,6 @@ public class Calendar_EventServiceAdv { ...@@ -957,8 +953,6 @@ public class Calendar_EventServiceAdv {
} }
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) { try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
return calendar_EventService.destoryWithBundle(emc, bundle); return calendar_EventService.destoryWithBundle(emc, bundle);
} catch (Exception e) {
throw e;
} }
} }
...@@ -975,8 +969,6 @@ public class Calendar_EventServiceAdv { ...@@ -975,8 +969,6 @@ public class Calendar_EventServiceAdv {
} }
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) { try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
return emc.find(commentId, Calendar_EventComment.class); return emc.find(commentId, Calendar_EventComment.class);
} catch (Exception e) {
throw e;
} }
} }
} }
...@@ -20,8 +20,7 @@ import org.apache.poi.xssf.usermodel.XSSFSheet; ...@@ -20,8 +20,7 @@ import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/** /**
* 抽象excel2007读入器,先构建.xlsx一张模板,改写模板中的sheet.xml,使用这种方法 * 抽象excel2007读入器,先构建.xlsx一张模板,改写模板中的sheet.xml,使用这种方法 写入.xlsx文件,不需要太大的内存
* 写入.xlsx文件,不需要太大的内存
* *
*/ */
public abstract class AbstractExcel2007Writer { public abstract class AbstractExcel2007Writer {
...@@ -30,81 +29,84 @@ public abstract class AbstractExcel2007Writer { ...@@ -30,81 +29,84 @@ public abstract class AbstractExcel2007Writer {
/** /**
* 写入电子表格的主要流程 * 写入电子表格的主要流程
*
* @param fileName * @param fileName
* @throws Exception * @throws Exception
*/ */
@SuppressWarnings("resource") @SuppressWarnings("resource")
public void process( String fileName ) throws Exception{ public void process(String fileName) throws Exception {
// 建立工作簿和电子表格对象 // 建立工作簿和电子表格对象
XSSFWorkbook wb = new XSSFWorkbook(); XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet( "sheet1" ); XSSFSheet sheet = wb.createSheet("sheet1");
// 持有电子表格数据的xml文件名 例如 /xl/worksheets/sheet1.xml // 持有电子表格数据的xml文件名 例如 /xl/worksheets/sheet1.xml
String sheetRef = sheet.getPackagePart().getPartName().getName(); String sheetRef = sheet.getPackagePart().getPartName().getName();
// 保存模板 // 保存模板
FileOutputStream os = new FileOutputStream( "template.xlsx" ); FileOutputStream os = new FileOutputStream("template.xlsx");
wb.write(os); wb.write(os);
os.close(); os.close();
// 生成xml文件 // 生成xml文件
File tmp = File.createTempFile( "sheet", ".xml" ); File tmp = File.createTempFile("sheet", ".xml");
Writer fw = new FileWriter(tmp); Writer fw = new FileWriter(tmp);
sw = new SpreadsheetWriter(fw); sw = new SpreadsheetWriter(fw);
generate(); generate();
fw.close(); fw.close();
// 使用产生的数据替换模板 // 使用产生的数据替换模板
File templateFile = new File( "template.xlsx" ); File templateFile = new File("template.xlsx");
FileOutputStream out = new FileOutputStream(fileName); FileOutputStream out = new FileOutputStream(fileName);
substitute(templateFile, tmp, sheetRef.substring(1), out); substitute(templateFile, tmp, sheetRef.substring(1), out);
out.close(); out.close();
//删除文件之前调用一下垃圾回收器,否则无法删除模板文件 // 删除文件之前调用一下垃圾回收器,否则无法删除模板文件
System.gc(); System.gc();
// 删除临时模板文件 // 删除临时模板文件
if (templateFile.isFile()&&templateFile.exists()){ if (templateFile.isFile() && templateFile.exists()) {
templateFile.delete(); templateFile.delete();
} }
} }
/** /**
* 写入电子表格的主要流程 * 写入电子表格的主要流程
*
* @param fileName * @param fileName
* @throws Exception * @throws Exception
*/ */
@SuppressWarnings("resource") @SuppressWarnings("resource")
public void process( OutputStream out ) throws Exception{ public void process(OutputStream out) throws Exception {
// 建立工作簿和电子表格对象 // 建立工作簿和电子表格对象
XSSFWorkbook wb = new XSSFWorkbook(); XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet( "sheet1" ); XSSFSheet sheet = wb.createSheet("sheet1");
// 持有电子表格数据的xml文件名 例如 /xl/worksheets/sheet1.xml // 持有电子表格数据的xml文件名 例如 /xl/worksheets/sheet1.xml
String sheetRef = sheet.getPackagePart().getPartName().getName(); String sheetRef = sheet.getPackagePart().getPartName().getName();
// 保存模板 // 保存模板
FileOutputStream os = new FileOutputStream( "template.xlsx" ); FileOutputStream os = new FileOutputStream("template.xlsx");
wb.write(os); wb.write(os);
os.close(); os.close();
// 生成xml文件 // 生成xml文件
File tmp = File.createTempFile( "sheet", ".xml" ); File tmp = File.createTempFile("sheet", ".xml");
Writer fw = new FileWriter(tmp); Writer fw = new FileWriter(tmp);
sw = new SpreadsheetWriter(fw); sw = new SpreadsheetWriter(fw);
generate(); generate();
fw.close(); fw.close();
// 使用产生的数据替换模板 // 使用产生的数据替换模板
File templateFile = new File( "template.xlsx" ); File templateFile = new File("template.xlsx");
substitute(templateFile, tmp, sheetRef.substring(1), out); substitute(templateFile, tmp, sheetRef.substring(1), out);
out.close(); out.close();
//删除文件之前调用一下垃圾回收器,否则无法删除模板文件 // 删除文件之前调用一下垃圾回收器,否则无法删除模板文件
System.gc(); System.gc();
// 删除临时模板文件 // 删除临时模板文件
if (templateFile.isFile()&&templateFile.exists()){ if (templateFile.isFile() && templateFile.exists()) {
templateFile.delete(); templateFile.delete();
} }
} }
/** /**
* 类使用者应该使用此方法进行写操作 * 类使用者应该使用此方法进行写操作
*
* @throws Exception * @throws Exception
*/ */
public abstract void generate() throws Exception; public abstract void generate() throws Exception;
...@@ -137,16 +139,14 @@ public abstract class AbstractExcel2007Writer { ...@@ -137,16 +139,14 @@ public abstract class AbstractExcel2007Writer {
* *
* @param zipfile the template file * @param zipfile the template file
* @param tmpfile the XML file with the sheet data * @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 entry the name of the sheet entry to substitute, e.g.
* xl/worksheets/sheet1.xml
* @param out the stream to write the result to * @param out the stream to write the result to
*/ */
@SuppressWarnings("resource") @SuppressWarnings("resource")
private static void substitute(File zipfile, File tmpfile, String entry, private static void substitute(File zipfile, File tmpfile, String entry, OutputStream out) throws IOException {
OutputStream out) throws IOException { try (ZipFile zip = new ZipFile(zipfile); ZipOutputStream zos = new ZipOutputStream(out)) {
ZipFile zip = new ZipFile(zipfile); @SuppressWarnings("unchecked")
ZipOutputStream zos = new ZipOutputStream(out);
@SuppressWarnings( "unchecked" )
Enumeration<ZipEntry> en = (Enumeration<ZipEntry>) zip.entries(); Enumeration<ZipEntry> en = (Enumeration<ZipEntry>) zip.entries();
while (en.hasMoreElements()) { while (en.hasMoreElements()) {
ZipEntry ze = en.nextElement(); ZipEntry ze = en.nextElement();
...@@ -158,14 +158,13 @@ public abstract class AbstractExcel2007Writer { ...@@ -158,14 +158,13 @@ public abstract class AbstractExcel2007Writer {
} }
} }
zos.putNextEntry(new ZipEntry(entry)); zos.putNextEntry(new ZipEntry(entry));
InputStream is = new FileInputStream(tmpfile); try (InputStream is = new FileInputStream(tmpfile)) {
copyStream(is, zos); copyStream(is, zos);
is.close(); }
zos.close(); }
} }
private static void copyStream(InputStream in, OutputStream out) private static void copyStream(InputStream in, OutputStream out) throws IOException {
throws IOException {
byte[] chunk = new byte[1024]; byte[] chunk = new byte[1024];
int count; int count;
while ((count = in.read(chunk)) >= 0) { while ((count = in.read(chunk)) >= 0) {
...@@ -180,21 +179,21 @@ public abstract class AbstractExcel2007Writer { ...@@ -180,21 +179,21 @@ public abstract class AbstractExcel2007Writer {
public static class SpreadsheetWriter { public static class SpreadsheetWriter {
private final Writer _out; private final Writer _out;
private int _rownum; private int _rownum;
private static String LINE_SEPARATOR = System.getProperty( "line.separator" ); private static String LINE_SEPARATOR = System.getProperty("line.separator");
public SpreadsheetWriter(Writer out) { public SpreadsheetWriter(Writer out) {
_out = out; _out = out;
} }
public void beginSheet() throws IOException { public void beginSheet() throws IOException {
_out.write( "<?xml version=\"1.0\" encoding=\"GB2312\"?>" _out.write("<?xml version=\"1.0\" encoding=\"GB2312\"?>"
+ "<worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">" ); + "<worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">");
_out.write( "<sheetData>"+LINE_SEPARATOR); _out.write("<sheetData>" + LINE_SEPARATOR);
} }
public void endSheet() throws IOException { public void endSheet() throws IOException {
_out.write( "</sheetData>" ); _out.write("</sheetData>");
_out.write( "</worksheet>" ); _out.write("</worksheet>");
} }
/** /**
...@@ -203,7 +202,7 @@ public abstract class AbstractExcel2007Writer { ...@@ -203,7 +202,7 @@ public abstract class AbstractExcel2007Writer {
* @param rownum 以0开始 * @param rownum 以0开始
*/ */
public void insertRow(int rownum) throws IOException { public void insertRow(int rownum) throws IOException {
_out.write( "<row r=\"" + (rownum + 1) + "\">"+LINE_SEPARATOR); _out.write("<row r=\"" + (rownum + 1) + "\">" + LINE_SEPARATOR);
this._rownum = rownum; this._rownum = rownum;
} }
...@@ -211,54 +210,47 @@ public abstract class AbstractExcel2007Writer { ...@@ -211,54 +210,47 @@ public abstract class AbstractExcel2007Writer {
* 插入行结束标志 * 插入行结束标志
*/ */
public void endRow() throws IOException { public void endRow() throws IOException {
_out.write( "</row>"+LINE_SEPARATOR); _out.write("</row>" + LINE_SEPARATOR);
} }
/** /**
* 插入新列 * 插入新列
*
* @param columnIndex * @param columnIndex
* @param value * @param value
* @param styleIndex * @param styleIndex
* @throws IOException * @throws IOException
*/ */
public void createCell(int columnIndex, String value, int styleIndex) public void createCell(int columnIndex, String value, int styleIndex) throws IOException {
throws IOException { String ref = new CellReference(_rownum, columnIndex).formatAsString();
String ref = new CellReference(_rownum, columnIndex) _out.write("<c r=\"" + ref + "\" t=\"inlineStr\"");
.formatAsString();
_out.write( "<c r=\"" + ref + "\" t=\"inlineStr\"" );
if (styleIndex != -1) if (styleIndex != -1)
_out.write( " s=\"" + styleIndex + "\"" ); _out.write(" s=\"" + styleIndex + "\"");
_out.write( ">" ); _out.write(">");
_out.write( "<is><t>"+XMLEncoder.encode(value)+"</t></is>" ); _out.write("<is><t>" + XMLEncoder.encode(value) + "</t></is>");
_out.write( "</c>" ); _out.write("</c>");
} }
public void createCell(int columnIndex, String value) public void createCell(int columnIndex, String value) throws IOException {
throws IOException {
createCell(columnIndex, value, -1); createCell(columnIndex, value, -1);
} }
public void createCell(int columnIndex, double value, int styleIndex) public void createCell(int columnIndex, double value, int styleIndex) throws IOException {
throws IOException { String ref = new CellReference(_rownum, columnIndex).formatAsString();
String ref = new CellReference(_rownum, columnIndex) _out.write("<c r=\"" + ref + "\" t=\"n\"");
.formatAsString();
_out.write( "<c r=\"" + ref + "\" t=\"n\"" );
if (styleIndex != -1) if (styleIndex != -1)
_out.write( " s=\"" + styleIndex + "\"" ); _out.write(" s=\"" + styleIndex + "\"");
_out.write( ">" ); _out.write(">");
_out.write( "<v>" + value + "</v>" ); _out.write("<v>" + value + "</v>");
_out.write( "</c>" ); _out.write("</c>");
} }
public void createCell(int columnIndex, double value) public void createCell(int columnIndex, double value) throws IOException {
throws IOException {
createCell(columnIndex, value, -1); createCell(columnIndex, value, -1);
} }
public void createCell(int columnIndex, Calendar value, int styleIndex) public void createCell(int columnIndex, Calendar value, int styleIndex) throws IOException {
throws IOException { createCell(columnIndex, DateUtil.getExcelDate(value, false), styleIndex);
createCell(columnIndex, DateUtil.getExcelDate(value, false),
styleIndex);
} }
} }
} }
\ No newline at end of file
...@@ -27,16 +27,18 @@ class ActionListPaging extends BaseAction { ...@@ -27,16 +27,18 @@ class ActionListPaging extends BaseAction {
ActionResult<List<Wo>> result = new ActionResult<>(); ActionResult<List<Wo>> result = new ActionResult<>();
EntityManager em = emc.get(AppDict.class); EntityManager em = emc.get(AppDict.class);
CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaBuilder cb = em.getCriteriaBuilder();
Predicate p = cb.conjunction();; Predicate p = cb.conjunction();
;
List<Wo> wos = emc.fetchDescPaging(AppDict.class, Wo.copier, p, page, size, AppDict.sequence_FIELDNAME); List<Wo> wos = emc.fetchDescPaging(AppDict.class, Wo.copier, p, page, size, AppDict.sequence_FIELDNAME);
wos.stream().forEach(wo -> { wos.stream().forEach(wo -> {
try { try {
AppInfo appInfo = emc.find( wo.getAppId(), AppInfo.class ); AppInfo appInfo = emc.find(wo.getAppId(), AppInfo.class);
if(appInfo != null){ if (appInfo != null) {
wo.setAppName(appInfo.getAppName()); wo.setAppName(appInfo.getAppName());
wo.setAppAlias(appInfo.getAppAlias()); wo.setAppAlias(appInfo.getAppAlias());
} }
} catch (Exception e) { } catch (Exception e) {
logger.error(e);
} }
}); });
result.setData(wos); result.setData(wos);
......
package com.x.cms.assemble.control.jaxrs.script; package com.x.cms.assemble.control.jaxrs.script;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Predicate;
import com.x.base.core.container.EntityManagerContainer; import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory; import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.entity.JpaObject; import com.x.base.core.entity.JpaObject;
...@@ -8,16 +14,16 @@ import com.x.base.core.project.bean.WrapCopier; ...@@ -8,16 +14,16 @@ import com.x.base.core.project.bean.WrapCopier;
import com.x.base.core.project.bean.WrapCopierFactory; import com.x.base.core.project.bean.WrapCopierFactory;
import com.x.base.core.project.http.ActionResult; import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson; import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.ListTools; import com.x.base.core.project.tools.ListTools;
import com.x.cms.core.entity.AppInfo; import com.x.cms.core.entity.AppInfo;
import com.x.cms.core.entity.element.Script; import com.x.cms.core.entity.element.Script;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Predicate;
import java.util.List;
class ActionListPaging extends BaseAction { class ActionListPaging extends BaseAction {
private static Logger logger = LoggerFactory.getLogger(ActionListPaging.class);
ActionResult<List<Wo>> execute(EffectivePerson effectivePerson, Integer page, Integer size) throws Exception { ActionResult<List<Wo>> execute(EffectivePerson effectivePerson, Integer page, Integer size) throws Exception {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) { try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<List<Wo>> result = new ActionResult<>(); ActionResult<List<Wo>> result = new ActionResult<>();
...@@ -27,11 +33,12 @@ class ActionListPaging extends BaseAction { ...@@ -27,11 +33,12 @@ class ActionListPaging extends BaseAction {
List<Wo> wos = emc.fetchDescPaging(Script.class, Wo.copier, p, page, size, Script.sequence_FIELDNAME); List<Wo> wos = emc.fetchDescPaging(Script.class, Wo.copier, p, page, size, Script.sequence_FIELDNAME);
wos.stream().forEach(wo -> { wos.stream().forEach(wo -> {
try { try {
AppInfo appInfo = emc.find( wo.getAppId(), AppInfo.class ); AppInfo appInfo = emc.find(wo.getAppId(), AppInfo.class);
if(appInfo != null){ if (appInfo != null) {
wo.setAppName(appInfo.getAppName()); wo.setAppName(appInfo.getAppName());
} }
} catch (Exception e) { } catch (Exception e) {
logger.error(e);
} }
}); });
result.setData(wos); result.setData(wos);
......
...@@ -2,6 +2,8 @@ package com.x.cms.assemble.control.queue; ...@@ -2,6 +2,8 @@ package com.x.cms.assemble.control.queue;
import com.x.base.core.project.x_hotpic_assemble_control; import com.x.base.core.project.x_hotpic_assemble_control;
import com.x.base.core.project.annotation.FieldDescribe; import com.x.base.core.project.annotation.FieldDescribe;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.queue.AbstractQueue; import com.x.base.core.project.queue.AbstractQueue;
import com.x.cms.assemble.control.ThisApplication; import com.x.cms.assemble.control.ThisApplication;
import com.x.cms.core.entity.Document; import com.x.cms.core.entity.Document;
...@@ -12,21 +14,22 @@ import com.x.cms.core.entity.Document; ...@@ -12,21 +14,22 @@ import com.x.cms.core.entity.Document;
*/ */
public class QueueDocumentUpdate extends AbstractQueue<Document> { public class QueueDocumentUpdate extends AbstractQueue<Document> {
public void execute( Document document ) throws Exception { private static Logger logger = LoggerFactory.getLogger(QueueDocumentUpdate.class);
public void execute(Document document) throws Exception {
WrapInHotPictureInfo hotPictureInfo = new WrapInHotPictureInfo(); WrapInHotPictureInfo hotPictureInfo = new WrapInHotPictureInfo();
hotPictureInfo.setApplication( "CMS" ); hotPictureInfo.setApplication("CMS");
hotPictureInfo.setTitle( document.getTitle() ); hotPictureInfo.setTitle(document.getTitle());
hotPictureInfo.setInfoId( document.getId() ); hotPictureInfo.setInfoId(document.getId());
try { try {
ThisApplication.context().applications().postQuery( ThisApplication.context().applications().postQuery(x_hotpic_assemble_control.class, "changeTitle",
x_hotpic_assemble_control.class, "changeTitle", hotPictureInfo hotPictureInfo);
); } catch (Exception e) {
}catch( Exception e ) { logger.error(e);
} }
} }
public static class WrapInHotPictureInfo {
public static class WrapInHotPictureInfo{
@FieldDescribe("应用名称") @FieldDescribe("应用名称")
private String application = ""; private String application = "";
......
...@@ -91,6 +91,7 @@ public class FileUtil { ...@@ -91,6 +91,7 @@ public class FileUtil {
try { try {
is.close(); is.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace();
} }
} }
} }
...@@ -119,6 +120,7 @@ public class FileUtil { ...@@ -119,6 +120,7 @@ public class FileUtil {
try { try {
is.close(); is.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace();
} }
} }
} }
......
...@@ -37,29 +37,29 @@ public class ActiveMQ implements MQInterface { ...@@ -37,29 +37,29 @@ public class ActiveMQ implements MQInterface {
try { try {
MQActive configMQ = Config.mq().getActiveMQ(); MQActive configMQ = Config.mq().getActiveMQ();
logger.info("MqActive initialize....."); logger.info("MqActive initialize.....");
String queueName=configMQ.getQueueName(); String queueName = configMQ.getQueueName();
String url=configMQ.getUrl(); String url = configMQ.getUrl();
url = url.trim(); url = url.trim();
String protocol = url.substring(0, 3); String protocol = url.substring(0, 3);
if(protocol.equalsIgnoreCase("tcp")) { if (protocol.equalsIgnoreCase("tcp")) {
ConnectionFactory factory=new ActiveMQConnectionFactory(url); ConnectionFactory factory = new ActiveMQConnectionFactory(url);
this.connection= factory.createConnection(); this.connection = factory.createConnection();
this.connection.start(); this.connection.start();
this.session= this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE); this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination=session.createQueue(queueName); Destination destination = session.createQueue(queueName);
this.producer = session.createProducer(destination); this.producer = session.createProducer(destination);
}else { } else {
String keyStore = configMQ.getKeyStore(); String keyStore = configMQ.getKeyStore();
String keyStorePassword = configMQ.getKeyStorePassword(); String keyStorePassword = configMQ.getKeyStorePassword();
String trustStore = configMQ.getTrustStore(); String trustStore = configMQ.getTrustStore();
ActiveMQSslConnectionFactory sslConnectionFactory = new ActiveMQSslConnectionFactory(); ActiveMQSslConnectionFactory sslConnectionFactory = new ActiveMQSslConnectionFactory();
sslConnectionFactory.setBrokerURL(url); sslConnectionFactory.setBrokerURL(url);
sslConnectionFactory.setKeyAndTrustManagers(this.loadKeyManager(keyStore, keyStorePassword), this.loadTrustManager(trustStore), sslConnectionFactory.setKeyAndTrustManagers(this.loadKeyManager(keyStore, keyStorePassword),
new java.security.SecureRandom()); this.loadTrustManager(trustStore), new java.security.SecureRandom());
this.connection = sslConnectionFactory.createConnection(); this.connection = sslConnectionFactory.createConnection();
this.connection.start(); this.connection.start();
...@@ -75,16 +75,14 @@ public class ActiveMQ implements MQInterface { ...@@ -75,16 +75,14 @@ public class ActiveMQ implements MQInterface {
} }
private static class MQHolder{ private static class MQHolder {
private static ActiveMQ instance = new ActiveMQ(); private static ActiveMQ instance = new ActiveMQ();
} }
public static ActiveMQ getInstance() {
public static ActiveMQ getInstance(){
return MQHolder.instance; return MQHolder.instance;
} }
public static void main(String[] args) { public static void main(String[] args) {
ActiveMQ MQClient = getInstance(); ActiveMQ MQClient = getInstance();
Message msg = new Message(); Message msg = new Message();
...@@ -100,7 +98,7 @@ public class ActiveMQ implements MQInterface { ...@@ -100,7 +98,7 @@ public class ActiveMQ implements MQInterface {
try { try {
Gson gson = new Gson(); Gson gson = new Gson();
String msg = gson.toJson(message); String msg = gson.toJson(message);
TextMessage textMessage= this.session.createTextMessage(msg); TextMessage textMessage = this.session.createTextMessage(msg);
this.producer.send(textMessage); this.producer.send(textMessage);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
...@@ -122,9 +120,9 @@ public class ActiveMQ implements MQInterface { ...@@ -122,9 +120,9 @@ public class ActiveMQ implements MQInterface {
} }
} }
/** /**
* 加载证书文件 * 加载证书文件
*
* @param trustStore * @param trustStore
* @return * @return
* @throws java.security.NoSuchAlgorithmException * @throws java.security.NoSuchAlgorithmException
...@@ -132,17 +130,20 @@ public class ActiveMQ implements MQInterface { ...@@ -132,17 +130,20 @@ public class ActiveMQ implements MQInterface {
* @throws java.io.IOException * @throws java.io.IOException
* @throws java.security.GeneralSecurityException * @throws java.security.GeneralSecurityException
*/ */
public static TrustManager[] loadTrustManager(String trustStore) throws java.security.NoSuchAlgorithmException, java.security.KeyStoreException, public static TrustManager[] loadTrustManager(String trustStore) throws java.security.NoSuchAlgorithmException,
java.io.IOException, java.security.GeneralSecurityException { java.security.KeyStoreException, java.io.IOException, java.security.GeneralSecurityException {
KeyStore ks = KeyStore. getInstance("JKS"); KeyStore ks = KeyStore.getInstance("JKS");
ks.load( new FileInputStream(trustStore), null); try (FileInputStream fis = new FileInputStream(trustStore)) {
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory. getDefaultAlgorithm()); ks.load(fis, null);
}
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks); tmf.init(ks);
return tmf.getTrustManagers(); return tmf.getTrustManagers();
} }
/** /**
* 加载密钥文件 * 加载密钥文件
*
* @param keyStore * @param keyStore
* @param keyStorePassword * @param keyStorePassword
* @return * @return
...@@ -153,12 +154,13 @@ public class ActiveMQ implements MQInterface { ...@@ -153,12 +154,13 @@ public class ActiveMQ implements MQInterface {
* @throws java.io.IOException * @throws java.io.IOException
* @throws java.security.UnrecoverableKeyException * @throws java.security.UnrecoverableKeyException
*/ */
public static KeyManager[] loadKeyManager(String keyStore, String keyStorePassword) throws java.security.NoSuchAlgorithmException, public static KeyManager[] loadKeyManager(String keyStore, String keyStorePassword)
java.security.KeyStoreException, java.security.GeneralSecurityException, java.security.cert.CertificateException, java.io.IOException, throws java.security.NoSuchAlgorithmException, java.security.KeyStoreException,
java.security.GeneralSecurityException, java.security.cert.CertificateException, java.io.IOException,
java.security.UnrecoverableKeyException { java.security.UnrecoverableKeyException {
KeyStore ks = KeyStore. getInstance("JKS"); KeyStore ks = KeyStore.getInstance("JKS");
ks.load( new FileInputStream(keyStore), keyStorePassword.toCharArray()); ks.load(new FileInputStream(keyStore), keyStorePassword.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory. getDefaultAlgorithm()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, keyStorePassword.toCharArray()); kmf.init(ks, keyStorePassword.toCharArray());
return kmf.getKeyManagers(); return kmf.getKeyManagers();
} }
......
package com.x.organization.assemble.authentication.jaxrs.authentication; package com.x.organization.assemble.authentication.jaxrs.authentication;
import java.util.*; import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Collectors; import java.util.stream.Collectors;
...@@ -8,6 +11,9 @@ import java.util.stream.Collectors; ...@@ -8,6 +11,9 @@ import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import com.x.base.core.entity.JpaObject; import com.x.base.core.entity.JpaObject;
import com.x.base.core.project.annotation.FieldDescribe; import com.x.base.core.project.annotation.FieldDescribe;
import com.x.base.core.project.bean.NameValuePair; import com.x.base.core.project.bean.NameValuePair;
...@@ -30,9 +36,6 @@ import com.x.organization.assemble.authentication.wrapout.WrapOutAuthentication; ...@@ -30,9 +36,6 @@ import com.x.organization.assemble.authentication.wrapout.WrapOutAuthentication;
import com.x.organization.core.entity.Identity; import com.x.organization.core.entity.Identity;
import com.x.organization.core.entity.Person; import com.x.organization.core.entity.Person;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
abstract class BaseAction extends StandardJaxrsAction { abstract class BaseAction extends StandardJaxrsAction {
private static Logger logger = LoggerFactory.getLogger(BaseAction.class); private static Logger logger = LoggerFactory.getLogger(BaseAction.class);
...@@ -71,7 +74,7 @@ abstract class BaseAction extends StandardJaxrsAction { ...@@ -71,7 +74,7 @@ abstract class BaseAction extends StandardJaxrsAction {
EffectivePerson effectivePerson = new EffectivePerson(person.getDistinguishedName(), tokenType, EffectivePerson effectivePerson = new EffectivePerson(person.getDistinguishedName(), tokenType,
Config.token().getCipher()); Config.token().getCipher());
if ((null != request) && (null != response)) { if ((null != request) && (null != response)) {
if(!isMoaTerminal(request)) { if (!isMoaTerminal(request)) {
String clientIp = HttpToken.remoteAddress(request); String clientIp = HttpToken.remoteAddress(request);
logger.debug("{} client ip is : {}", person.getDistinguishedName(), clientIp); logger.debug("{} client ip is : {}", person.getDistinguishedName(), clientIp);
if (!this.checkIp(clientIp, person.getIpAddress())) { if (!this.checkIp(clientIp, person.getIpAddress())) {
...@@ -164,9 +167,12 @@ abstract class BaseAction extends StandardJaxrsAction { ...@@ -164,9 +167,12 @@ abstract class BaseAction extends StandardJaxrsAction {
} }
} }
// private List<String> listRole(Business business, String personId) throws Exception { // private List<String> listRole(Business business, String personId) throws
// Exception {
// List<String> roles = new ArrayList<>(); // List<String> roles = new ArrayList<>();
// for (Role o : business.entityManagerContainer().fetch(business.role().listWithPerson(personId), Role.class, // for (Role o :
// business.entityManagerContainer().fetch(business.role().listWithPerson(personId),
// Role.class,
// ListTools.toList(Role.DISTINGUISHEDNAME))) { // ListTools.toList(Role.DISTINGUISHEDNAME))) {
// roles.add(o.getDistinguishedName()); // roles.add(o.getDistinguishedName());
// } // }
...@@ -209,10 +215,10 @@ abstract class BaseAction extends StandardJaxrsAction { ...@@ -209,10 +215,10 @@ abstract class BaseAction extends StandardJaxrsAction {
logger.debug("token post parameter:{}.", parameter); logger.debug("token post parameter:{}.", parameter);
List<NameValuePair> heads = null; List<NameValuePair> heads = null;
//if (StringUtils.equalsIgnoreCase(oauthClient.getTokenType(), "form")) { // if (StringUtils.equalsIgnoreCase(oauthClient.getTokenType(), "form")) {
heads = new ArrayList<>(); heads = new ArrayList<>();
heads.add(new NameValuePair("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")); heads.add(new NameValuePair("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"));
//} // }
String str = HttpConnection.postAsString(address, heads, parameter); String str = HttpConnection.postAsString(address, heads, parameter);
return str; return str;
...@@ -289,57 +295,59 @@ abstract class BaseAction extends StandardJaxrsAction { ...@@ -289,57 +295,59 @@ abstract class BaseAction extends StandardJaxrsAction {
} }
} }
protected boolean checkIp(String clientIp, String ipAddress){ protected boolean checkIp(String clientIp, String ipAddress) {
boolean returnValue = true; boolean returnValue = true;
if(StringUtils.isNotEmpty(clientIp) && StringUtils.isNotEmpty(ipAddress)){ if (StringUtils.isNotEmpty(clientIp) && StringUtils.isNotEmpty(ipAddress)) {
try { try {
String[] ipAddressArr = StringUtils.split(ipAddress, ","); String[] ipAddressArr = StringUtils.split(ipAddress, ",");
for (String regIp : ipAddressArr) { for (String regIp : ipAddressArr) {
if(StringUtils.isNotEmpty(regIp)) { if (StringUtils.isNotEmpty(regIp)) {
Pattern pattern = Pattern.compile(regIp.trim()); Pattern pattern = Pattern.compile(regIp.trim());
Matcher matcher = pattern.matcher(clientIp); Matcher matcher = pattern.matcher(clientIp);
returnValue = matcher.find(); returnValue = matcher.find();
if(returnValue){ if (returnValue) {
break; break;
} }
} }
} }
} catch (Exception e) { } catch (Exception e) {
logger.error(e);
} }
} }
return returnValue; return returnValue;
} }
protected boolean isMoaTerminal(HttpServletRequest request){ protected boolean isMoaTerminal(HttpServletRequest request) {
String xClient = request.getHeader("x-client"); String xClient = request.getHeader("x-client");
if(StringUtils.isNotBlank(xClient)){ if (StringUtils.isNotBlank(xClient)) {
xClient = xClient.toLowerCase(); xClient = xClient.toLowerCase();
if (xClient.indexOf("android") != -1) { if (xClient.indexOf("android") != -1) {
//安卓 // 安卓
return true; return true;
} }
if (xClient.indexOf("ios") != -1) { if (xClient.indexOf("ios") != -1) {
//安卓 // 安卓
return true; return true;
} }
} }
String userAgent = request.getHeader("User-Agent"); String userAgent = request.getHeader("User-Agent");
if(StringUtils.isNotBlank(userAgent)) { if (StringUtils.isNotBlank(userAgent)) {
userAgent = userAgent.toLowerCase(); userAgent = userAgent.toLowerCase();
if (userAgent.indexOf("micromessenger") != -1) { if (userAgent.indexOf("micromessenger") != -1) {
//微信 // 微信
return true; return true;
} }
if (userAgent.indexOf("dingtalk") != -1) { if (userAgent.indexOf("dingtalk") != -1) {
//钉钉 // 钉钉
return true; return true;
} }
if (userAgent.indexOf("android") != -1) { if (userAgent.indexOf("android") != -1) {
//安卓 // 安卓
return true; return true;
} }
if (userAgent.indexOf("iphone") != -1 || userAgent.indexOf("ipad") != -1 || userAgent.indexOf("ipod") != -1) { if (userAgent.indexOf("iphone") != -1 || userAgent.indexOf("ipad") != -1
//苹果 || userAgent.indexOf("ipod") != -1) {
// 苹果
return true; return true;
} }
} }
......
...@@ -6,7 +6,6 @@ import javax.ws.rs.ApplicationPath; ...@@ -6,7 +6,6 @@ import javax.ws.rs.ApplicationPath;
import com.x.base.core.project.jaxrs.AbstractActionApplication; import com.x.base.core.project.jaxrs.AbstractActionApplication;
import com.x.organization.assemble.control.jaxrs.export.ExportAction; import com.x.organization.assemble.control.jaxrs.export.ExportAction;
import com.x.organization.assemble.control.jaxrs.function.FunctionAction;
import com.x.organization.assemble.control.jaxrs.group.GroupAction; import com.x.organization.assemble.control.jaxrs.group.GroupAction;
import com.x.organization.assemble.control.jaxrs.identity.IdentityAction; import com.x.organization.assemble.control.jaxrs.identity.IdentityAction;
import com.x.organization.assemble.control.jaxrs.inputperson.InputPersonAction; import com.x.organization.assemble.control.jaxrs.inputperson.InputPersonAction;
...@@ -29,7 +28,7 @@ public class ActionApplication extends AbstractActionApplication { ...@@ -29,7 +28,7 @@ public class ActionApplication extends AbstractActionApplication {
classes.add(IdentityAction.class); classes.add(IdentityAction.class);
classes.add(GroupAction.class); classes.add(GroupAction.class);
classes.add(RoleAction.class); classes.add(RoleAction.class);
classes.add(FunctionAction.class); // classes.add(FunctionAction.class);
classes.add(LoginRecordAction.class); classes.add(LoginRecordAction.class);
classes.add(InputPersonAction.class); classes.add(InputPersonAction.class);
classes.add(UnitAction.class); classes.add(UnitAction.class);
......
package com.x.organization.assemble.control.jaxrs.function; //package com.x.organization.assemble.control.jaxrs.function;
//
import java.util.List; //import java.util.List;
import java.util.Objects; //import java.util.Objects;
//
import javax.persistence.EntityManager; //import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder; //import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; //import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root; //import javax.persistence.criteria.Root;
//
import org.apache.commons.beanutils.PropertyUtils; //import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils; //import org.apache.commons.lang3.StringUtils;
//
import com.x.base.core.container.EntityManagerContainer; //import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory; //import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.project.config.Config; //import com.x.base.core.project.config.Config;
import com.x.base.core.project.http.ActionResult; //import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.WrapOutCount; //import com.x.base.core.project.http.WrapOutCount;
import com.x.base.core.project.tools.Crypto; //import com.x.base.core.project.tools.Crypto;
import com.x.organization.core.entity.Person; //import com.x.organization.core.entity.Person;
//
public class ActionCreatePassword { //public class ActionCreatePassword {
//
protected ActionResult<WrapOutCount> execute(String attribute) throws Exception { // protected ActionResult<WrapOutCount> execute(String attribute) throws Exception {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) { // try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<WrapOutCount> result = new ActionResult<>(); // ActionResult<WrapOutCount> result = new ActionResult<>();
if (!StringUtils.equals(attribute, "password")) { // if (!StringUtils.equals(attribute, "password")) {
EntityManager em = emc.beginTransaction(Person.class); // EntityManager em = emc.beginTransaction(Person.class);
CriteriaBuilder cb = em.getCriteriaBuilder(); // CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Person> cq = cb.createQuery(Person.class); // CriteriaQuery<Person> cq = cb.createQuery(Person.class);
Root<Person> root = cq.from(Person.class); // Root<Person> root = cq.from(Person.class);
cq.select(root); // cq.select(root);
List<Person> list = em.createQuery(cq).getResultList(); // List<Person> list = em.createQuery(cq).getResultList();
for (Person o : list) { // for (Person o : list) {
Object obj = PropertyUtils.getProperty(o, attribute); // Object obj = PropertyUtils.getProperty(o, attribute);
if (null == obj) { // if (null == obj) {
throw new Exception("person{name:" + o.getName() + "} can not create password."); // throw new Exception("person{name:" + o.getName() + "} can not create password.");
} // }
String str = Objects.toString(obj); // String str = Objects.toString(obj);
if (StringUtils.isEmpty(str)) { // if (StringUtils.isEmpty(str)) {
throw new Exception("person{name:" + o.getName() + "} can not create empty password."); // throw new Exception("person{name:" + o.getName() + "} can not create empty password.");
} // }
String value = Crypto.encrypt(str, Config.token().getKey()); // String value = Crypto.encrypt(str, Config.token().getKey());
PropertyUtils.setProperty(o, "password", value); // PropertyUtils.setProperty(o, "password", value);
} // }
emc.commit(); // emc.commit();
WrapOutCount wrap = new WrapOutCount(); // WrapOutCount wrap = new WrapOutCount();
wrap.setCount(list.size()); // wrap.setCount(list.size());
result.setData(wrap); // result.setData(wrap);
} // }
return result; // return result;
} // }
} // }
//
} //}
package com.x.organization.assemble.control.jaxrs.function; //package com.x.organization.assemble.control.jaxrs.function;
//
import java.util.ArrayList; //import java.util.ArrayList;
import java.util.List; //import java.util.List;
//
import javax.persistence.EntityManager; //import javax.persistence.EntityManager;
import javax.persistence.Tuple; //import javax.persistence.Tuple;
import javax.persistence.criteria.CriteriaBuilder; //import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; //import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root; //import javax.persistence.criteria.Root;
import javax.persistence.criteria.Selection; //import javax.persistence.criteria.Selection;
//
import com.x.base.core.container.EntityManagerContainer; //import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.project.http.WrapInStringList; //import com.x.base.core.project.http.WrapInStringList;
import com.x.organization.assemble.control.Business; //import com.x.organization.assemble.control.Business;
import com.x.organization.core.entity.Person; //import com.x.organization.core.entity.Person;
//
public class ActionListAllPersonName { //public class ActionListAllPersonName {
//
protected List<Tuple> execute(Business business, WrapInStringList wrapIn) throws Exception { // protected List<Tuple> execute(Business business, WrapInStringList wrapIn) throws Exception {
EntityManagerContainer emc = business.entityManagerContainer(); // EntityManagerContainer emc = business.entityManagerContainer();
EntityManager em = emc.get(Person.class); // EntityManager em = emc.get(Person.class);
CriteriaBuilder cb = em.getCriteriaBuilder(); // CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createQuery(Tuple.class); // CriteriaQuery<Tuple> cq = cb.createQuery(Tuple.class);
Root<Person> root = cq.from(Person.class); // Root<Person> root = cq.from(Person.class);
List<Selection<?>> selections = new ArrayList<>(); // List<Selection<?>> selections = new ArrayList<>();
for (String str : wrapIn.getValueList()) { // for (String str : wrapIn.getValueList()) {
selections.add(root.get(str)); // selections.add(root.get(str));
} // }
cq.multiselect(selections); // cq.multiselect(selections);
List<Tuple> wraps = em.createQuery(cq).getResultList(); // List<Tuple> wraps = em.createQuery(cq).getResultList();
return wraps; // return wraps;
} // }
//
} //}
package com.x.organization.assemble.control.jaxrs.function; //package com.x.organization.assemble.control.jaxrs.function;
//
import com.x.base.core.project.cache.CacheManager; //import com.x.base.core.project.cache.CacheManager;
import org.apache.commons.lang3.StringUtils; //import org.apache.commons.lang3.StringUtils;
//
import com.x.base.core.container.EntityManagerContainer; //import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.entity.annotation.CheckPersistType; //import com.x.base.core.entity.annotation.CheckPersistType;
import com.x.base.core.project.cache.ApplicationCache; //import com.x.base.core.project.cache.ApplicationCache;
import com.x.base.core.project.exception.ExceptionWhen; //import com.x.base.core.project.exception.ExceptionWhen;
import com.x.base.core.project.http.WrapInString; //import com.x.base.core.project.http.WrapInString;
import com.x.base.core.project.http.WrapOutId; //import com.x.base.core.project.http.WrapOutId;
import com.x.organization.assemble.control.Business; //import com.x.organization.assemble.control.Business;
import com.x.organization.core.entity.Person; //import com.x.organization.core.entity.Person;
//
public class ActionSetPassword { //public class ActionSetPassword {
//
protected WrapOutId execute(Business business, String name, WrapInString wrapIn) throws Exception { // protected WrapOutId execute(Business business, String name, WrapInString wrapIn) throws Exception {
EntityManagerContainer emc = business.entityManagerContainer(); // EntityManagerContainer emc = business.entityManagerContainer();
String personId = business.person().getWithName(name, null); // String personId = business.person().getWithName(name, null);
if (StringUtils.isEmpty(personId)) { // if (StringUtils.isEmpty(personId)) {
personId = business.person().getWithUnique(name, null); // personId = business.person().getWithUnique(name, null);
} // }
if (StringUtils.isEmpty(personId)) { // if (StringUtils.isEmpty(personId)) {
throw new Exception("can not find person:" + name); // throw new Exception("can not find person:" + name);
} else { // } else {
if (StringUtils.isEmpty(wrapIn.getValue())) { // if (StringUtils.isEmpty(wrapIn.getValue())) {
throw new Exception("new password is empty"); // throw new Exception("new password is empty");
} // }
Person person = emc.find(personId, Person.class, ExceptionWhen.not_found); // Person person = emc.find(personId, Person.class, ExceptionWhen.not_found);
emc.beginTransaction(Person.class); // emc.beginTransaction(Person.class);
business.person().setPassword(person, wrapIn.getValue(),false); // business.person().setPassword(person, wrapIn.getValue(),false);
emc.check(person, CheckPersistType.all); // emc.check(person, CheckPersistType.all);
emc.commit(); // emc.commit();
CacheManager.notify(Person.class); // CacheManager.notify(Person.class);
WrapOutId wrap = new WrapOutId(person.getId()); // WrapOutId wrap = new WrapOutId(person.getId());
return wrap; // return wrap;
} // }
} // }
//
} //}
package com.x.organization.assemble.control.jaxrs.function; //package com.x.organization.assemble.control.jaxrs.function;
//
import java.util.List; //import java.util.List;
//
import javax.persistence.EntityManager; //import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder; //import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; //import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root; //import javax.persistence.criteria.Root;
//
import org.apache.commons.beanutils.PropertyUtils; //import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils; //import org.apache.commons.lang3.StringUtils;
//
import com.x.base.core.container.EntityManagerContainer; //import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory; //import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.project.http.ActionResult; //import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.WrapOutCount; //import com.x.base.core.project.http.WrapOutCount;
import com.x.base.core.project.tools.Crypto; //import com.x.base.core.project.tools.Crypto;
import com.x.organization.core.entity.Person; //import com.x.organization.core.entity.Person;
//
public class ActionSetText { //public class ActionSetText {
//
protected ActionResult<WrapOutCount> execute(String attribute, String key) throws Exception { // protected ActionResult<WrapOutCount> execute(String attribute, String key) throws Exception {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) { // try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<WrapOutCount> result = new ActionResult<>(); // ActionResult<WrapOutCount> result = new ActionResult<>();
if (!StringUtils.equals(attribute, "password")) { // if (!StringUtils.equals(attribute, "password")) {
EntityManager em = emc.beginTransaction(Person.class); // EntityManager em = emc.beginTransaction(Person.class);
CriteriaBuilder cb = em.getCriteriaBuilder(); // CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Person> cq = cb.createQuery(Person.class); // CriteriaQuery<Person> cq = cb.createQuery(Person.class);
Root<Person> root = cq.from(Person.class); // Root<Person> root = cq.from(Person.class);
cq.select(root); // cq.select(root);
List<Person> list = em.createQuery(cq).getResultList(); // List<Person> list = em.createQuery(cq).getResultList();
for (Person o : list) { // for (Person o : list) {
String value = Crypto.decrypt(o.getPassword(), key); // String value = Crypto.decrypt(o.getPassword(), key);
PropertyUtils.setProperty(o, attribute, value); // PropertyUtils.setProperty(o, attribute, value);
} // }
emc.commit(); // emc.commit();
WrapOutCount wrap = new WrapOutCount(); // WrapOutCount wrap = new WrapOutCount();
wrap.setCount(list.size()); // wrap.setCount(list.size());
result.setData(wrap); // result.setData(wrap);
} // }
return result; // return result;
} // }
} // }
//
} //}
...@@ -65,9 +65,6 @@ class ActionChangePassword extends ActionBase { ...@@ -65,9 +65,6 @@ class ActionChangePassword extends ActionBase {
throw new ExceptionInvalidPassword(Config.person().getPasswordRegexHint()); throw new ExceptionInvalidPassword(Config.person().getPasswordRegexHint());
} }
// if (PasswordTools.checkPasswordStrength(wi.getNewPassword()) < 4) {
// throw new ExceptionInvalidPassword();
// }
} }
emc.beginTransaction(Person.class); emc.beginTransaction(Person.class);
business.person().setPassword(person, wi.getNewPassword()); business.person().setPassword(person, wi.getNewPassword());
......
...@@ -53,22 +53,14 @@ class ActionSetPassword extends BaseAction { ...@@ -53,22 +53,14 @@ class ActionSetPassword extends BaseAction {
if (StringUtils.isEmpty(wi.getConfirmPassword())) { if (StringUtils.isEmpty(wi.getConfirmPassword())) {
throw new ExceptionConfirmPasswordEmpty(); throw new ExceptionConfirmPasswordEmpty();
} }
/*
if (!StringUtils.equals(wi.getNewPassword(), wi.getConfirmPassword())) {
throw new ExceptionTwicePasswordNotMatch();
}
if (StringUtils.equals(wi.getNewPassword(), wi.getOldPassword())) {
throw new ExceptionNewPasswordSameAsOldPassword();
}*/
String oldPassword = wi.getOldPassword(); String oldPassword = wi.getOldPassword();
String newPassword = wi.getNewPassword(); String newPassword = wi.getNewPassword();
String confirmPassword = wi.getConfirmPassword(); String confirmPassword = wi.getConfirmPassword();
String isEncrypted = wi.getIsEncrypted(); String isEncrypted = wi.getIsEncrypted();
//RSA解秘
if (!StringUtils.isEmpty(isEncrypted)) { if (!StringUtils.isEmpty(isEncrypted)) {
if(isEncrypted.trim().equalsIgnoreCase("y")) { if (isEncrypted.trim().equalsIgnoreCase("y")) {
oldPassword = this.decryptRSA(oldPassword); oldPassword = this.decryptRSA(oldPassword);
newPassword = this.decryptRSA(newPassword); newPassword = this.decryptRSA(newPassword);
confirmPassword = this.decryptRSA(confirmPassword); confirmPassword = this.decryptRSA(confirmPassword);
...@@ -82,7 +74,6 @@ class ActionSetPassword extends BaseAction { ...@@ -82,7 +74,6 @@ class ActionSetPassword extends BaseAction {
throw new ExceptionNewPasswordSameAsOldPassword(); throw new ExceptionNewPasswordSameAsOldPassword();
} }
if (BooleanUtils.isTrue(Config.person().getSuperPermission()) if (BooleanUtils.isTrue(Config.person().getSuperPermission())
&& StringUtils.equals(Config.token().getPassword(), oldPassword)) { && StringUtils.equals(Config.token().getPassword(), oldPassword)) {
logger.info("user{name:" + person.getName() + "} use superPermission."); logger.info("user{name:" + person.getName() + "} use superPermission.");
...@@ -96,7 +87,6 @@ class ActionSetPassword extends BaseAction { ...@@ -96,7 +87,6 @@ class ActionSetPassword extends BaseAction {
} }
} }
emc.beginTransaction(Person.class); emc.beginTransaction(Person.class);
business.person().setPassword(person, newPassword); business.person().setPassword(person, newPassword);
emc.commit(); emc.commit();
...@@ -110,7 +100,6 @@ class ActionSetPassword extends BaseAction { ...@@ -110,7 +100,6 @@ class ActionSetPassword extends BaseAction {
} }
} }
public String decryptRSA(String strDecrypt) { public String decryptRSA(String strDecrypt) {
String privateKey; String privateKey;
String decrypt = null; String decrypt = null;
...@@ -137,6 +126,8 @@ class ActionSetPassword extends BaseAction { ...@@ -137,6 +126,8 @@ class ActionSetPassword extends BaseAction {
public static class Wi extends GsonPropertyObject { public static class Wi extends GsonPropertyObject {
private static final long serialVersionUID = 1L;
@FieldDescribe("原密码") @FieldDescribe("原密码")
private String oldPassword; private String oldPassword;
......
...@@ -30,7 +30,7 @@ class ActionCreate extends BaseAction { ...@@ -30,7 +30,7 @@ class ActionCreate extends BaseAction {
Wi wi = this.convertToWrapIn(jsonElement, Wi.class); Wi wi = this.convertToWrapIn(jsonElement, Wi.class);
Business business = new Business(emc); Business business = new Business(emc);
String name = wi.getName(); String name = wi.getName();
String password = wi.getPassword(); String passwd = wi.getPassword();
String mobile = wi.getMobile(); String mobile = wi.getMobile();
GenderType genderType = wi.getGenderType(); GenderType genderType = wi.getGenderType();
String codeAnswer = wi.getCodeAnswer(); String codeAnswer = wi.getCodeAnswer();
...@@ -61,12 +61,9 @@ class ActionCreate extends BaseAction { ...@@ -61,12 +61,9 @@ class ActionCreate extends BaseAction {
throw new ExceptionMailExist(mail); throw new ExceptionMailExist(mail);
} }
} }
if (!password.matches(Config.person().getPasswordRegex())) { if (!passwd.matches(Config.person().getPasswordRegex())) {
throw new ExceptionInvalidPassword(Config.person().getPasswordRegexHint()); throw new ExceptionInvalidPassword(Config.person().getPasswordRegexHint());
} }
// if (PasswordTools.checkPasswordStrength(password) < 4) {
// throw new ExceptionInvalidPassword();
// }
if (null == genderType) { if (null == genderType) {
throw new ExceptionInvalidGenderType(); throw new ExceptionInvalidGenderType();
} }
...@@ -82,7 +79,7 @@ class ActionCreate extends BaseAction { ...@@ -82,7 +79,7 @@ class ActionCreate extends BaseAction {
throw new ExceptionInvalidCaptcha(); throw new ExceptionInvalidCaptcha();
} }
} }
this.register(business, name, password, genderType, mobile, mail); this.register(business, name, passwd, genderType, mobile, mail);
Wo wo = new Wo(); Wo wo = new Wo();
wo.setValue(true); wo.setValue(true);
result.setData(wo); result.setData(wo);
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册