diff --git a/o2server/x_attendance_assemble_control/src/main/java/com/x/attendance/assemble/control/factory/AttendanceSelfHolidayFactory.java b/o2server/x_attendance_assemble_control/src/main/java/com/x/attendance/assemble/control/factory/AttendanceSelfHolidayFactory.java index c04786efe74c077696a87600a497be91492ce6f5..04ac4d2173dd7321fb558a200b2960bd5fa2105f 100644 --- a/o2server/x_attendance_assemble_control/src/main/java/com/x/attendance/assemble/control/factory/AttendanceSelfHolidayFactory.java +++ b/o2server/x_attendance_assemble_control/src/main/java/com/x/attendance/assemble/control/factory/AttendanceSelfHolidayFactory.java @@ -20,80 +20,85 @@ import com.x.attendance.assemble.control.jaxrs.selfholiday.WrapInFilter; import com.x.attendance.entity.AttendanceSelfHoliday; import com.x.attendance.entity.AttendanceSelfHoliday_; import com.x.base.core.project.exception.ExceptionWhen; +import com.x.base.core.project.logger.Logger; +import com.x.base.core.project.logger.LoggerFactory; + /** * 系统配置信息表基础功能服务类 */ public class AttendanceSelfHolidayFactory extends AbstractFactory { - - public AttendanceSelfHolidayFactory(Business business) throws Exception { - super(business); - } - - //@MethodDescribe("获取指定Id的AttendanceSelfHoliday信息对象") - public AttendanceSelfHoliday get( String id ) throws Exception { - return this.entityManagerContainer().find(id, AttendanceSelfHoliday.class, ExceptionWhen.none); - } - + + private static final Logger LOGGER = LoggerFactory.getLogger(AttendanceSelfHolidayFactory.class); + + public AttendanceSelfHolidayFactory(Business business) throws Exception { + super(business); + } + + // @MethodDescribe("获取指定Id的AttendanceSelfHoliday信息对象") + public AttendanceSelfHoliday get(String id) throws Exception { + return this.entityManagerContainer().find(id, AttendanceSelfHoliday.class, ExceptionWhen.none); + } + //@MethodDescribe("列示全部的AttendanceSelfHoliday信息列表") - public List listAll() throws Exception { - EntityManager em = this.entityManagerContainer().get(AttendanceSelfHoliday.class); - CriteriaBuilder cb = em.getCriteriaBuilder(); - CriteriaQuery cq = cb.createQuery(String.class); - Root root = cq.from( AttendanceSelfHoliday.class); - cq.select(root.get(AttendanceSelfHoliday_.id)); - return em.createQuery(cq).getResultList(); - } - + public List listAll() throws Exception { + EntityManager em = this.entityManagerContainer().get(AttendanceSelfHoliday.class); + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(String.class); + Root root = cq.from(AttendanceSelfHoliday.class); + cq.select(root.get(AttendanceSelfHoliday_.id)); + return em.createQuery(cq).getResultList(); + } + // @MethodDescribe("列示指定Id的AttendanceSelfHoliday信息列表") - public List list(List ids) throws Exception { - if( ids == null || ids.size() == 0 ){ - return new ArrayList(); - } - EntityManager em = this.entityManagerContainer().get(AttendanceSelfHoliday.class); - CriteriaBuilder cb = em.getCriteriaBuilder(); - CriteriaQuery cq = cb.createQuery(AttendanceSelfHoliday.class); - Root root = cq.from(AttendanceSelfHoliday.class); - Predicate p = root.get(AttendanceSelfHoliday_.id).in(ids); - return em.createQuery(cq.where(p)).getResultList(); - } - - public List listWithBatchFlag( String batchFlag ) throws Exception { - if( StringUtils.isEmpty( batchFlag )){ - return null; - } - EntityManager em = this.entityManagerContainer().get(AttendanceSelfHoliday.class); - CriteriaBuilder cb = em.getCriteriaBuilder(); - CriteriaQuery cq = cb.createQuery(AttendanceSelfHoliday.class); - Root root = cq.from(AttendanceSelfHoliday.class); - Predicate p = cb.equal( root.get(AttendanceSelfHoliday_.batchFlag), batchFlag ); - return em.createQuery(cq.where(p)).getResultList(); - } - - public List listIdsWithBatchFlag( String batchFlag ) throws Exception { - if( StringUtils.isEmpty( batchFlag )){ - return null; - } - EntityManager em = this.entityManagerContainer().get(AttendanceSelfHoliday.class); - CriteriaBuilder cb = em.getCriteriaBuilder(); - CriteriaQuery cq = cb.createQuery(String.class); - Root root = cq.from(AttendanceSelfHoliday.class); - Predicate p = cb.equal( root.get(AttendanceSelfHoliday_.batchFlag), batchFlag ); - cq.select(root.get(AttendanceSelfHoliday_.id)); - return em.createQuery(cq.where(p)).getResultList(); - } - - //@MethodDescribe("列示单个员工的AttendanceSelfHoliday信息列表") - public List getByEmployeeName(String empName) throws Exception { - EntityManager em = this.entityManagerContainer().get(AttendanceSelfHoliday.class); - CriteriaBuilder cb = em.getCriteriaBuilder(); - CriteriaQuery cq = cb.createQuery(String.class); - Root root = cq.from( AttendanceSelfHoliday.class); - Predicate p = root.get(AttendanceSelfHoliday_.employeeName).in( empName ); - cq.select(root.get(AttendanceSelfHoliday_.id)); - return em.createQuery(cq.where(p)).getResultList(); - } - - //@MethodDescribe("根据流程的文档ID列示员工的AttendanceSelfHoliday信息列表") + public List list(List ids) throws Exception { + if (ids == null || ids.size() == 0) { + return new ArrayList(); + } + EntityManager em = this.entityManagerContainer().get(AttendanceSelfHoliday.class); + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(AttendanceSelfHoliday.class); + Root root = cq.from(AttendanceSelfHoliday.class); + Predicate p = root.get(AttendanceSelfHoliday_.id).in(ids); + return em.createQuery(cq.where(p)).getResultList(); + } + + public List listWithBatchFlag(String batchFlag) throws Exception { + if (StringUtils.isEmpty(batchFlag)) { + return null; + } + EntityManager em = this.entityManagerContainer().get(AttendanceSelfHoliday.class); + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(AttendanceSelfHoliday.class); + Root root = cq.from(AttendanceSelfHoliday.class); + Predicate p = cb.equal(root.get(AttendanceSelfHoliday_.batchFlag), batchFlag); + return em.createQuery(cq.where(p)).getResultList(); + } + + public List listIdsWithBatchFlag(String batchFlag) throws Exception { + if (StringUtils.isEmpty(batchFlag)) { + return null; + } + EntityManager em = this.entityManagerContainer().get(AttendanceSelfHoliday.class); + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(String.class); + Root root = cq.from(AttendanceSelfHoliday.class); + Predicate p = cb.equal(root.get(AttendanceSelfHoliday_.batchFlag), batchFlag); + cq.select(root.get(AttendanceSelfHoliday_.id)); + return em.createQuery(cq.where(p)).getResultList(); + } + + // @MethodDescribe("列示单个员工的AttendanceSelfHoliday信息列表") + public List getByEmployeeName(String empName) throws Exception { + EntityManager em = this.entityManagerContainer().get(AttendanceSelfHoliday.class); + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(String.class); + Root root = cq.from(AttendanceSelfHoliday.class); + Predicate p = root.get(AttendanceSelfHoliday_.employeeName).in(empName); + cq.select(root.get(AttendanceSelfHoliday_.id)); + return em.createQuery(cq.where(p)).getResultList(); + } + + // @MethodDescribe("根据流程的文档ID列示员工的AttendanceSelfHoliday信息列表") // public List getByWorkFlowDocId(String docId) throws Exception { // EntityManager em = this.entityManagerContainer().get(AttendanceSelfHoliday.class); // CriteriaBuilder cb = em.getCriteriaBuilder(); @@ -104,194 +109,202 @@ public class AttendanceSelfHolidayFactory extends AbstractFactory { // return em.createQuery(cq.where(p)).getResultList(); // } - public List listByStartDateAndEndDate(Date startDate, Date endDate) throws Exception { - EntityManager em = this.entityManagerContainer().get(AttendanceSelfHoliday.class); - CriteriaBuilder cb = em.getCriteriaBuilder(); - CriteriaQuery cq = cb.createQuery(String.class); - Root root = cq.from( AttendanceSelfHoliday.class); - Predicate p = cb.between(root.get(AttendanceSelfHoliday_.startTime), startDate, endDate); - p = cb.and( p, cb.between(root.get(AttendanceSelfHoliday_.endTime), startDate, endDate)); - cq.select(root.get(AttendanceSelfHoliday_.id)); - return em.createQuery(cq.where(p)).getResultList(); - } - - /** - * 查询下一页的信息数据 - * @param id - * @param count - * @param sequence - * @param wrapIn - * @return - * @throws Exception - */ - @SuppressWarnings("unchecked") - public List listIdsNextWithFilter( String id, Integer count, Object sequence, ActionListNextWithFilter.WrapIn wrapIn ) throws Exception { - //先获取上一页最后一条的sequence值,如果有值的话,以此sequence值作为依据取后续的count条数据 - EntityManager em = this.entityManagerContainer().get( AttendanceSelfHoliday.class ); - String order = wrapIn.getOrder();//排序方式 - List vs = new ArrayList<>(); - StringBuffer sql_stringBuffer = new StringBuffer(); - - if( order == null || order.isEmpty() ){ - order = "DESC"; - } - - Integer index = 1; - sql_stringBuffer.append( "SELECT o FROM "+AttendanceSelfHoliday.class.getCanonicalName()+" o where 1=1" ); - - if ((null != sequence) ) { - sql_stringBuffer.append(" and o.sequence " + (StringUtils.equalsIgnoreCase(order, "DESC") ? "<" : ">") + (" ?" + (index))); - vs.add(sequence); - index++; - } - if ((null != wrapIn.getQ_empName()) && (!wrapIn.getQ_empName().isEmpty())) { - sql_stringBuffer.append(" and o.employeeName = ?" + (index)); - vs.add( wrapIn.getQ_empName() ); - index++; - } - if (null != wrapIn.getUnitNames() && wrapIn.getUnitNames().size()>0) { - sql_stringBuffer.append(" and o.unitOu in ( ?" + (index) + ")"); - vs.add( wrapIn.getUnitNames() ); - index++; - } - if (null != wrapIn.getTopUnitNames() && wrapIn.getTopUnitNames().size() > 0 ) { - sql_stringBuffer.append(" and o.topUnitOu in ( ?" + (index) + ")"); - vs.add( wrapIn.getTopUnitNames() ); - index++; - } - if (null != wrapIn.getStartdate() && null != wrapIn.getEnddate()) { - sql_stringBuffer.append(" and o.startTime >= ?" + (index) ); - vs.add( wrapIn.getStartdate()); - index++; - - sql_stringBuffer.append(" and o.endTime <= ?" + (index)); - vs.add( wrapIn.getEnddate()); - index++; - } - - if( StringUtils.isNotEmpty( wrapIn.getKey() )){ - sql_stringBuffer.append(" order by o."+wrapIn.getKey()+" " + order ); - }else{ - sql_stringBuffer.append(" order by o.sequence " + order ); - } - - Query query = em.createQuery( sql_stringBuffer.toString(), AttendanceSelfHoliday.class ); - //System.out.println("query=" +query.toString()); - //为查询设置所有的参数值 - 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 listIdsPrevWithFilter( String id, Integer count, Object sequence, WrapInFilter wrapIn ) throws Exception { - //先获取上一页最后一条的sequence值,如果有值的话,以此sequence值作为依据取后续的count条数据 - EntityManager em = this.entityManagerContainer().get( AttendanceSelfHoliday.class ); - String order = wrapIn.getOrder();//排序方式 - List vs = new ArrayList<>(); - StringBuffer sql_stringBuffer = new StringBuffer(); - Integer index = 1; - - if( order == null || order.isEmpty() ){ - order = "DESC"; - } - - sql_stringBuffer.append( "SELECT o FROM "+AttendanceSelfHoliday.class.getCanonicalName()+" o where 1=1" ); - if ((null != sequence) ) { - sql_stringBuffer.append(" and o.sequence " + (StringUtils.equalsIgnoreCase(order, "DESC") ? ">" : "<") + (" ?" + (index))); - vs.add(sequence); - index++; - } - if ((null != wrapIn.getQ_empName()) && (!wrapIn.getQ_empName().isEmpty())) { - sql_stringBuffer.append(" and o.employeeName = ?" + (index)); - vs.add( wrapIn.getQ_empName() ); - index++; - } - if (null != wrapIn.getUnitNames() && wrapIn.getUnitNames().size()>0) { - sql_stringBuffer.append(" and o.unitName in ( ?" + (index) + ")"); - vs.add( wrapIn.getUnitNames() ); - index++; - } - if (null != wrapIn.getTopUnitNames() && wrapIn.getTopUnitNames().size() > 0 ) { - sql_stringBuffer.append(" and o.topUnitName in ( ?" + (index) + ")"); - vs.add( wrapIn.getTopUnitNames() ); - index++; - } - - if( StringUtils.isNotEmpty( wrapIn.getKey() )){ - sql_stringBuffer.append(" order by o."+wrapIn.getKey()+" " + order ); - }else{ - sql_stringBuffer.append(" order by o.sequence " + order ); - } - - Query query = em.createQuery( sql_stringBuffer.toString(), AttendanceSelfHoliday.class ); - //为查询设置所有的参数值 - for (int i = 0; i < vs.size(); i++) { - query.setParameter(i + 1, vs.get(i)); - } - - return query.setMaxResults(20).getResultList(); - } - - /** - * 查询符合的文档信息总数 - * @param wrapIn - * @return - * @throws Exception - */ - public long getCountWithFilter( WrapInFilter wrapIn ) throws Exception { - //先获取上一页最后一条的sequence值,如果有值的话,以此sequence值作为依据取后续的count条数据 - EntityManager em = this.entityManagerContainer().get( AttendanceSelfHoliday.class ); - List vs = new ArrayList<>(); - StringBuffer sql_stringBuffer = new StringBuffer(); - Integer index = 1; - - sql_stringBuffer.append( "SELECT count(o.id) FROM "+AttendanceSelfHoliday.class.getCanonicalName()+" o where 1=1" ); - - if ((null != wrapIn.getQ_empName()) && (!wrapIn.getQ_empName().isEmpty())) { - sql_stringBuffer.append(" and o.employeeName = ?" + (index)); - vs.add( wrapIn.getQ_empName() ); - index++; - } - if (null != wrapIn.getUnitNames() && wrapIn.getUnitNames().size()>0) { - sql_stringBuffer.append(" and o.unitName in ( ?" + (index) + ")"); - vs.add( wrapIn.getUnitNames() ); - index++; - } - if (null != wrapIn.getTopUnitNames() && wrapIn.getTopUnitNames().size() > 0 ) { - sql_stringBuffer.append(" and o.topUnitName in ( ?" + (index) + ")"); - vs.add( wrapIn.getTopUnitNames() ); - index++; - } - - Query query = em.createQuery( sql_stringBuffer.toString(), AttendanceSelfHoliday.class ); - //为查询设置所有的参数值 - for (int i = 0; i < vs.size(); i++) { - query.setParameter(i + 1, vs.get(i)); - } - return (Long) query.getSingleResult(); - } - - public List getByPersonName(String personName) throws Exception { - if( personName == null || personName.isEmpty() ) { - throw new Exception("personName is null."); - } - EntityManager em = this.entityManagerContainer().get(AttendanceSelfHoliday.class); - CriteriaBuilder cb = em.getCriteriaBuilder(); - CriteriaQuery cq = cb.createQuery(String.class); - Root root = cq.from( AttendanceSelfHoliday.class); - Predicate p = cb.equal(root.get(AttendanceSelfHoliday_.employeeName ), personName ); - cq.select(root.get(AttendanceSelfHoliday_.id)); - return em.createQuery(cq.where(p)).getResultList(); - } + public List listByStartDateAndEndDate(Date startDate, Date endDate) throws Exception { + EntityManager em = this.entityManagerContainer().get(AttendanceSelfHoliday.class); + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(String.class); + Root root = cq.from(AttendanceSelfHoliday.class); + Predicate p = cb.between(root.get(AttendanceSelfHoliday_.startTime), startDate, endDate); + p = cb.and(p, cb.between(root.get(AttendanceSelfHoliday_.endTime), startDate, endDate)); + cq.select(root.get(AttendanceSelfHoliday_.id)); + return em.createQuery(cq.where(p)).getResultList(); + } + + /** + * 查询下一页的信息数据 + * + * @param id + * @param count + * @param sequence + * @param wrapIn + * @return + * @throws Exception + */ + @SuppressWarnings("unchecked") + public List listIdsNextWithFilter(String id, Integer count, Object sequence, + ActionListNextWithFilter.WrapIn wrapIn) throws Exception { + // 先获取上一页最后一条的sequence值,如果有值的话,以此sequence值作为依据取后续的count条数据 + EntityManager em = this.entityManagerContainer().get(AttendanceSelfHoliday.class); + String order = wrapIn.getOrder();// 排序方式 + List vs = new ArrayList<>(); + StringBuffer sql_stringBuffer = new StringBuffer(); + + if (order == null || order.isEmpty()) { + order = "DESC"; + } + + Integer index = 1; + sql_stringBuffer.append("SELECT o FROM " + AttendanceSelfHoliday.class.getCanonicalName() + " o where 1=1"); + + if ((null != sequence)) { + sql_stringBuffer.append( + " and o.sequence " + (StringUtils.equalsIgnoreCase(order, "DESC") ? "<" : ">") + (" ?" + (index))); + vs.add(sequence); + index++; + } + if ((null != wrapIn.getQ_empName()) && (!wrapIn.getQ_empName().isEmpty())) { + sql_stringBuffer.append(" and o.employeeName = ?" + (index)); + vs.add(wrapIn.getQ_empName()); + index++; + } + if (null != wrapIn.getUnitNames() && wrapIn.getUnitNames().size() > 0) { + sql_stringBuffer.append(" and o.unitOu in ( ?" + (index) + ")"); + vs.add(wrapIn.getUnitNames()); + index++; + } + if (null != wrapIn.getTopUnitNames() && wrapIn.getTopUnitNames().size() > 0) { + sql_stringBuffer.append(" and o.topUnitOu in ( ?" + (index) + ")"); + vs.add(wrapIn.getTopUnitNames()); + index++; + } + if (null != wrapIn.getStartdate() && null != wrapIn.getEnddate()) { + sql_stringBuffer.append(" and o.startTime >= ?" + (index)); + vs.add(wrapIn.getStartdate()); + index++; + + sql_stringBuffer.append(" and o.endTime <= ?" + (index)); + vs.add(wrapIn.getEnddate()); + index++; + } + + if (StringUtils.isNotEmpty(wrapIn.getKey())) { + sql_stringBuffer.append(" order by o." + wrapIn.getKey() + " " + order); + } else { + sql_stringBuffer.append(" order by o.sequence " + order); + } + + Query query = em.createQuery(sql_stringBuffer.toString(), AttendanceSelfHoliday.class); + // System.out.println("query=" +query.toString()); + // 为查询设置所有的参数值 + 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 listIdsPrevWithFilter(String id, Integer count, Object sequence, + WrapInFilter wrapIn) throws Exception { + // 先获取上一页最后一条的sequence值,如果有值的话,以此sequence值作为依据取后续的count条数据 + EntityManager em = this.entityManagerContainer().get(AttendanceSelfHoliday.class); + String order = wrapIn.getOrder();// 排序方式 + List vs = new ArrayList<>(); + StringBuffer sql_stringBuffer = new StringBuffer(); + Integer index = 1; + + if (order == null || order.isEmpty()) { + order = "DESC"; + } + + sql_stringBuffer.append("SELECT o FROM " + AttendanceSelfHoliday.class.getCanonicalName() + " o where 1=1"); + if ((null != sequence)) { + sql_stringBuffer.append( + " and o.sequence " + (StringUtils.equalsIgnoreCase(order, "DESC") ? ">" : "<") + (" ?" + (index))); + vs.add(sequence); + index++; + } + if ((null != wrapIn.getQ_empName()) && (!wrapIn.getQ_empName().isEmpty())) { + sql_stringBuffer.append(" and o.employeeName = ?" + (index)); + vs.add(wrapIn.getQ_empName()); + index++; + } + if (null != wrapIn.getUnitNames() && wrapIn.getUnitNames().size() > 0) { + sql_stringBuffer.append(" and o.unitName in ( ?" + (index) + ")"); + vs.add(wrapIn.getUnitNames()); + index++; + } + if (null != wrapIn.getTopUnitNames() && wrapIn.getTopUnitNames().size() > 0) { + sql_stringBuffer.append(" and o.topUnitName in ( ?" + (index) + ")"); + vs.add(wrapIn.getTopUnitNames()); + index++; + } + + if (StringUtils.isNotEmpty(wrapIn.getKey())) { + sql_stringBuffer.append(" order by o." + wrapIn.getKey() + " " + order); + } else { + sql_stringBuffer.append(" order by o.sequence " + order); + } + + Query query = em.createQuery(sql_stringBuffer.toString(), AttendanceSelfHoliday.class); + // 为查询设置所有的参数值 + for (int i = 0; i < vs.size(); i++) { + query.setParameter(i + 1, vs.get(i)); + } + LOGGER.debug("query :{}, parameter:{}.", query::toString, () -> vs); + return query.setMaxResults(20).getResultList(); + } + + /** + * 查询符合的文档信息总数 + * + * @param wrapIn + * @return + * @throws Exception + */ + public long getCountWithFilter(WrapInFilter wrapIn) throws Exception { + // 先获取上一页最后一条的sequence值,如果有值的话,以此sequence值作为依据取后续的count条数据 + EntityManager em = this.entityManagerContainer().get(AttendanceSelfHoliday.class); + List vs = new ArrayList<>(); + StringBuffer sql_stringBuffer = new StringBuffer(); + Integer index = 1; + + sql_stringBuffer + .append("SELECT count(o.id) FROM " + AttendanceSelfHoliday.class.getCanonicalName() + " o where 1=1"); + + if ((null != wrapIn.getQ_empName()) && (!wrapIn.getQ_empName().isEmpty())) { + sql_stringBuffer.append(" and o.employeeName = ?" + (index)); + vs.add(wrapIn.getQ_empName()); + index++; + } + if (null != wrapIn.getUnitNames() && wrapIn.getUnitNames().size() > 0) { + sql_stringBuffer.append(" and o.unitName in ( ?" + (index) + ")"); + vs.add(wrapIn.getUnitNames()); + index++; + } + if (null != wrapIn.getTopUnitNames() && wrapIn.getTopUnitNames().size() > 0) { + sql_stringBuffer.append(" and o.topUnitName in ( ?" + (index) + ")"); + vs.add(wrapIn.getTopUnitNames()); + index++; + } + + Query query = em.createQuery(sql_stringBuffer.toString(), AttendanceSelfHoliday.class); + // 为查询设置所有的参数值 + for (int i = 0; i < vs.size(); i++) { + query.setParameter(i + 1, vs.get(i)); + } + return (Long) query.getSingleResult(); + } + + public List getByPersonName(String personName) throws Exception { + if (personName == null || personName.isEmpty()) { + throw new Exception("personName is null."); + } + EntityManager em = this.entityManagerContainer().get(AttendanceSelfHoliday.class); + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(String.class); + Root root = cq.from(AttendanceSelfHoliday.class); + Predicate p = cb.equal(root.get(AttendanceSelfHoliday_.employeeName), personName); + cq.select(root.get(AttendanceSelfHoliday_.id)); + return em.createQuery(cq.where(p)).getResultList(); + } } \ No newline at end of file diff --git a/o2server/x_attendance_assemble_control/src/main/java/com/x/attendance/assemble/control/jaxrs/selfholiday/ActionListNextWithFilter.java b/o2server/x_attendance_assemble_control/src/main/java/com/x/attendance/assemble/control/jaxrs/selfholiday/ActionListNextWithFilter.java index e50fb081cb7e0a85eb9236de6f76d95abc0b6544..6c8ad4ce2c93d36b3671a9983f5485a82e345045 100644 --- a/o2server/x_attendance_assemble_control/src/main/java/com/x/attendance/assemble/control/jaxrs/selfholiday/ActionListNextWithFilter.java +++ b/o2server/x_attendance_assemble_control/src/main/java/com/x/attendance/assemble/control/jaxrs/selfholiday/ActionListNextWithFilter.java @@ -24,161 +24,174 @@ import com.x.base.core.project.http.EffectivePerson; import com.x.base.core.project.jaxrs.StandardJaxrsAction; import com.x.base.core.project.logger.Logger; import com.x.base.core.project.logger.LoggerFactory; +import com.x.base.core.project.tools.ListTools; public class ActionListNextWithFilter extends BaseAction { - - private static Logger logger = LoggerFactory.getLogger( ActionListNextWithFilter.class ); - protected DateOperation dateOperation = new DateOperation(); - protected ActionResult> execute( HttpServletRequest request, EffectivePerson effectivePerson, String id, Integer count, JsonElement jsonElement ) throws Exception { - ActionResult> result = new ActionResult<>(); - List wraps = new ArrayList<>(); - EffectivePerson currentPerson = this.effectivePerson(request); - Long total = 0L; - List detailList = null; - List topUnitNames = new ArrayList(); - List unitNames = new ArrayList(); - List unitNameList = null; - WrapIn wrapIn = null; - Boolean check = true; - Date startDate = null; - Date endDate = null; - - try { - wrapIn = this.convertToWrapIn( jsonElement, WrapIn.class ); - startDate = dateOperation.getDateFromString( wrapIn.getStartdateString() + " 00:00:00"); - endDate = dateOperation.getDateFromString( wrapIn.getEnddateString() + " 23:59:59"); - - if( endDate == null ){ - endDate = dateOperation.getLastDateInMonth( new Date() ); - } - - if( startDate == null ){ - startDate = dateOperation.getFirstDateInMonth( new Date() ); - } - - if( startDate.after( endDate ) ){ - startDate = dateOperation.getFirstDateInMonth( new Date() ); - } - wrapIn.setStartdate(startDate); - wrapIn.setEnddate(endDate); - } catch (Exception e ) { - check = false; - Exception exception = new ExceptionWrapInConvert( e, jsonElement ); - result.error( exception ); - logger.error( e, currentPerson, request, null); - } - if(check ){ - try { - EntityManagerContainer emc = EntityManagerContainerFactory.instance().create(); - Business business = new Business(emc); - - //查询出ID对应的记录的sequence - Object sequence = null; - if( id == null || "(0)".equals(id) || id.isEmpty() ){ - //logger.info( "第一页查询,没有id传入" ); - }else{ - if (!StringUtils.equalsIgnoreCase(id,StandardJaxrsAction.EMPTY_SYMBOL)) { - sequence = PropertyUtils.getProperty(emc.find( id, AttendanceSelfHoliday.class ), JpaObject.sequence_FIELDNAME); - } - } - - //处理一下顶层组织,查询下级顶层组织 - if( StringUtils.isNotEmpty( wrapIn.getQ_topUnitName() ) ){ - topUnitNames.add( wrapIn.getQ_topUnitName() ); - try{ - unitNameList = userManagerService.listSubUnitNameWithParent( wrapIn.getQ_topUnitName() ); - }catch(Exception e){ - Exception exception = new ExceptionSelfHolidayProcess( e, - "系统根据顶层组织名称查询所有下级组织列表时发生异常.Name:" + wrapIn.getQ_topUnitName() ); - result.error( exception ); - logger.error( e, currentPerson, request, null); - } - if( unitNameList != null && unitNameList.size() > 0 ){ - for( String unitName : unitNameList){ - topUnitNames.add( unitName ); - } - } - wrapIn.setTopUnitNames( topUnitNames ); - } - - //处理一下组织,查询下级组织 - if( StringUtils.isNotEmpty( wrapIn.getQ_unitName() ) ){ - unitNames.add(wrapIn.getQ_unitName()); - try{ - unitNameList = userManagerService.listSubUnitNameWithParent( wrapIn.getQ_unitName() ); - }catch(Exception e){ - Exception exception = new ExceptionSelfHolidayProcess( e, "系统根据组织名称查询所有下级组织列表时发生异常.Name:" + wrapIn.getQ_unitName() ); - result.error( exception ); - logger.error( e, currentPerson, request, null); - } - if( unitNameList != null && unitNameList.size() > 0 ){ - for( String unitName : unitNameList){ - unitNames.add( unitName ); - } - } - wrapIn.setUnitNames(unitNames); - } - - //从数据库中查询符合条件的一页数据对象 - detailList = business.getAttendanceSelfHolidayFactory().listIdsNextWithFilter( id, count, sequence, wrapIn ); - - //从数据库中查询符合条件的对象总数 - total = business.getAttendanceSelfHolidayFactory().getCountWithFilter( wrapIn ); - - //将所有查询出来的有状态的对象转换为可以输出的过滤过属性的对象 - wraps = Wo.copier.copy( detailList ); - } catch (Throwable th) { - th.printStackTrace(); - result.error(th); - } - } - result.setCount( total ); - result.setData(wraps); - return result; - } - public static class WrapIn extends WrapInFilter{ - String startdateString; - String enddateString; - Date startdate = null; - Date enddate = null; - - 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 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 static class Wo extends AttendanceSelfHoliday { - - private static final long serialVersionUID = -5076990764713538973L; - - public static WrapCopier copier = - WrapCopierFactory.wo(AttendanceSelfHoliday.class, Wo.class, null,JpaObject.FieldsInvisible); - } + + private static Logger logger = LoggerFactory.getLogger(ActionListNextWithFilter.class); + protected DateOperation dateOperation = new DateOperation(); + + protected ActionResult> execute(HttpServletRequest request, EffectivePerson effectivePerson, String id, + Integer count, JsonElement jsonElement) throws Exception { + ActionResult> result = new ActionResult<>(); + List wraps = new ArrayList<>(); + EffectivePerson currentPerson = this.effectivePerson(request); + Long total = 0L; + List detailList = null; + List topUnitNames = new ArrayList(); + List unitNames = new ArrayList(); + List unitNameList = null; + WrapIn wrapIn = null; + Boolean check = true; + Date startDate = null; + Date endDate = null; + + try { + wrapIn = this.convertToWrapIn(jsonElement, WrapIn.class); + if (StringUtils.isNotBlank(wrapIn.getStartdateString())) { + startDate = dateOperation.getDateFromString(wrapIn.getStartdateString() + " 00:00:00"); + } + + if (StringUtils.isNotBlank(wrapIn.getEnddateString())) { + endDate = dateOperation.getDateFromString(wrapIn.getEnddateString() + " 23:59:59"); + } + + if (endDate == null) { + endDate = dateOperation.getLastDateInMonth(new Date()); + } + + if (startDate == null) { + startDate = dateOperation.getFirstDateInMonth(new Date()); + } + + if (startDate.after(endDate)) { + startDate = dateOperation.getFirstDateInMonth(new Date()); + } + wrapIn.setStartdate(startDate); + wrapIn.setEnddate(endDate); + } catch (Exception e) { + check = false; + Exception exception = new ExceptionWrapInConvert(e, jsonElement); + result.error(exception); + logger.error(e, currentPerson, request, null); + } + if (check) { + try { + EntityManagerContainer emc = EntityManagerContainerFactory.instance().create(); + Business business = new Business(emc); + + // 查询出ID对应的记录的sequence + Object sequence = null; + if (id == null || "(0)".equals(id) || id.isEmpty()) { + // logger.info( "第一页查询,没有id传入" ); + } else { + if (!StringUtils.equalsIgnoreCase(id, StandardJaxrsAction.EMPTY_SYMBOL)) { + sequence = PropertyUtils.getProperty(emc.find(id, AttendanceSelfHoliday.class), + JpaObject.sequence_FIELDNAME); + } + } + + // 处理一下顶层组织,查询下级顶层组织 + if (StringUtils.isNotEmpty(wrapIn.getQ_topUnitName())) { + topUnitNames.add(wrapIn.getQ_topUnitName()); + try { + unitNameList = userManagerService.listSubUnitNameWithParent(wrapIn.getQ_topUnitName()); + } catch (Exception e) { + Exception exception = new ExceptionSelfHolidayProcess(e, + "系统根据顶层组织名称查询所有下级组织列表时发生异常.Name:" + wrapIn.getQ_topUnitName()); + result.error(exception); + logger.error(e, currentPerson, request, null); + } + if (unitNameList != null && unitNameList.size() > 0) { + for (String unitName : unitNameList) { + topUnitNames.add(unitName); + } + } + wrapIn.setTopUnitNames(topUnitNames); + } + + // 处理一下组织,查询下级组织 + if (StringUtils.isNotEmpty(wrapIn.getQ_unitName())) { + unitNames.add(wrapIn.getQ_unitName()); + try { + unitNameList = userManagerService.listSubUnitNameWithParent(wrapIn.getQ_unitName()); + } catch (Exception e) { + Exception exception = new ExceptionSelfHolidayProcess(e, + "系统根据组织名称查询所有下级组织列表时发生异常.Name:" + wrapIn.getQ_unitName()); + result.error(exception); + logger.error(e, currentPerson, request, null); + } + if (ListTools.isNotEmpty(unitNameList)) { + for (String unitName : unitNameList) { + unitNames.add(unitName); + } + } + wrapIn.setUnitNames(unitNames); + } + + // 从数据库中查询符合条件的一页数据对象 + detailList = business.getAttendanceSelfHolidayFactory().listIdsNextWithFilter(id, count, sequence, + wrapIn); + + // 从数据库中查询符合条件的对象总数 + total = business.getAttendanceSelfHolidayFactory().getCountWithFilter(wrapIn); + + // 将所有查询出来的有状态的对象转换为可以输出的过滤过属性的对象 + wraps = Wo.copier.copy(detailList); + } catch (Throwable th) { + th.printStackTrace(); + result.error(th); + } + } + result.setCount(total); + result.setData(wraps); + return result; + } + + public static class WrapIn extends WrapInFilter { + String startdateString; + String enddateString; + Date startdate = null; + Date enddate = null; + + 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 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 static class Wo extends AttendanceSelfHoliday { + + private static final long serialVersionUID = -5076990764713538973L; + + public static WrapCopier copier = WrapCopierFactory.wo(AttendanceSelfHoliday.class, + Wo.class, null, JpaObject.FieldsInvisible); + } } \ No newline at end of file diff --git a/o2server/x_base_core_project/src/main/java/com/x/base/core/container/factory/PersistenceXmlHelper.java b/o2server/x_base_core_project/src/main/java/com/x/base/core/container/factory/PersistenceXmlHelper.java index f81a4e6758c8297d6b99ab94187cb079c20ac606..4de5e160befde8f0ac58bf9d63a094d9bf1adcbf 100644 --- a/o2server/x_base_core_project/src/main/java/com/x/base/core/container/factory/PersistenceXmlHelper.java +++ b/o2server/x_base_core_project/src/main/java/com/x/base/core/container/factory/PersistenceXmlHelper.java @@ -37,307 +37,307 @@ import io.github.classgraph.ScanResult; public class PersistenceXmlHelper { - private PersistenceXmlHelper() { + private PersistenceXmlHelper() { - } + } - public static List directWriteDynamicEnhance(String path, List classNames) throws Exception { - try { - Document document = DocumentHelper.createDocument(); - Element persistence = createPersistenceElement(document); - Element unit = persistence.addElement("persistence-unit"); - unit.addAttribute("name", "dynamic"); - unit.addAttribute("transaction-type", "RESOURCE_LOCAL"); - unit.addElement("provider").addText(PersistenceProviderImpl.class.getName()); - for (String className : classNames) { - unit.addElement("class").addText(className); - } - unit.addElement("class").addText("com.x.base.core.entity.SliceJpaObject"); - unit.addElement("class").addText("com.x.base.core.entity.JpaObject"); - OutputFormat format = OutputFormat.createPrettyPrint(); - format.setEncoding(StandardCharsets.UTF_8.name()); - File file = new File(path); - FileUtils.touch(file); - XMLWriter writer = new XMLWriter(new FileWriter(file), format); - writer.write(document); - writer.close(); - return classNames; - } catch (Exception e) { - throw new Exception("registContainerEntity error.className:" + ListTools.toStringJoin(classNames), e); - } - } + public static List directWriteDynamicEnhance(String path, List classNames) throws Exception { + try { + Document document = DocumentHelper.createDocument(); + Element persistence = createPersistenceElement(document); + Element unit = persistence.addElement("persistence-unit"); + unit.addAttribute("name", "dynamic"); + unit.addAttribute("transaction-type", "RESOURCE_LOCAL"); + unit.addElement("provider").addText(PersistenceProviderImpl.class.getName()); + for (String className : classNames) { + unit.addElement("class").addText(className); + } + unit.addElement("class").addText("com.x.base.core.entity.SliceJpaObject"); + unit.addElement("class").addText("com.x.base.core.entity.JpaObject"); + OutputFormat format = OutputFormat.createPrettyPrint(); + format.setEncoding(StandardCharsets.UTF_8.name()); + File file = new File(path); + FileUtils.touch(file); + XMLWriter writer = new XMLWriter(new FileWriter(file), format); + writer.write(document); + writer.close(); + return classNames; + } catch (Exception e) { + throw new Exception("registContainerEntity error.className:" + ListTools.toStringJoin(classNames), e); + } + } - private static Element createPersistenceElement(Document document) { - Element persistence = document.addElement("persistence", "http://java.sun.com/xml/ns/persistence"); - persistence.addAttribute(QName.get("schemaLocation", "xsi", "http://www.w3.org/2001/XMLSchema-instance"), - "http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"); - persistence.addAttribute("version", "2.0"); - return persistence; - } + private static Element createPersistenceElement(Document document) { + Element persistence = document.addElement("persistence", "http://java.sun.com/xml/ns/persistence"); + persistence.addAttribute(QName.get("schemaLocation", "xsi", "http://www.w3.org/2001/XMLSchema-instance"), + "http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"); + persistence.addAttribute("version", "2.0"); + return persistence; + } - @SuppressWarnings("unchecked") - public static void writeForDdl(String path) throws Exception { - try { - Document document = DocumentHelper.createDocument(); - Element persistence = createPersistenceElement(document); - Element unit = persistence.addElement("persistence-unit"); - unit.addAttribute("name", "enhance"); - unit.addAttribute("transaction-type", "RESOURCE_LOCAL"); - Element provider = unit.addElement("provider"); - provider.addText(PersistenceProviderImpl.class.getName()); - List entities = new ArrayList<>(); - for (String className : (List) Config.resource(Config.RESOURCE_CONTAINERENTITYNAMES)) { - Class clazz = (Class) Thread.currentThread().getContextClassLoader() - .loadClass(className); - for (Class o : JpaObjectTools.scanMappedSuperclass(clazz)) { - entities.add(o.getName()); - } - } - entities = ListTools.trim(entities, true, true); - for (String className : entities) { - unit.addElement("class").addText(className); - } - Element properties = unit.addElement("properties"); - if (BooleanUtils.isTrue(Config.externalDataSources().enable())) { - writeForDdlExternalProperty(properties); - } else { - writeForDdlInternalProperty(properties); - } - OutputFormat format = OutputFormat.createPrettyPrint(); - format.setEncoding("UTF-8"); - File file = new File(path); - FileUtils.touch(file); - XMLWriter writer = new XMLWriter(new FileWriter(file), format); - writer.write(document); - writer.close(); - } catch (Exception e) { - throw new Exception("writeForDdl error.", e); - } - } + @SuppressWarnings("unchecked") + public static void writeForDdl(String path) throws Exception { + try { + Document document = DocumentHelper.createDocument(); + Element persistence = createPersistenceElement(document); + Element unit = persistence.addElement("persistence-unit"); + unit.addAttribute("name", "enhance"); + unit.addAttribute("transaction-type", "RESOURCE_LOCAL"); + Element provider = unit.addElement("provider"); + provider.addText(PersistenceProviderImpl.class.getName()); + List entities = new ArrayList<>(); + for (String className : (List) Config.resource(Config.RESOURCE_CONTAINERENTITYNAMES)) { + Class clazz = (Class) Thread.currentThread().getContextClassLoader() + .loadClass(className); + for (Class o : JpaObjectTools.scanMappedSuperclass(clazz)) { + entities.add(o.getName()); + } + } + entities = ListTools.trim(entities, true, true); + for (String className : entities) { + unit.addElement("class").addText(className); + } + Element properties = unit.addElement("properties"); + if (BooleanUtils.isTrue(Config.externalDataSources().enable())) { + writeForDdlExternalProperty(properties); + } else { + writeForDdlInternalProperty(properties); + } + OutputFormat format = OutputFormat.createPrettyPrint(); + format.setEncoding("UTF-8"); + File file = new File(path); + FileUtils.touch(file); + XMLWriter writer = new XMLWriter(new FileWriter(file), format); + writer.write(document); + writer.close(); + } catch (Exception e) { + throw new Exception("writeForDdl error.", e); + } + } - private static void writeForDdlExternalProperty(Element properties) throws Exception { - Element property = properties.addElement("property"); - property.addAttribute("name", "javax.persistence.jdbc.driver"); - property.addAttribute("value", Config.externalDataSources().get(0).getDriverClassName()); - property = properties.addElement("property"); - property.addAttribute("name", "javax.persistence.jdbc.url"); - property.addAttribute("value", Config.externalDataSources().get(0).getUrl()); - property = properties.addElement("property"); - property.addAttribute("name", "javax.persistence.jdbc.user"); - property.addAttribute("value", Config.externalDataSources().get(0).getUsername()); - property = properties.addElement("property"); - property.addAttribute("name", "javax.persistence.jdbc.password"); - property.addAttribute("value", Config.externalDataSources().get(0).getPassword()); - property = properties.addElement("property"); - property.addAttribute("name", "openjpa.DynamicEnhancementAgent"); - property.addAttribute("value", "false"); - } + private static void writeForDdlExternalProperty(Element properties) throws Exception { + Element property = properties.addElement("property"); + property.addAttribute("name", "javax.persistence.jdbc.driver"); + property.addAttribute("value", Config.externalDataSources().get(0).getDriverClassName()); + property = properties.addElement("property"); + property.addAttribute("name", "javax.persistence.jdbc.url"); + property.addAttribute("value", Config.externalDataSources().get(0).getUrl()); + property = properties.addElement("property"); + property.addAttribute("name", "javax.persistence.jdbc.user"); + property.addAttribute("value", Config.externalDataSources().get(0).getUsername()); + property = properties.addElement("property"); + property.addAttribute("name", "javax.persistence.jdbc.password"); + property.addAttribute("value", Config.externalDataSources().get(0).getPassword()); + property = properties.addElement("property"); + property.addAttribute("name", "openjpa.DynamicEnhancementAgent"); + property.addAttribute("value", "false"); + } - private static void writeForDdlInternalProperty(Element properties) throws Exception { - Element property = properties.addElement("property"); - property.addAttribute("name", "javax.persistence.jdbc.driver"); - property.addAttribute("value", SlicePropertiesBuilder.driver_h2); - property = properties.addElement("property"); - property.addAttribute("name", "javax.persistence.jdbc.url"); - Node node = Config.currentNode(); - String url = "jdbc:h2:tcp://" + Config.node() + ":" + node.getData().getTcpPort() + "/X;JMX=" - + (node.getData().getJmxEnable() ? "TRUE" : "FALSE") + ";CACHE_SIZE=" - + (node.getData().getCacheSize() * 1024); - property.addAttribute("value", url); - property = properties.addElement("property"); - property.addAttribute("name", "javax.persistence.jdbc.user"); - property.addAttribute("value", "sa"); - property = properties.addElement("property"); - property.addAttribute("name", "javax.persistence.jdbc.password"); - property.addAttribute("value", Config.token().getPassword()); - property = properties.addElement("property"); - property.addAttribute("name", "openjpa.DynamicEnhancementAgent"); - property.addAttribute("value", "false"); - } + private static void writeForDdlInternalProperty(Element properties) throws Exception { + Element property = properties.addElement("property"); + property.addAttribute("name", "javax.persistence.jdbc.driver"); + property.addAttribute("value", SlicePropertiesBuilder.driver_h2); + property = properties.addElement("property"); + property.addAttribute("name", "javax.persistence.jdbc.url"); + Node node = Config.currentNode(); + String url = "jdbc:h2:tcp://" + Config.node() + ":" + node.getData().getTcpPort() + "/X;JMX=" + + (node.getData().getJmxEnable() ? "TRUE" : "FALSE") + ";CACHE_SIZE=" + + (node.getData().getCacheSize() * 1024); + property.addAttribute("value", url); + property = properties.addElement("property"); + property.addAttribute("name", "javax.persistence.jdbc.user"); + property.addAttribute("value", "sa"); + property = properties.addElement("property"); + property.addAttribute("name", "javax.persistence.jdbc.password"); + property.addAttribute("value", Config.token().getPassword()); + property = properties.addElement("property"); + property.addAttribute("name", "openjpa.DynamicEnhancementAgent"); + property.addAttribute("value", "false"); + } - @SuppressWarnings("unchecked") - public static List write(String path, List entities, boolean loadDynamicEntityClass, - ClassLoader classLoader) { - List names = new ArrayList<>(); - String name = ""; - try { - names.addAll((List) Config.resource(Config.RESOURCE_CONTAINERENTITYNAMES)); - names = ListTools.includesExcludesWildcard(names, entities, null); - Document document = DocumentHelper.createDocument(); - Element persistence = createPersistenceElement(document); - ClassLoader cl = (null == classLoader) ? Thread.currentThread().getContextClassLoader() : classLoader; - for (String className : names) { - name = className; - Class clazz = (Class) cl.loadClass(className); - Element unit = persistence.addElement("persistence-unit"); - unit.addAttribute("name", className); - unit.addAttribute("transaction-type", "RESOURCE_LOCAL"); - Element provider = unit.addElement("provider"); - provider.addText(PersistenceProviderImpl.class.getName()); - for (Class o : JpaObjectTools.scanMappedSuperclass(clazz)) { - unit.addElement("class").addText(o.getName()); - } - } - if (loadDynamicEntityClass) { - names.addAll(addDynamicClassCreateCombineUnit(persistence, cl)); - } - OutputFormat format = OutputFormat.createPrettyPrint(); - format.setEncoding("UTF-8"); - File file = new File(path); - FileUtils.touch(file); - XMLWriter writer = new XMLWriter(new FileWriter(file), format); - writer.write(document); - writer.close(); - return names; - } catch (Exception e) { - throw new IllegalStateException("write error.className:" + name, e); - } - } + @SuppressWarnings("unchecked") + public static List write(String path, List entities, boolean loadDynamicEntityClass, + ClassLoader classLoader) { + List names = new ArrayList<>(); + String name = ""; + try { + names.addAll((List) Config.resource(Config.RESOURCE_CONTAINERENTITYNAMES)); + names = ListTools.includesExcludesWildcard(names, entities, null); + Document document = DocumentHelper.createDocument(); + Element persistence = createPersistenceElement(document); + ClassLoader cl = (null == classLoader) ? Thread.currentThread().getContextClassLoader() : classLoader; + for (String className : names) { + name = className; + Class clazz = (Class) cl.loadClass(className); + Element unit = persistence.addElement("persistence-unit"); + unit.addAttribute("name", className); + unit.addAttribute("transaction-type", "RESOURCE_LOCAL"); + Element provider = unit.addElement("provider"); + provider.addText(PersistenceProviderImpl.class.getName()); + for (Class o : JpaObjectTools.scanMappedSuperclass(clazz)) { + unit.addElement("class").addText(o.getName()); + } + } + if (loadDynamicEntityClass) { + names.addAll(addDynamicClassCreateCombineUnit(persistence, cl)); + } + OutputFormat format = OutputFormat.createPrettyPrint(); + format.setEncoding("UTF-8"); + File file = new File(path); + FileUtils.touch(file); + XMLWriter writer = new XMLWriter(new FileWriter(file), format); + writer.write(document); + writer.close(); + return names; + } catch (Exception e) { + throw new IllegalStateException("write error.className:" + name, e); + } + } - private static Collection addDynamicClassCreateCombineUnit(Element persistence, ClassLoader cl) - throws ClassNotFoundException { - Set names = new TreeSet<>(); - Set combineNames = new TreeSet<>(); - try (ScanResult sr = new ClassGraph().addClassLoader(cl).enableAnnotationInfo().scan()) { - for (ClassInfo info : sr.getClassesWithAnnotation(ContainerEntity.class.getName())) { - Class cls = cl.loadClass(info.getName()); - if (StringUtils.startsWith(cls.getName(), DynamicEntity.CLASS_PACKAGE)) { - names.add(cls.getName()); - for (Class o : JpaObjectTools.scanMappedSuperclass(cls)) { - combineNames.add(o.getName()); - } - } - } - } - if (!names.isEmpty()) { - for (String className : names) { - @SuppressWarnings("unchecked") - Class clazz = (Class) cl.loadClass(className); - Element unit = persistence.addElement("persistence-unit"); - unit.addAttribute("name", className); - unit.addAttribute("transaction-type", "RESOURCE_LOCAL"); - Element provider = unit.addElement("provider"); - provider.addText(PersistenceProviderImpl.class.getName()); - for (Class o : JpaObjectTools.scanMappedSuperclass(clazz)) { - unit.addElement("class").addText(o.getName()); - } - } - } - Element unit = persistence.addElement("persistence-unit"); - unit.addAttribute("name", DynamicBaseEntity.class.getName()); - unit.addAttribute("transaction-type", "RESOURCE_LOCAL"); - unit.addElement("provider").addText(PersistenceProviderImpl.class.getName()); - for (String name : combineNames) { - unit.addElement("class").addText(name); - } - return names; - } + private static Collection addDynamicClassCreateCombineUnit(Element persistence, ClassLoader cl) + throws ClassNotFoundException { + Set names = new TreeSet<>(); + Set combineNames = new TreeSet<>(); + try (ScanResult sr = new ClassGraph().addClassLoader(cl).enableAnnotationInfo().scan()) { + for (ClassInfo info : sr.getClassesWithAnnotation(ContainerEntity.class.getName())) { + Class cls = cl.loadClass(info.getName()); + if (StringUtils.startsWith(cls.getName(), DynamicEntity.CLASS_PACKAGE)) { + names.add(cls.getName()); + for (Class o : JpaObjectTools.scanMappedSuperclass(cls)) { + combineNames.add(o.getName()); + } + } + } + } + if (!names.isEmpty()) { + for (String className : names) { + @SuppressWarnings("unchecked") + Class clazz = (Class) cl.loadClass(className); + Element unit = persistence.addElement("persistence-unit"); + unit.addAttribute("name", className); + unit.addAttribute("transaction-type", "RESOURCE_LOCAL"); + Element provider = unit.addElement("provider"); + provider.addText(PersistenceProviderImpl.class.getName()); + for (Class o : JpaObjectTools.scanMappedSuperclass(clazz)) { + unit.addElement("class").addText(o.getName()); + } + } + } + Element unit = persistence.addElement("persistence-unit"); + unit.addAttribute("name", DynamicBaseEntity.class.getName()); + unit.addAttribute("transaction-type", "RESOURCE_LOCAL"); + unit.addElement("provider").addText(PersistenceProviderImpl.class.getName()); + for (String name : combineNames) { + unit.addElement("class").addText(name); + } + return names; + } - public static Properties properties(String className, boolean sliceFeatureEnable) throws Exception { - if (sliceFeatureEnable) { - if (BooleanUtils.isTrue(Config.externalDataSources().enable())) { - return propertiesExternalSlice(className); - } else { - return propertiesInternalSlice(className); - } - } else { - if (BooleanUtils.isTrue(Config.externalDataSources().enable())) { - return propertiesExternalSingle(className); - } else { - return propertiesInternalSingle(className); - } - } - } + public static Properties properties(String className, boolean sliceFeatureEnable) throws Exception { + if (sliceFeatureEnable) { + if (BooleanUtils.isTrue(Config.externalDataSources().enable())) { + return propertiesExternalSlice(className); + } else { + return propertiesInternalSlice(className); + } + } else { + if (BooleanUtils.isTrue(Config.externalDataSources().enable())) { + return propertiesExternalSingle(className); + } else { + return propertiesInternalSingle(className); + } + } + } - private static Properties propertiesBaseSlice(String className) throws Exception { - Properties properties = new Properties(); - properties.put("openjpa.BrokerFactory", "slice"); - properties.put("openjpa.slice.Lenient", "false"); - properties.put("openjpa.slice.DistributionPolicy", FactorDistributionPolicy.class.getName()); - properties.put("openjpa.QueryCompilationCache", "false"); - properties.put("openjpa.IgnoreChanges", "true"); - properties.put("openjpa.QueryCache", "false"); - properties.put("openjpa.QueryCompilationCache", "false"); - properties.put("openjpa.LockManager", "none"); - properties.put("openjpa.jdbc.ResultSetType", "scroll-insensitive"); - /* 如果启用本地初始化会导致classLoad的问题 */ - properties.put("openjpa.DynamicEnhancementAgent", "false"); - properties.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=false)"); - properties.put("openjpa.Log", "DefaultLevel=WARN"); - return properties; - } + private static Properties propertiesBaseSlice(String className) throws Exception { + Properties properties = new Properties(); + properties.put("openjpa.BrokerFactory", "slice"); + properties.put("openjpa.slice.Lenient", "false"); + properties.put("openjpa.slice.DistributionPolicy", FactorDistributionPolicy.class.getName()); + properties.put("openjpa.QueryCompilationCache", "false"); + properties.put("openjpa.IgnoreChanges", "true"); + properties.put("openjpa.QueryCache", "false"); + properties.put("openjpa.QueryCompilationCache", "false"); + properties.put("openjpa.LockManager", "none"); + properties.put("openjpa.jdbc.ResultSetType", "scroll-insensitive"); + /* 如果启用本地初始化会导致classLoad的问题 */ + properties.put("openjpa.DynamicEnhancementAgent", "false"); + properties.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=false)"); + properties.put("openjpa.Log", "DefaultLevel=WARN"); + return properties; + } - private static Properties propertiesExternalSlice(String className) throws Exception { - Properties properties = propertiesBaseSlice(className); - properties.put("openjpa.jdbc.DBDictionary", Config.externalDataSources().dictionary()); - /* 如果是DB2 添加 Schema,mysql 不需要Schema 如果用了Schema H2数据库就会报错说没有Schema */ - if (Config.externalDataSources().hasSchema()) { - properties.put("openjpa.jdbc.Schema", JpaObject.default_schema); - } - properties.put("openjpa.slice.Names", - StringUtils.join(Config.externalDataSources().findNamesOfContainerEntity(className), ",")); - for (String name : Config.externalDataSources().findNamesOfContainerEntity(className)) { - properties.put("openjpa.slice." + name + ".ConnectionFactoryName", Config.RESOURCE_JDBC_PREFIX + name); - properties.put("openjpa.slice." + name + ".Log", Config.externalDataSources().log(name)); - } - return properties; - } + private static Properties propertiesExternalSlice(String className) throws Exception { + Properties properties = propertiesBaseSlice(className); + properties.put("openjpa.jdbc.DBDictionary", Config.externalDataSources().dictionary()); + /* 如果是DB2 添加 Schema,mysql 不需要Schema 如果用了Schema H2数据库就会报错说没有Schema */ + if (Config.externalDataSources().hasSchema()) { + properties.put("openjpa.jdbc.Schema", Config.externalDataSources().schema()); + } + properties.put("openjpa.slice.Names", + StringUtils.join(Config.externalDataSources().findNamesOfContainerEntity(className), ",")); + for (String name : Config.externalDataSources().findNamesOfContainerEntity(className)) { + properties.put("openjpa.slice." + name + ".ConnectionFactoryName", Config.RESOURCE_JDBC_PREFIX + name); + properties.put("openjpa.slice." + name + ".Log", Config.externalDataSources().log(name)); + } + return properties; + } - private static Properties propertiesInternalSlice(String className) throws Exception { - Properties properties = propertiesBaseSlice(className); - properties.put("openjpa.jdbc.DBDictionary", SlicePropertiesBuilder.dictionary_h2); - properties.put("openjpa.slice.Names", - StringUtils.join(Config.nodes().dataServers().findNamesOfContainerEntity(className), ",")); - for (String name : Config.nodes().dataServers().findNamesOfContainerEntity(className)) { - properties.put("openjpa.slice." + name + ".ConnectionFactoryName", Config.RESOURCE_JDBC_PREFIX + name); - properties.put("openjpa.slice." + name + ".Log", Config.nodes().dataServers().log(name)); - } - return properties; - } + private static Properties propertiesInternalSlice(String className) throws Exception { + Properties properties = propertiesBaseSlice(className); + properties.put("openjpa.jdbc.DBDictionary", SlicePropertiesBuilder.dictionary_h2); + properties.put("openjpa.slice.Names", + StringUtils.join(Config.nodes().dataServers().findNamesOfContainerEntity(className), ",")); + for (String name : Config.nodes().dataServers().findNamesOfContainerEntity(className)) { + properties.put("openjpa.slice." + name + ".ConnectionFactoryName", Config.RESOURCE_JDBC_PREFIX + name); + properties.put("openjpa.slice." + name + ".Log", Config.nodes().dataServers().log(name)); + } + return properties; + } - private static Properties propertiesBaseSingle(String className) throws Exception { - Properties properties = new Properties(); - properties.put("openjpa.QueryCompilationCache", "false"); - properties.put("openjpa.IgnoreChanges", "true"); - properties.put("openjpa.QueryCache", "false"); - properties.put("openjpa.QueryCompilationCache", "false"); - properties.put("openjpa.LockManager", "none"); - properties.put("openjpa.jdbc.ResultSetType", "scroll-insensitive"); - // 使用ture支持多线程访问,但是是通过lock同步执行的. - properties.put("openjpa.Multithreaded", "true"); - /* 如果启用本地初始化会导致classLoad的问题 */ - properties.put("openjpa.DynamicEnhancementAgent", "false"); - properties.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=false)"); - return properties; - } + private static Properties propertiesBaseSingle(String className) throws Exception { + Properties properties = new Properties(); + properties.put("openjpa.QueryCompilationCache", "false"); + properties.put("openjpa.IgnoreChanges", "true"); + properties.put("openjpa.QueryCache", "false"); + properties.put("openjpa.QueryCompilationCache", "false"); + properties.put("openjpa.LockManager", "none"); + properties.put("openjpa.jdbc.ResultSetType", "scroll-insensitive"); + // 使用ture支持多线程访问,但是是通过lock同步执行的. + properties.put("openjpa.Multithreaded", "true"); + /* 如果启用本地初始化会导致classLoad的问题 */ + properties.put("openjpa.DynamicEnhancementAgent", "false"); + properties.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=false)"); + return properties; + } - private static Properties propertiesExternalSingle(String className) throws Exception { - Properties properties = propertiesBaseSingle(className); - properties.put("openjpa.jdbc.DBDictionary", Config.externalDataSources().dictionary()); - /* 如果是DB2 添加 Schema,mysql 不需要Schema 如果用了Schema H2数据库就会报错说没有Schema */ - if (Config.externalDataSources().hasSchema()) { - properties.put("openjpa.jdbc.Schema", JpaObject.default_schema); - } - if (StringUtils.isNotEmpty(Config.externalDataSources().getTransactionIsolation())) { - properties.put("openjpa.jdbc.TransactionIsolation", Config.externalDataSources().getTransactionIsolation()); - } - for (String name : Config.externalDataSources().findNamesOfContainerEntity(className)) { - properties.put("openjpa.ConnectionFactoryName", Config.RESOURCE_JDBC_PREFIX + name); - properties.put("openjpa.Log", Config.externalDataSources().log(name)); - break; - } - return properties; - } + private static Properties propertiesExternalSingle(String className) throws Exception { + Properties properties = propertiesBaseSingle(className); + properties.put("openjpa.jdbc.DBDictionary", Config.externalDataSources().dictionary()); + /* 如果是DB2 添加 Schema,mysql 不需要Schema 如果用了Schema H2数据库就会报错说没有Schema */ + if (Config.externalDataSources().hasSchema()) { + properties.put("openjpa.jdbc.Schema", Config.externalDataSources().schema()); + } + if (StringUtils.isNotEmpty(Config.externalDataSources().getTransactionIsolation())) { + properties.put("openjpa.jdbc.TransactionIsolation", Config.externalDataSources().getTransactionIsolation()); + } + for (String name : Config.externalDataSources().findNamesOfContainerEntity(className)) { + properties.put("openjpa.ConnectionFactoryName", Config.RESOURCE_JDBC_PREFIX + name); + properties.put("openjpa.Log", Config.externalDataSources().log(name)); + break; + } + return properties; + } - private static Properties propertiesInternalSingle(String className) throws Exception { - Properties properties = propertiesBaseSingle(className); - properties.put("openjpa.jdbc.DBDictionary", SlicePropertiesBuilder.dictionary_h2); - for (String name : Config.nodes().dataServers().findNamesOfContainerEntity(className)) { - properties.put("openjpa.ConnectionFactoryName", Config.RESOURCE_JDBC_PREFIX + name); - properties.put("openjpa.Log", Config.nodes().dataServers().log(name)); - break; - } - return properties; - } + private static Properties propertiesInternalSingle(String className) throws Exception { + Properties properties = propertiesBaseSingle(className); + properties.put("openjpa.jdbc.DBDictionary", SlicePropertiesBuilder.dictionary_h2); + for (String name : Config.nodes().dataServers().findNamesOfContainerEntity(className)) { + properties.put("openjpa.ConnectionFactoryName", Config.RESOURCE_JDBC_PREFIX + name); + properties.put("openjpa.Log", Config.nodes().dataServers().log(name)); + break; + } + return properties; + } } \ No newline at end of file diff --git a/o2server/x_base_core_project/src/main/java/com/x/base/core/container/factory/SlicePropertiesBuilder.java b/o2server/x_base_core_project/src/main/java/com/x/base/core/container/factory/SlicePropertiesBuilder.java index b6beb9f9eee352e3d22272d066e5bc07836616a9..288b1c90f5cb7f35c532593f7877a73efb0e7a7b 100644 --- a/o2server/x_base_core_project/src/main/java/com/x/base/core/container/factory/SlicePropertiesBuilder.java +++ b/o2server/x_base_core_project/src/main/java/com/x/base/core/container/factory/SlicePropertiesBuilder.java @@ -4,183 +4,183 @@ import org.apache.commons.lang3.StringUtils; public class SlicePropertiesBuilder { - private SlicePropertiesBuilder() { - // nothing - } + private SlicePropertiesBuilder() { + // nothing + } - public static String driver_db2 = "com.ibm.db2.jcc.DB2Driver"; - public static String driver_oracle = "oracle.jdbc.OracleDriver"; - public static String driver_mysql = "com.mysql.cj.jdbc.Driver"; - public static String driver_postgresql = "org.postgresql.Driver"; - public static String driver_informix = "com.informix.jdbc.IfxDriver"; - public static String driver_h2 = "org.h2.Driver"; - public static String driver_dm = "dm.jdbc.driver.DmDriver"; - public static String driver_sqlserver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; - public static String driver_gbase = "com.gbasedbt.jdbc.Driver"; - public static String driver_gbasemysql = "com.gbase.cj.jdbc.Driver"; - public static String driver_kingbase = "com.kingbase.Driver"; - public static String driver_kingbase8 = "com.kingbase8.Driver"; - public static String driver_oscar = "com.oscar.Driver"; - /* 避免db2在aix版本和lwl版本字段长度不一致的问题 */ - public static String dictionary_db2 = "db2(createPrimaryKeys=false,characterColumnSize=255,maxColumnNameLength=128,maxIndexNameLength=128,maxConstraintNameLength=128)"; - public static String dictionary_oracle = "oracle(maxTableNameLength=128,maxColumnNameLength=128,maxIndexNameLength=128,maxConstraintNameLength=128,maxEmbeddedClobSize=-1,maxEmbeddedBlobSize=-1)"; - public static String dictionary_mysql = "mysql(clobTypeName=LONGTEXT,blobTypeName=LONGBLOB,createPrimaryKeys=false,maxIndexesPerTable=64)"; - public static String dictionary_postgresql = "postgres"; - public static String dictionary_informix = "informix"; - public static String dictionary_h2 = "org.apache.openjpa.jdbc.sql.H2Dictionary"; - public static String dictionary_dm = "com.x.base.core.openjpa.jdbc.sql.DMDictionary"; - public static String dictionary_sqlserver = "sqlserver(schemaCase=preserve)"; - public static String dictionary_gbase = "com.x.base.core.openjpa.jdbc.sql.GBaseDictionary"; - public static String dictionary_gbasemysql = "com.x.base.core.openjpa.jdbc.sql.GBaseMySQLDictionary"; - public static String dictionary_kingbase = "com.x.base.core.openjpa.jdbc.sql.KingbaseDictionary"; - public static String dictionary_kingbase8 = "com.x.base.core.openjpa.jdbc.sql.Kingbase8Dictionary"; - public static String dictionary_oscar = "com.x.base.core.openjpa.jdbc.sql.OscarDictionary"; + public static String driver_db2 = "com.ibm.db2.jcc.DB2Driver"; + public static String driver_oracle = "oracle.jdbc.OracleDriver"; + public static String driver_mysql = "com.mysql.cj.jdbc.Driver"; + public static String driver_postgresql = "org.postgresql.Driver"; + public static String driver_informix = "com.informix.jdbc.IfxDriver"; + public static String driver_h2 = "org.h2.Driver"; + public static String driver_dm = "dm.jdbc.driver.DmDriver"; + public static String driver_sqlserver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; + public static String driver_gbase = "com.gbasedbt.jdbc.Driver"; + public static String driver_gbasemysql = "com.gbase.cj.jdbc.Driver"; + public static String driver_kingbase = "com.kingbase.Driver"; + public static String driver_kingbase8 = "com.kingbase8.Driver"; + public static String driver_oscar = "com.oscar.Driver"; + /* 避免db2在aix版本和lwl版本字段长度不一致的问题 */ + public static String dictionary_db2 = "db2(createPrimaryKeys=false,characterColumnSize=255,maxColumnNameLength=128,maxIndexNameLength=128,maxConstraintNameLength=128)"; + public static String dictionary_oracle = "oracle(maxTableNameLength=128,maxColumnNameLength=128,maxIndexNameLength=128,maxConstraintNameLength=128,maxEmbeddedClobSize=-1,maxEmbeddedBlobSize=-1)"; + public static String dictionary_mysql = "mysql(clobTypeName=LONGTEXT,blobTypeName=LONGBLOB,createPrimaryKeys=false,maxIndexesPerTable=64)"; + public static String dictionary_postgresql = "postgres"; + public static String dictionary_informix = "informix"; + public static String dictionary_h2 = "org.apache.openjpa.jdbc.sql.H2Dictionary"; + public static String dictionary_dm = "com.x.base.core.openjpa.jdbc.sql.DMDictionary"; + public static String dictionary_sqlserver = "sqlserver(schemaCase=preserve)"; + public static String dictionary_gbase = "com.x.base.core.openjpa.jdbc.sql.GBaseDictionary"; + public static String dictionary_gbasemysql = "com.x.base.core.openjpa.jdbc.sql.GBaseMySQLDictionary"; + public static String dictionary_kingbase = "com.x.base.core.openjpa.jdbc.sql.KingbaseDictionary"; + public static String dictionary_kingbase8 = "com.x.base.core.openjpa.jdbc.sql.Kingbase8Dictionary"; + public static String dictionary_oscar = "com.x.base.core.openjpa.jdbc.sql.OscarDictionary"; - public static String validationQuery_db2 = "select 1 from sysibm.sysdummy1"; - public static String validationQuery_oracle = "select 1 from dual"; - public static String validationQuery_mysql = "select 1"; - public static String validationQuery_postgresql = "select 1"; - public static String validationQuery_informix = "select 1"; - public static String validationQuery_h2 = "select 1"; - public static String validationQuery_dm = "select getdate()"; - public static String validationQuery_sqlserver = "select 1"; - public static String validationQuery_gbase = "select 1 from dual"; - public static String validationQuery_gbasemysql = "select now()"; - public static String validationQuery_kingbase = "select now()"; - public static String validationQuery_kingbase8 = "select now()"; - public static String validationQuery_oscar = "select 1 from dual"; + public static String validationQuery_db2 = "select 1 from sysibm.sysdummy1"; + public static String validationQuery_oracle = "select 1 from dual"; + public static String validationQuery_mysql = "select 1"; + public static String validationQuery_postgresql = "select 1"; + public static String validationQuery_informix = "select 1"; + public static String validationQuery_h2 = "select 1"; + public static String validationQuery_dm = "select getdate()"; + public static String validationQuery_sqlserver = "select 1"; + public static String validationQuery_gbase = "select 1 from dual"; + public static String validationQuery_gbasemysql = "select now()"; + public static String validationQuery_kingbase = "select now()"; + public static String validationQuery_kingbase8 = "select now()"; + public static String validationQuery_oscar = "select 1 from dual"; - // 单个slice名称 - public static String getName(Integer i) throws Exception { - try { - return "s" + ((1001 + i) + "").substring(1); - } catch (Exception e) { - throw new Exception("can not create slice name property", e); - } - } + // 单个slice名称 + public static String getName(Integer i) throws Exception { + try { + return "s" + ((1001 + i) + "").substring(1); + } catch (Exception e) { + throw new Exception("can not create slice name property", e); + } + } - public static String driverClassNameOfUrl(String url) throws Exception { - if (StringUtils.containsIgnoreCase(url, "jdbc:db2:")) { - return driver_db2; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:oracle:")) { - return driver_oracle; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:mysql:")) { - return driver_mysql; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:postgresql:")) { - return driver_postgresql; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:informix-sqli:")) { - return driver_informix; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:gbasedbt-sqli:")) { - return driver_gbase; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:gbase:")) { - return driver_gbasemysql; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:h2:tcp:")) { - return driver_h2; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:dm:")) { - return driver_dm; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:sqlserver:")) { - return driver_sqlserver; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:kingbase:")) { - return driver_kingbase; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:kingbase8:")) { - return driver_kingbase8; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:oscar:")) { - return driver_oscar; - } - throw new Exception("can not get driverClassName of url: " + url + "."); - } + public static String driverClassNameOfUrl(String url) throws Exception { + if (StringUtils.containsIgnoreCase(url, "jdbc:db2:")) { + return driver_db2; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:oracle:")) { + return driver_oracle; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:mysql:")) { + return driver_mysql; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:postgresql:")) { + return driver_postgresql; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:informix-sqli:")) { + return driver_informix; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:gbasedbt-sqli:")) { + return driver_gbase; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:gbase:")) { + return driver_gbasemysql; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:h2:tcp:")) { + return driver_h2; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:dm:")) { + return driver_dm; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:sqlserver:")) { + return driver_sqlserver; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:kingbase:")) { + return driver_kingbase; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:kingbase8:")) { + return driver_kingbase8; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:oscar:")) { + return driver_oscar; + } + throw new Exception("can not get driverClassName of url: " + url + "."); + } - public static String dictionaryOfUrl(String url) throws Exception { - if (StringUtils.containsIgnoreCase(url, "jdbc:db2:")) { - return dictionary_db2; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:oracle:")) { - return dictionary_oracle; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:mysql:")) { - return dictionary_mysql; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:postgresql:")) { - return dictionary_postgresql; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:informix-sqli:")) { - return dictionary_informix; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:gbasedbt-sqli:")) { - return dictionary_gbase; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:gbase:")) { - return dictionary_gbasemysql; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:h2:tcp:")) { - return dictionary_h2; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:dm:")) { - return dictionary_dm; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:sqlserver:")) { - return dictionary_sqlserver; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:kingbase:")) { - return dictionary_kingbase; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:kingbase8:")) { - return dictionary_kingbase8; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:oscar:")) { - return dictionary_oscar; - } - throw new Exception("can not get dictionary of url: " + url + "."); - } + public static String dictionaryOfUrl(String url) throws Exception { + if (StringUtils.containsIgnoreCase(url, "jdbc:db2:")) { + return dictionary_db2; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:oracle:")) { + return dictionary_oracle; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:mysql:")) { + return dictionary_mysql; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:postgresql:")) { + return dictionary_postgresql; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:informix-sqli:")) { + return dictionary_informix; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:gbasedbt-sqli:")) { + return dictionary_gbase; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:gbase:")) { + return dictionary_gbasemysql; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:h2:tcp:")) { + return dictionary_h2; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:dm:")) { + return dictionary_dm; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:sqlserver:")) { + return dictionary_sqlserver; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:kingbase:")) { + return dictionary_kingbase; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:kingbase8:")) { + return dictionary_kingbase8; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:oscar:")) { + return dictionary_oscar; + } + throw new Exception("can not get dictionary of url: " + url + "."); + } - public static boolean hasSchemaOfUrl(String url) throws Exception { - if (StringUtils.containsIgnoreCase(url, "jdbc:db2:")) { - return true; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:oracle:")) { - return false; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:mysql:")) { - return false; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:postgresql:")) { - return false; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:informix-sqli:")) { - return true; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:gbasedbt-sqli:")) { - return true; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:gbase:")) { - return false; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:h2:tcp:")) { - return false; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:dm:")) { - return true; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:sqlserver:")) { - return false; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:kingbase:")) { - return true; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:kingbase8:")) { - return true; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:oscar:")) { - return true; - } - throw new Exception("can not get schema of url: " + url + "."); - } + public static boolean hasSchemaOfUrl(String url) throws Exception { + if (StringUtils.containsIgnoreCase(url, "jdbc:db2:")) { + return true; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:oracle:")) { + return true; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:mysql:")) { + return false; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:postgresql:")) { + return false; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:informix-sqli:")) { + return true; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:gbasedbt-sqli:")) { + return true; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:gbase:")) { + return false; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:h2:tcp:")) { + return false; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:dm:")) { + return true; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:sqlserver:")) { + return false; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:kingbase:")) { + return true; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:kingbase8:")) { + return true; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:oscar:")) { + return true; + } + throw new Exception("can not get schema of url: " + url + "."); + } - public static String validationQueryOfUrl(String url) throws Exception { - if (StringUtils.containsIgnoreCase(url, "jdbc:db2:")) { - return validationQuery_db2; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:oracle:")) { - return validationQuery_oracle; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:mysql:")) { - return validationQuery_mysql; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:postgresql:")) { - return validationQuery_postgresql; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:informix-sqli:")) { - return validationQuery_informix; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:gbasedbt-sqli:")) { - return validationQuery_gbase; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:gbase:")) { - return validationQuery_gbasemysql; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:h2:tcp:")) { - return validationQuery_h2; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:dm:")) { - return validationQuery_dm; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:sqlserver:")) { - return validationQuery_sqlserver; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:kingbase:")) { - return validationQuery_kingbase; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:kingbase8:")) { - return validationQuery_kingbase8; - } else if (StringUtils.containsIgnoreCase(url, "jdbc:oscar:")) { - return validationQuery_oscar; - } - throw new Exception("can not get schema of url: " + url + "."); - } + public static String validationQueryOfUrl(String url) throws Exception { + if (StringUtils.containsIgnoreCase(url, "jdbc:db2:")) { + return validationQuery_db2; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:oracle:")) { + return validationQuery_oracle; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:mysql:")) { + return validationQuery_mysql; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:postgresql:")) { + return validationQuery_postgresql; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:informix-sqli:")) { + return validationQuery_informix; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:gbasedbt-sqli:")) { + return validationQuery_gbase; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:gbase:")) { + return validationQuery_gbasemysql; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:h2:tcp:")) { + return validationQuery_h2; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:dm:")) { + return validationQuery_dm; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:sqlserver:")) { + return validationQuery_sqlserver; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:kingbase:")) { + return validationQuery_kingbase; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:kingbase8:")) { + return validationQuery_kingbase8; + } else if (StringUtils.containsIgnoreCase(url, "jdbc:oscar:")) { + return validationQuery_oscar; + } + throw new Exception("can not get schema of url: " + url + "."); + } } \ No newline at end of file diff --git a/o2server/x_base_core_project/src/main/java/com/x/base/core/project/config/ExternalDataSource.java b/o2server/x_base_core_project/src/main/java/com/x/base/core/project/config/ExternalDataSource.java index 79f8a5124640f26a5469d9ac4ddbdcc1fe07c012..d4971898c27401be5dc3bfdce4fd67c8e5d5baff 100644 --- a/o2server/x_base_core_project/src/main/java/com/x/base/core/project/config/ExternalDataSource.java +++ b/o2server/x_base_core_project/src/main/java/com/x/base/core/project/config/ExternalDataSource.java @@ -12,251 +12,259 @@ import com.x.base.core.project.tools.Crypto; public class ExternalDataSource extends ConfigObject { - // 无需保存 - private transient String _password; - - public ExternalDataSource() { - } - - public static final Boolean DEFAULT_ENABLE = false; - - public static final String DEFAULT_URL = "jdbc:mysql://127.0.0.1:3306/X?autoReconnect=true&allowPublicKeyRetrieval=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8"; - - public static final String DEFAULT_USERNAME = "root"; - - public static final String DEFAULT_PASSWORD = "password"; - - public static final String DEFAULT_DRIVERCLASSNAME = ""; - - public static final String DEFAULT_DICTIONARY = ""; - - public static final Integer DEFAULT_MAXTOTAL = 100; - - public static final Integer DEFAULT_MAXIDLE = 0; - - public static final Boolean DEFAULT_STATENABLE = true; - - public static final String DEFAULT_STATFILTER = "mergeStat"; - - public static final List DEFAULT_INCLUDES = new ArrayList<>(); - - public static final List DEFAULT_EXCLUDES = new ArrayList<>(); - - public static final Integer DEFAULT_SLOWSQLMILLIS = 2000; - - public static final String DEFAULT_LOGLEVEL = "ERROR"; - - public static final String DEFAULT_TRANSACTIONISOLATION = "read-committed"; - - public static final Boolean DEFAULT_TESTCONNECTIONONCHECKIN = false; - - public static final Boolean DEFAULT_TESTCONNECTIONONCHECKOUT = false; - - public static final Integer DEFAULT_MAXIDLETIME = 300; - - public static final Boolean DEFAULT_AUTOCOMMIT = false; - - public static final Boolean DEFAULT_TRACESQLENABLE = false; - - public static ExternalDataSource defaultInstance() { - - ExternalDataSource o = new ExternalDataSource(); - o.enable = DEFAULT_ENABLE; - o.url = DEFAULT_URL; - o.username = DEFAULT_USERNAME; - o.password = DEFAULT_PASSWORD; - o.driverClassName = DEFAULT_DRIVERCLASSNAME; - o.dictionary = DEFAULT_DICTIONARY; - o.maxTotal = DEFAULT_MAXTOTAL; - o.maxIdle = DEFAULT_MAXIDLE; - o.statEnable = DEFAULT_STATENABLE; - o.statFilter = DEFAULT_STATFILTER; - o.slowSqlMillis = DEFAULT_SLOWSQLMILLIS; - o.includes = DEFAULT_INCLUDES; - o.excludes = DEFAULT_EXCLUDES; - o.logLevel = DEFAULT_LOGLEVEL; - o.transactionIsolation = DEFAULT_TRANSACTIONISOLATION; - o.testConnectionOnCheckin = DEFAULT_TESTCONNECTIONONCHECKIN; - o.testConnectionOnCheckout = DEFAULT_TESTCONNECTIONONCHECKOUT; - o.maxIdleTime = DEFAULT_MAXIDLETIME; - o.autoCommit = DEFAULT_AUTOCOMMIT; - o.traceSqlEnable = DEFAULT_TRACESQLENABLE; - return o; - } - - @FieldDescribe("是否启用,如果启用多个数据库,那么必须是相同类型的,不能混用,且用户名密码必须一致.") - private Boolean enable; - @FieldDescribe("jdbc连接地址.") - private String url; - @FieldDescribe("数据库jdbc连接用户名.") - private String username; - @FieldDescribe("数据库jdbc连接密码.") - private String password; - @FieldDescribe("数据库驱动类名.") - private String driverClassName; - @FieldDescribe("方言类.") - private String dictionary; - @FieldDescribe("最大使用连接数.") - private Integer maxTotal; - @FieldDescribe("最大空闲连接数.") - private Integer maxIdle; - @FieldDescribe("启用统计,默认启用.") - private Boolean statEnable; - @FieldDescribe("统计方式配置,默认mergeStat.") - private String statFilter; - @FieldDescribe("执行缓慢sql毫秒数,默认2000毫秒,执行缓慢的sql将被单独记录.") - private Integer slowSqlMillis; - @FieldDescribe("设置此数据库存储的类,默认情况下存储所有类型,如果需要对每个类进行单独的控制以达到高性能,可以将不同的类存储到不同的节点上提高性能.可以使用通配符*.") - private List includes; - @FieldDescribe("在此节点上不存储的类,和includes一起设置实际存储的类,可以使用通配符*.") - private List excludes; - @FieldDescribe("默认日志级别,FATAL, ERROR, WARN, INFO, TRACE. 完整的配置为DefaultLevel=WARN, Tool=TRACE, Enhance=TRACE, METADATA=TRACE, Runtime=TRACE, Query=TRACE, DataCache=TRACE, JDBC=TRACE, SQL=TRACE.") - private String logLevel = DEFAULT_LOGLEVEL; - @FieldDescribe("事务隔离级别:default,none,read-uncommitted,read-committed,repeatable-read,serializable.默认使用default(数据库设置的事务级别).") - private String transactionIsolation; - @FieldDescribe("测试入池连接,默认false.") - private Boolean testConnectionOnCheckin; - @FieldDescribe("测试出池连接,默认false.") - private Boolean testConnectionOnCheckout; - @FieldDescribe("空闲阈值,默认300秒.") - private Integer maxIdleTime; - @FieldDescribe("自动提交,默认为false.") - private Boolean autoCommit = DEFAULT_AUTOCOMMIT; - @FieldDescribe("启用sql跟踪.") - private Boolean traceSqlEnable = DEFAULT_TRACESQLENABLE; - - public Boolean getTraceSqlEnable() { - return (null == this.traceSqlEnable) ? DEFAULT_TRACESQLENABLE : this.traceSqlEnable; - } - - public Boolean getAutoCommit() { - return (null == this.autoCommit) ? DEFAULT_AUTOCOMMIT : this.autoCommit; - } - - public Integer getMaxIdleTime() { - return maxIdleTime == null ? DEFAULT_MAXIDLETIME : this.maxIdleTime; - } - - public Boolean getTestConnectionOnCheckin() { - return this.testConnectionOnCheckin == null ? DEFAULT_TESTCONNECTIONONCHECKIN : this.testConnectionOnCheckin; - } - - public Boolean getTestConnectionOnCheckout() { - return this.testConnectionOnCheckout == null ? DEFAULT_TESTCONNECTIONONCHECKOUT : this.testConnectionOnCheckout; - } - - public String getTransactionIsolation() { - return StringUtils.isEmpty(this.transactionIsolation) ? DEFAULT_TRANSACTIONISOLATION - : this.transactionIsolation; - } - - public String getLogLevel() { - return StringUtils.isEmpty(this.logLevel) ? DEFAULT_LOGLEVEL : this.logLevel; - } - - public String getDriverClassName() throws Exception { - return StringUtils.isEmpty(this.driverClassName) ? SlicePropertiesBuilder.driverClassNameOfUrl(this.url) - : this.driverClassName; - } - - public String getDictionary() throws Exception { - return StringUtils.isEmpty(this.dictionary) ? SlicePropertiesBuilder.dictionaryOfUrl(this.url) - : this.dictionary; - } - - public Integer getSlowSqlMillis() { - return (null == this.slowSqlMillis || this.slowSqlMillis < 1) ? DEFAULT_SLOWSQLMILLIS : this.slowSqlMillis; - } - - public String getStatFilter() { - return StringUtils.isEmpty(this.statFilter) ? DEFAULT_STATFILTER : this.statFilter; - } - - public Boolean getStatEnable() { - return null == statEnable ? DEFAULT_STATENABLE : this.statEnable; - } - - public Integer getMaxIdle() { - if ((this.maxIdle == null) || (this.maxIdle < 1)) { - return DEFAULT_MAXIDLE; - } else { - return this.maxTotal; - } - } - - public Integer getMaxTotal() { - if ((this.maxTotal == null) || (this.maxTotal < 0)) { - return DEFAULT_MAXTOTAL; - } else { - return this.maxTotal; - } - } - - public Boolean getEnable() { - return null == enable ? DEFAULT_ENABLE : this.enable; - } - - public String getUrl() { - return StringUtils.isEmpty(this.url) ? DEFAULT_URL : this.url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - if (StringUtils.isEmpty(this._password)) { - this._password = Crypto.plainText(this.password); - } - return this._password; - } - - public void setPassword(String password) { - this.password = password; - } - - public List getIncludes() { - return null == includes ? DEFAULT_INCLUDES : this.includes; - } - - public void setIncludes(List includes) { - this.includes = includes; - } - - public List getExcludes() { - return null == excludes ? DEFAULT_EXCLUDES : this.excludes; - } - - public void setExcludes(List excludes) { - this.excludes = excludes; - } - - public void setEnable(Boolean enable) { - this.enable = enable; - } - - public void setDriverClassName(String driverClassName) { - this.driverClassName = driverClassName; - } - - public void setDictionary(String dictionary) { - this.dictionary = dictionary; - } - - public void setMaxTotal(Integer maxTotal) { - this.maxTotal = maxTotal; - } - - public void setLogLevel(String logLevel) { - this.logLevel = logLevel; - } + // 无需保存 + private transient String _password; + + public ExternalDataSource() { + } + + public static final Boolean DEFAULT_ENABLE = false; + + public static final String DEFAULT_URL = "jdbc:mysql://127.0.0.1:3306/X?autoReconnect=true&allowPublicKeyRetrieval=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8"; + + public static final String DEFAULT_USERNAME = "root"; + + public static final String DEFAULT_PASSWORD = "password"; + + public static final String DEFAULT_DRIVERCLASSNAME = ""; + + public static final String DEFAULT_DICTIONARY = ""; + + public static final Integer DEFAULT_MAXTOTAL = 100; + + public static final Integer DEFAULT_MAXIDLE = 0; + + public static final Boolean DEFAULT_STATENABLE = true; + + public static final String DEFAULT_STATFILTER = "mergeStat"; + + public static final List DEFAULT_INCLUDES = new ArrayList<>(); + + public static final List DEFAULT_EXCLUDES = new ArrayList<>(); + + public static final Integer DEFAULT_SLOWSQLMILLIS = 2000; + + public static final String DEFAULT_LOGLEVEL = "ERROR"; + + public static final String DEFAULT_TRANSACTIONISOLATION = "read-committed"; + + public static final Boolean DEFAULT_TESTCONNECTIONONCHECKIN = false; + + public static final Boolean DEFAULT_TESTCONNECTIONONCHECKOUT = false; + + public static final Integer DEFAULT_MAXIDLETIME = 300; + + public static final Boolean DEFAULT_AUTOCOMMIT = false; + + public static final Boolean DEFAULT_TRACESQLENABLE = false; + + public static final String DEFAULT_SCHEMA = "X"; + + public static ExternalDataSource defaultInstance() { + + ExternalDataSource o = new ExternalDataSource(); + o.enable = DEFAULT_ENABLE; + o.url = DEFAULT_URL; + o.username = DEFAULT_USERNAME; + o.password = DEFAULT_PASSWORD; + o.driverClassName = DEFAULT_DRIVERCLASSNAME; + o.dictionary = DEFAULT_DICTIONARY; + o.maxTotal = DEFAULT_MAXTOTAL; + o.maxIdle = DEFAULT_MAXIDLE; + o.statEnable = DEFAULT_STATENABLE; + o.statFilter = DEFAULT_STATFILTER; + o.slowSqlMillis = DEFAULT_SLOWSQLMILLIS; + o.includes = DEFAULT_INCLUDES; + o.excludes = DEFAULT_EXCLUDES; + o.logLevel = DEFAULT_LOGLEVEL; + o.transactionIsolation = DEFAULT_TRANSACTIONISOLATION; + o.testConnectionOnCheckin = DEFAULT_TESTCONNECTIONONCHECKIN; + o.testConnectionOnCheckout = DEFAULT_TESTCONNECTIONONCHECKOUT; + o.maxIdleTime = DEFAULT_MAXIDLETIME; + o.autoCommit = DEFAULT_AUTOCOMMIT; + o.traceSqlEnable = DEFAULT_TRACESQLENABLE; + return o; + } + + @FieldDescribe("是否启用,如果启用多个数据库,那么必须是相同类型的,不能混用,且用户名密码必须一致.") + private Boolean enable; + @FieldDescribe("jdbc连接地址.") + private String url; + @FieldDescribe("数据库jdbc连接用户名.") + private String username; + @FieldDescribe("数据库jdbc连接密码.") + private String password; + @FieldDescribe("数据库驱动类名.") + private String driverClassName; + @FieldDescribe("方言类.") + private String dictionary; + @FieldDescribe("最大使用连接数.") + private Integer maxTotal; + @FieldDescribe("最大空闲连接数.") + private Integer maxIdle; + @FieldDescribe("启用统计,默认启用.") + private Boolean statEnable; + @FieldDescribe("统计方式配置,默认mergeStat.") + private String statFilter; + @FieldDescribe("执行缓慢sql毫秒数,默认2000毫秒,执行缓慢的sql将被单独记录.") + private Integer slowSqlMillis; + @FieldDescribe("设置此数据库存储的类,默认情况下存储所有类型,如果需要对每个类进行单独的控制以达到高性能,可以将不同的类存储到不同的节点上提高性能.可以使用通配符*.") + private List includes; + @FieldDescribe("在此节点上不存储的类,和includes一起设置实际存储的类,可以使用通配符*.") + private List excludes; + @FieldDescribe("默认日志级别,FATAL, ERROR, WARN, INFO, TRACE. 完整的配置为DefaultLevel=WARN, Tool=TRACE, Enhance=TRACE, METADATA=TRACE, Runtime=TRACE, Query=TRACE, DataCache=TRACE, JDBC=TRACE, SQL=TRACE.") + private String logLevel = DEFAULT_LOGLEVEL; + @FieldDescribe("事务隔离级别:default,none,read-uncommitted,read-committed,repeatable-read,serializable.默认使用default(数据库设置的事务级别).") + private String transactionIsolation; + @FieldDescribe("测试入池连接,默认false.") + private Boolean testConnectionOnCheckin; + @FieldDescribe("测试出池连接,默认false.") + private Boolean testConnectionOnCheckout; + @FieldDescribe("空闲阈值,默认300秒.") + private Integer maxIdleTime; + @FieldDescribe("自动提交,默认为false.") + private Boolean autoCommit = DEFAULT_AUTOCOMMIT; + @FieldDescribe("启用sql跟踪.") + private Boolean traceSqlEnable = DEFAULT_TRACESQLENABLE; + @FieldDescribe("模式.") + private String schema = DEFAULT_SCHEMA; + + public Boolean getTraceSqlEnable() { + return (null == this.traceSqlEnable) ? DEFAULT_TRACESQLENABLE : this.traceSqlEnable; + } + + public Boolean getAutoCommit() { + return (null == this.autoCommit) ? DEFAULT_AUTOCOMMIT : this.autoCommit; + } + + public Integer getMaxIdleTime() { + return maxIdleTime == null ? DEFAULT_MAXIDLETIME : this.maxIdleTime; + } + + public Boolean getTestConnectionOnCheckin() { + return this.testConnectionOnCheckin == null ? DEFAULT_TESTCONNECTIONONCHECKIN : this.testConnectionOnCheckin; + } + + public Boolean getTestConnectionOnCheckout() { + return this.testConnectionOnCheckout == null ? DEFAULT_TESTCONNECTIONONCHECKOUT : this.testConnectionOnCheckout; + } + + public String getTransactionIsolation() { + return StringUtils.isEmpty(this.transactionIsolation) ? DEFAULT_TRANSACTIONISOLATION + : this.transactionIsolation; + } + + public String getLogLevel() { + return StringUtils.isEmpty(this.logLevel) ? DEFAULT_LOGLEVEL : this.logLevel; + } + + public String getDriverClassName() throws Exception { + return StringUtils.isEmpty(this.driverClassName) ? SlicePropertiesBuilder.driverClassNameOfUrl(this.url) + : this.driverClassName; + } + + public String getDictionary() throws Exception { + return StringUtils.isEmpty(this.dictionary) ? SlicePropertiesBuilder.dictionaryOfUrl(this.url) + : this.dictionary; + } + + public Integer getSlowSqlMillis() { + return (null == this.slowSqlMillis || this.slowSqlMillis < 1) ? DEFAULT_SLOWSQLMILLIS : this.slowSqlMillis; + } + + public String getStatFilter() { + return StringUtils.isEmpty(this.statFilter) ? DEFAULT_STATFILTER : this.statFilter; + } + + public Boolean getStatEnable() { + return null == statEnable ? DEFAULT_STATENABLE : this.statEnable; + } + + public Integer getMaxIdle() { + if ((this.maxIdle == null) || (this.maxIdle < 1)) { + return DEFAULT_MAXIDLE; + } else { + return this.maxTotal; + } + } + + public Integer getMaxTotal() { + if ((this.maxTotal == null) || (this.maxTotal < 0)) { + return DEFAULT_MAXTOTAL; + } else { + return this.maxTotal; + } + } + + public Boolean getEnable() { + return null == enable ? DEFAULT_ENABLE : this.enable; + } + + public String getUrl() { + return StringUtils.isEmpty(this.url) ? DEFAULT_URL : this.url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + if (StringUtils.isEmpty(this._password)) { + this._password = Crypto.plainText(this.password); + } + return this._password; + } + + public void setPassword(String password) { + this.password = password; + } + + public List getIncludes() { + return null == includes ? DEFAULT_INCLUDES : this.includes; + } + + public void setIncludes(List includes) { + this.includes = includes; + } + + public List getExcludes() { + return null == excludes ? DEFAULT_EXCLUDES : this.excludes; + } + + public void setExcludes(List excludes) { + this.excludes = excludes; + } + + public void setEnable(Boolean enable) { + this.enable = enable; + } + + public void setDriverClassName(String driverClassName) { + this.driverClassName = driverClassName; + } + + public void setDictionary(String dictionary) { + this.dictionary = dictionary; + } + + public void setMaxTotal(Integer maxTotal) { + this.maxTotal = maxTotal; + } + + public void setLogLevel(String logLevel) { + this.logLevel = logLevel; + } + + public String getSchema() { + return StringUtils.isBlank(this.schema) ? DEFAULT_SCHEMA : this.schema; + } } diff --git a/o2server/x_base_core_project/src/main/java/com/x/base/core/project/config/ExternalDataSources.java b/o2server/x_base_core_project/src/main/java/com/x/base/core/project/config/ExternalDataSources.java index 9059313342c5fe9b46159be46013e3e6a2e25b75..70d0433d99550900a54be827cfd58f6a6c050470 100644 --- a/o2server/x_base_core_project/src/main/java/com/x/base/core/project/config/ExternalDataSources.java +++ b/o2server/x_base_core_project/src/main/java/com/x/base/core/project/config/ExternalDataSources.java @@ -99,14 +99,23 @@ public class ExternalDataSources extends CopyOnWriteArrayList readers = new ArrayList<>(); + Set readers = new TreeSet<>(); try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) { Business business = new Business(emc); String person = business.index().who(effectivePerson, wi.getPerson()); - readers = business.index().determineReaders(person, category, key); + wi.getDirectoryList().stream().forEach(o -> { + try { + readers.addAll(business.index().determineReaders(person, o.getCategory(), o.getKey())); + } catch (Exception e) { + LOGGER.error(e); + } + }); } + List categories = this.categories(wi.getDirectoryList()); + Optional searchQuery = searchQuery(wi.getQuery(), new HanLPAnalyzer()); Optional readersQuery = Indexs.readersQuery(readers); List filterQueries = Indexs.filterQueries(wi.getFilterList()); @@ -89,14 +96,13 @@ class ActionExport extends BaseAction { filterQueries.stream().forEach(o -> builder.add(o, BooleanClause.Occur.MUST)); Query query = builder.build(); LOGGER.debug("index export lucene query:{}.", query::toString); - Optional optional = Indexs.directory(category, key, true); - if (optional.isEmpty()) { - throw new ExceptionDirectoryNotExist(); - } - try (DirectoryReader reader = DirectoryReader.open(optional.get()); Workbook workbook = new XSSFWorkbook()) { - List> outFields = outFields(wi.getFixedFieldList(), + try (MultiReader multiReader = new MultiReader(indexReaders(wi.getDirectoryList())); + Workbook workbook = new XSSFWorkbook()) { + List> outFields = outFields( + this.getFixedFieldList(categories), + wi.getFixedFieldList(), wi.getDynamicFieldList()); - IndexSearcher searcher = new IndexSearcher(reader); + IndexSearcher searcher = new IndexSearcher(multiReader); TopFieldCollector topFieldCollector = TopFieldCollector.create(sort(wi.getSort()), Config.query().index().getSearchMaxHits(), Config.query().index().getSearchMaxHits()); searcher.search(query, topFieldCollector); @@ -138,11 +144,11 @@ class ActionExport extends BaseAction { return result; } - private List> outFields(List fixedFieldList, + private List> outFields(List woFields, List fixedFieldList, List dynamicFieldList) { List> list = new ArrayList<>(); if (ListTools.isEmpty(fixedFieldList) && ListTools.isEmpty(dynamicFieldList)) { - list.addAll(getFixedFieldList(Indexs.CATEGORY_PROCESSPLATFORM).stream() + list.addAll(woFields.stream() .map(o -> Triple.of(o.getField(), o.getName(), o.getFieldType())).collect(Collectors.toList())); } else { if (!ListTools.isEmpty(fixedFieldList)) { @@ -182,7 +188,7 @@ class ActionExport extends BaseAction { cell.setCellStyle(cellStyle); }); // auto row size - // row.setHeight((short) 0); + row.setHeight((short) 0); return sheet; } @@ -190,15 +196,17 @@ class ActionExport extends BaseAction { final Row row = param.third().createRow(param.third().getLastRowNum() + 1); Streams.mapWithIndex(param.first().stream(), Pair::of) .map(o -> Quintuple.of(o.first().first(), o.first().second(), o.first().third(), o.second(), - param.second().getField(o.first().first()))) + param.second().getFields(o.first().first()))) .filter(o -> !Objects.isNull(o.fifth())).forEach(o -> { Object value = Indexs.indexableFieldValue(o.fifth(), o.third()); Cell cell = row.createCell(o.fourth().intValue()); - cell.setCellValue(Objects.toString(value, "")); + if ((null != value) && (Date.class.isAssignableFrom(value.getClass()))) { + cell.setCellValue(DateTools.format((Date) value)); + } else { + cell.setCellValue(Objects.toString(value, "")); + } cell.setCellStyle(param.fourth()); }); - // auto row size - // row.setHeight((short) 0); }; @Schema(name = "com.x.custom.index.assemble.control.jaxrs.search.ActionExport$Wo") diff --git a/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/index/ActionListDirectory.java b/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/index/ActionListDirectory.java index 6879270d4dde40efc3fcf3f28f651f709c0bd99d..89635419b10d30c8c17dc7382b6f9a1248c49b30 100644 --- a/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/index/ActionListDirectory.java +++ b/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/index/ActionListDirectory.java @@ -11,7 +11,6 @@ import com.x.base.core.container.EntityManagerContainer; import com.x.base.core.container.factory.EntityManagerContainerFactory; import com.x.base.core.entity.JpaObject; import com.x.base.core.project.annotation.FieldDescribe; -import com.x.base.core.project.bean.NameValuePair; import com.x.base.core.project.cache.Cache.CacheKey; import com.x.base.core.project.cache.CacheManager; import com.x.base.core.project.gson.GsonPropertyObject; @@ -60,8 +59,8 @@ class ActionListDirectory extends BaseAction { private Wo processPlatform(Business business) throws Exception { EntityManagerContainer emc = business.entityManagerContainer(); List os = emc.fetchAll(Application.class, APPLICATIONATTRIBUTES); - List keys = os.stream().map(o -> new NameValuePair(o.getName(), o.getId())) - .sorted(Comparator.nullsLast(Comparator.comparing(NameValuePair::getName))).collect( + List keys = os.stream().map(o -> new WoKey(o.getName(), o.getId())) + .sorted(Comparator.nullsLast(Comparator.comparing(WoKey::getName))).collect( ArrayList::new, List::add, List::addAll); Wo wo = new Wo(); @@ -73,8 +72,8 @@ class ActionListDirectory extends BaseAction { private Wo cms(Business business) throws Exception { EntityManagerContainer emc = business.entityManagerContainer(); List os = emc.fetchAll(AppInfo.class, APPINFOATTRIBUTES); - List keys = os.stream().map(o -> new NameValuePair(o.getAppName(), o.getId())) - .sorted(Comparator.nullsLast(Comparator.comparing(NameValuePair::getName))).collect( + List keys = os.stream().map(o -> new WoKey(o.getAppName(), o.getId())) + .sorted(Comparator.nullsLast(Comparator.comparing(WoKey::getName))).collect( ArrayList::new, List::add, List::addAll); Wo wo = new Wo(); @@ -83,7 +82,7 @@ class ActionListDirectory extends BaseAction { return wo; } - @Schema(name = "com.x.custom.index.assemble.control.jaxrs.index.ActionPost$Wo") + @Schema(name = "com.x.query.assemble.surface.jaxrs.index.ActionListDirectory$Wo") public class Wo extends GsonPropertyObject { @FieldDescribe("分类") @@ -92,7 +91,7 @@ class ActionListDirectory extends BaseAction { @FieldDescribe("标识") @Schema(description = "标识") - private List keyList = new ArrayList<>(); + private List keyList = new ArrayList<>(); public String getCategory() { return category; @@ -102,14 +101,48 @@ class ActionListDirectory extends BaseAction { this.category = category; } - public List getKeyList() { + public List getKeyList() { return keyList; } - public void setKeyList(List keyList) { + public void setKeyList(List keyList) { this.keyList = keyList; } } + @Schema(name = "com.x.query.assemble.surface.jaxrs.index.ActionListDirectory$WoKey") + public class WoKey extends GsonPropertyObject { + + public WoKey(String name, String key) { + this.name = name; + this.key = key; + } + + @FieldDescribe("名称.") + @Schema(description = "名称.") + private String name; + + @FieldDescribe("标识.") + @Schema(description = "标识.") + private String key; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + } + } \ No newline at end of file diff --git a/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/index/ActionPost.java b/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/index/ActionPost.java index d9ea43b2a6e17dcca32d2f884cfba248aca917a2..b5c89260f480a6497a5976f79ff2267b20eafb51 100644 --- a/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/index/ActionPost.java +++ b/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/index/ActionPost.java @@ -1,6 +1,5 @@ package com.x.query.assemble.surface.jaxrs.index; -import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -8,11 +7,11 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; +import java.util.TreeSet; import java.util.stream.Collectors; import java.util.stream.Stream; -import org.apache.commons.collections4.list.TreeList; -import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.MultiReader; import org.apache.lucene.search.BooleanClause; @@ -68,7 +67,7 @@ class ActionPost extends BaseAction { Integer rows = Indexs.rows(wi.getSize()); Integer start = Indexs.start(wi.getPage(), rows); - List readers = new TreeList<>(); + Set readers = new TreeSet<>(); try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) { Business business = new Business(emc); String person = business.index().who(effectivePerson, wi.getPerson()); @@ -81,10 +80,12 @@ class ActionPost extends BaseAction { }); } - initWo(wo); + List categories = this.categories(wi.getDirectoryList()); + + initWo(wo, categories); Optional searchQuery = searchQuery(wi.getQuery(), new HanLPAnalyzer()); - Optional readersQuery = Indexs.readersQuery(ListTools.trim(readers, true, true)); + Optional readersQuery = Indexs.readersQuery(readers); List filterQueries = Indexs.filterQueries(wi.getFilterList()); BooleanQuery.Builder builder = new BooleanQuery.Builder(); Stream.of(searchQuery, readersQuery).filter(Optional::isPresent) @@ -92,16 +93,17 @@ class ActionPost extends BaseAction { filterQueries.stream().forEach(o -> builder.add(o, BooleanClause.Occur.MUST)); Query query = builder.build(); LOGGER.debug("index lucene query:{}.", query::toString); - IndexReader[] indexReaders = this.indexReaders(wi); + IndexReader[] indexReaders = this.indexReaders(wi.getDirectoryList()); if (indexReaders.length == 0) { return result; } try (MultiReader multiReader = new MultiReader(indexReaders)) { IndexSearcher searcher = new IndexSearcher(multiReader); - wo.setDynamicFieldList(getDynamicFieldList(multiReader)); + wo.setDynamicFieldList(getDynamicFieldList(categories, multiReader)); TopFieldCollector topFieldCollector = TopFieldCollector.create(sort(wi.getSort()), 1000, 1000); - List>> firstPassGroupingCollectorPairs = Indexs - .adjustFacetField(wi.getFilterList().stream().map(Filter::getField).collect(Collectors.toList())) + List>> firstPassGroupingCollectorPairs = this + .adjustFacetField(categories, + wi.getFilterList().stream().map(Filter::getField).collect(Collectors.toList())) .stream() .>>map(o -> { try { @@ -153,20 +155,8 @@ class ActionPost extends BaseAction { return result; } - private void initWo(Wo wo) { - wo.setFixedFieldList(this.getFixedFieldList(Indexs.CATEGORY_PROCESSPLATFORM)); - } - - private IndexReader[] indexReaders(Wi wi) { - return wi.getDirectoryList().stream().map(o -> Indexs.directory(o.getCategory(), o.getKey(), true)) - .filter(Optional::isPresent).map(Optional::get).map(o -> { - try { - return DirectoryReader.open(o); - } catch (IOException e) { - LOGGER.error(e); - } - return null; - }).filter(o -> !Objects.isNull(o)).toArray(s -> new IndexReader[s]); + private void initWo(Wo wo, List categories) { + wo.setFixedFieldList(this.getFixedFieldList(categories)); } private void writeDocument(IndexSearcher searcher, TopFieldCollector topFieldCollector, int start, int rows, Wo wo, @@ -180,8 +170,8 @@ class ActionPost extends BaseAction { try { org.apache.lucene.document.Document document = searcher.doc(o.doc); Map map = outFields.stream() - .map(f -> Quadruple.of(Indexs.judgeField(f), document.getField(f))) - .filter(param -> null != param.fourth()) + .map(f -> Quadruple.of(Indexs.judgeField(f), document.getFields(f))) + .filter(param -> param.fourth().length > 0) .map(p -> Pair.of(p.first(), Indexs.indexableFieldValue(p.fourth(), p.third()))) .collect(Collectors.toMap(Pair::first, Pair::second)); wo.getDocumentList().add(map); diff --git a/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/index/ActionPost3.java b/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/index/ActionPost3.java deleted file mode 100644 index 06e5637a30d68f0f308d590976abfa05d46d63e8..0000000000000000000000000000000000000000 --- a/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/index/ActionPost3.java +++ /dev/null @@ -1,203 +0,0 @@ -package com.x.query.assemble.surface.jaxrs.index; -//package com.x.query.assemble.surface.jaxrs.index; -// -//import java.util.ArrayList; -//import java.util.Arrays; -//import java.util.Collection; -//import java.util.List; -//import java.util.Map; -//import java.util.Objects; -//import java.util.Optional; -//import java.util.stream.Collectors; -//import java.util.stream.Stream; -// -//import org.apache.lucene.index.DirectoryReader; -//import org.apache.lucene.search.BooleanClause; -//import org.apache.lucene.search.BooleanQuery; -//import org.apache.lucene.search.IndexSearcher; -//import org.apache.lucene.search.MultiCollector; -//import org.apache.lucene.search.Query; -//import org.apache.lucene.search.ScoreDoc; -//import org.apache.lucene.search.TopDocs; -//import org.apache.lucene.search.TopFieldCollector; -//import org.apache.lucene.search.grouping.FirstPassGroupingCollector; -//import org.apache.lucene.search.grouping.SearchGroup; -//import org.apache.lucene.search.grouping.TermGroupSelector; -//import org.apache.lucene.search.grouping.TopGroupsCollector; -//import org.apache.lucene.store.Directory; -//import org.apache.lucene.util.BytesRef; -// -//import com.google.gson.JsonElement; -//import com.hankcs.lucene.HanLPAnalyzer; -//import com.x.base.core.container.EntityManagerContainer; -//import com.x.base.core.container.factory.EntityManagerContainerFactory; -//import com.x.base.core.project.bean.tuple.Pair; -//import com.x.base.core.project.bean.tuple.Quadruple; -//import com.x.base.core.project.config.Config; -//import com.x.base.core.project.http.ActionResult; -//import com.x.base.core.project.http.EffectivePerson; -//import com.x.base.core.project.logger.Logger; -//import com.x.base.core.project.logger.LoggerFactory; -//import com.x.base.core.project.tools.ListTools; -//import com.x.query.assemble.surface.Business; -//import com.x.query.core.express.assemble.surface.jaxrs.index.ActionPostWi; -//import com.x.query.core.express.assemble.surface.jaxrs.index.ActionPostWo; -//import com.x.query.core.express.index.Facets; -//import com.x.query.core.express.index.Filter; -//import com.x.query.core.express.index.Indexs; -//import com.x.query.core.express.index.WoField; -// -//import io.swagger.v3.oas.annotations.media.Schema; -// -//class ActionPost extends BaseAction { -// -// private static final Logger LOGGER = LoggerFactory.getLogger(ActionPost.class); -// -// ActionResult execute(EffectivePerson effectivePerson, JsonElement jsonElement) throws Exception { -// -// LOGGER.info("execute:{}.", effectivePerson::getDistinguishedName); -// -// ActionResult result = new ActionResult<>(); -// Wo wo = new Wo(); -// result.setData(wo); -// -// Wi wi = this.convertToWrapIn(jsonElement, Wi.class); -// -// String category = wi.getCategory(); -// String key = wi.getKey(); -// Integer rows = Indexs.rows(wi.getSize()); -// Integer start = Indexs.start(wi.getPage(), rows); -// -// List readers = new ArrayList<>(); -// try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) { -// Business business = new Business(emc); -// String person = business.index().who(effectivePerson, wi.getPerson()); -// readers = business.index().determineReaders(person, category, key); -// } -// -// initWo(wo, wi); -// -// Optional searchQuery = searchQuery(wi.getQuery(), new HanLPAnalyzer()); -// Optional readersQuery = Indexs.readersQuery(readers); -// List filterQueries = Indexs.filterQueries(wi.getFilterList()); -// BooleanQuery.Builder builder = new BooleanQuery.Builder(); -// Stream.of(searchQuery, readersQuery).filter(Optional::isPresent) -// .forEach(o -> builder.add(o.get(), BooleanClause.Occur.MUST)); -// filterQueries.stream().forEach(o -> builder.add(o, BooleanClause.Occur.MUST)); -// Query query = builder.build(); -// LOGGER.debug("index lucene query:{}.", query::toString); -// Optional optional = Indexs.directory(category, key, true); -// if (optional.isEmpty()) { -// throw new ExceptionDirectoryNotExist(); -// } -// try (DirectoryReader reader = DirectoryReader.open(optional.get())) { -// wo.setDynamicFieldList(getDynamicFieldList(reader)); -// IndexSearcher searcher = new IndexSearcher(reader); -// TopFieldCollector topFieldCollector = TopFieldCollector.create(sort(wi.getSort()), 1000, 1000); -// List>> firstPassGroupingCollectorPairs = Indexs -// .adjustFacetField(wi.getFilterList().stream().map(Filter::getField).collect(Collectors.toList())) -// .stream() -// .>>map(o -> { -// try { -// return Pair.of(o, -// new FirstPassGroupingCollector<>(new TermGroupSelector(o), -// org.apache.lucene.search.Sort.INDEXORDER, -// Config.query().index().getFacetMaxGroups())); -// } catch (Exception ex) { -// LOGGER.error(ex); -// } -// return null; -// }).filter(o -> !Objects.isNull(o)).collect(Collectors.toList()); -// searcher.search(query, MultiCollector.wrap(topFieldCollector, MultiCollector -// .wrap(firstPassGroupingCollectorPairs.stream().map(Pair::second).collect(Collectors.toList())))); -// writeDocument(searcher, topFieldCollector, start, rows, wo, wi.getFixedFieldList(), -// wi.getDynamicFieldList()); -// List>> topGroupsCollectorPairs = firstPassGroupingCollectorPairs -// .stream().>>>>map(param -> { -// Collection> topGroups = null; -// try { -// topGroups = param.second().getTopGroups(0); -// } catch (Exception e) { -// LOGGER.error(e); -// } -// if (Objects.isNull(topGroups)) { -// return Pair.of(param.first(), Optional.empty()); -// } else { -// return Pair.of(param.first(), Optional.of(topGroups)); -// } -// }).filter(o -> o.second().isPresent()) -// .>>map(param -> { -// try { -// return Pair.of(param.first(), -// new TopGroupsCollector<>(new TermGroupSelector(param.first()), param.second().get(), -// org.apache.lucene.search.Sort.INDEXORDER, -// org.apache.lucene.search.Sort.INDEXORDER, -// Config.query().index().getSearchMaxHits(), false)); -// } catch (Exception e) { -// LOGGER.error(e); -// } -// return null; -// }).filter(o -> !Objects.isNull(o)).collect(Collectors.toList()); -// if (!topGroupsCollectorPairs.isEmpty()) { -// searcher.search(query, MultiCollector -// .wrap(topGroupsCollectorPairs.stream().map(Pair::second).collect(Collectors.toList()))); -// wo.setFacetList(Facets.topGroupsCollector(topGroupsCollectorPairs)); -// } -// } -// return result; -// } -// -// private void initWo(Wo wo, Wi wi) { -// wo.setFixedFieldList(this.getFixedFieldList(Indexs.CATEGORY_PROCESSPLATFORM)); -// } -// -// private void writeDocument(IndexSearcher searcher, TopFieldCollector topFieldCollector, int start, int rows, Wo wo, -// List fixedFieldList, List dynamicFieldList) { -// List outFields = outFields(wo, fixedFieldList, dynamicFieldList); -// TopDocs topDocs = topFieldCollector.topDocs(start, rows); -// wo.setCount(topDocs.totalHits.value); -// ScoreDoc[] scoreDocs = topDocs.scoreDocs; -// if (null != scoreDocs) { -// Arrays.stream(scoreDocs).forEach(o -> { -// try { -// org.apache.lucene.document.Document document = searcher.doc(o.doc); -// Map map = outFields.stream() -// .map(f -> Quadruple.of(Indexs.judgeField(f), document.getField(f))) -// .filter(param -> null != param.fourth()) -// .map(p -> Pair.of(p.first(), Indexs.indexableFieldValue(p.fourth(), p.third()))) -// .collect(Collectors.toMap(Pair::first, Pair::second)); -// wo.getDocumentList().add(map); -// } catch (Exception e) { -// LOGGER.error(e); -// } -// }); -// } -// } -// -// private List outFields(Wo wo, List fixedFieldList, List dynamicFieldList) { -// List list = new ArrayList<>(); -// list.add(Indexs.FIELD_ID); -// if (ListTools.isEmpty(fixedFieldList) && ListTools.isEmpty(dynamicFieldList)) { -// list.addAll(wo.getFixedFieldList().stream().map(WoField::getField).collect(Collectors.toList())); -// } else { -// list.addAll(fixedFieldList); -// list.addAll(dynamicFieldList); -// } -// return list; -// } -// -// @Schema(name = "com.x.custom.index.assemble.control.jaxrs.index.ActionPost$Wo") -// public class Wo extends ActionPostWo { -// -// private static final long serialVersionUID = 3751674531291729956L; -// -// } -// -// @Schema(name = "com.x.custom.index.assemble.control.jaxrs.index.ActionPost$Wi") -// public class Wi extends ActionPostWi { -// -// private static final long serialVersionUID = -4646809016933808952L; -// -// } -// -//} \ No newline at end of file diff --git a/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/index/BaseAction.java b/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/index/BaseAction.java index 1798400fe5ad93e9fa4725a907b4ed0dedcdf191..4b848a49ed545620a98cac6aa9c22fd6672ffeec 100644 --- a/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/index/BaseAction.java +++ b/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/index/BaseAction.java @@ -1,17 +1,21 @@ package com.x.query.assemble.surface.jaxrs.index; import java.io.IOException; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; +import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import org.apache.commons.collections4.ListUtils; import org.apache.commons.lang3.StringUtils; import org.apache.lucene.analysis.Analyzer; +import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.PointValues; import org.apache.lucene.queryparser.classic.ParseException; @@ -27,6 +31,7 @@ import org.apache.lucene.search.grouping.TopGroupsCollector; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.NumericUtils; +import com.google.common.collect.ImmutableMap; import com.x.base.core.project.bean.ValueCountPair; import com.x.base.core.project.bean.tuple.Pair; import com.x.base.core.project.cache.Cache.CacheCategory; @@ -35,7 +40,12 @@ import com.x.base.core.project.jaxrs.StandardJaxrsAction; import com.x.base.core.project.logger.Logger; import com.x.base.core.project.logger.LoggerFactory; import com.x.base.core.project.tools.DateTools; +import com.x.base.core.project.tools.ListTools; import com.x.cms.core.entity.AppInfo; +import com.x.cms.core.entity.Document; +import com.x.processplatform.core.entity.content.TaskCompleted; +import com.x.processplatform.core.entity.content.Work; +import com.x.processplatform.core.entity.content.WorkCompleted; import com.x.processplatform.core.entity.element.Application; import com.x.query.core.express.index.Indexs; import com.x.query.core.express.index.Sort; @@ -46,6 +56,36 @@ abstract class BaseAction extends StandardJaxrsAction { private static final Logger LOGGER = LoggerFactory.getLogger(BaseAction.class); + private static final Map PROCESSPLATFORM_FIELDNAME = ImmutableMap.builder() + .put(Indexs.PREFIX_FIELD_PROCESSPLATFORM_BOOLEAN + TaskCompleted.completed_FIELDNAME, "已完成") + .put(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING + WorkCompleted.creatorUnitLevelName_FIELDNAME, "创建者部门层级名") + .put(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING + WorkCompleted.application_FIELDNAME, "应用标识") + .put(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING + WorkCompleted.applicationName_FIELDNAME, "应用名称") + .put(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING + WorkCompleted.applicationAlias_FIELDNAME, "应用别名") + .put(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING + WorkCompleted.process_FIELDNAME, "流程标识") + .put(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING + WorkCompleted.processName_FIELDNAME, "流程名称") + .put(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING + WorkCompleted.processAlias_FIELDNAME, "流程别名") + .put(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING + WorkCompleted.job_FIELDNAME, "任务") + .put(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING + WorkCompleted.serial_FIELDNAME, "编号") + .put(Indexs.PREFIX_FIELD_PROCESSPLATFORM_BOOLEAN + WorkCompleted.expired_FIELDNAME, "超时") + .put(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING + Work.activityName_FIELDNAME, "活动环节") + .put(Indexs.PREFIX_FIELD_PROCESSPLATFORM_DATE + WorkCompleted.expireTime_FIELDNAME, "截至时间") + .put(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRINGS + Indexs.FIELD_ROCESSPLATFORM_TASKPERSONNAMES, "当前处理人") + .put(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRINGS + Indexs.FIELD_ROCESSPLATFORM_PRETASKPERSONNAMES, "前序处理人") + .build(); + + private static final Map CMS_FIELDNAME = ImmutableMap.builder() + .put(Indexs.PREFIX_FIELD_CMS_STRING + Document.appId_FIELDNAME, "栏目标识") + .put(Indexs.PREFIX_FIELD_CMS_STRING + Document.appName_FIELDNAME, "栏目名称") + .put(Indexs.PREFIX_FIELD_CMS_STRING + Document.appAlias_FIELDNAME, "栏目别名") + .put(Indexs.PREFIX_FIELD_CMS_STRING + Document.categoryId_FIELDNAME, "分类标识") + .put(Indexs.PREFIX_FIELD_CMS_STRING + Document.categoryName_FIELDNAME, "分类名称") + .put(Indexs.PREFIX_FIELD_CMS_STRING + Document.categoryAlias_FIELDNAME, "分类别名") + .put(Indexs.PREFIX_FIELD_CMS_STRING + Document.description_FIELDNAME, "说明") + .put(Indexs.PREFIX_FIELD_CMS_DATE + Document.publishTime_FIELDNAME, "发布时间") + .put(Indexs.PREFIX_FIELD_CMS_DATE + Document.modifyTime_FIELDNAME, "修改时间") + .build(); + protected static final WoField IDWOFIELD = new WoField(Indexs.FIELD_ID, "标识", Indexs.FIELD_TYPE_STRING); protected static final CacheCategory cacheCategory = new CacheCategory(Application.class, AppInfo.class); @@ -57,13 +97,7 @@ abstract class BaseAction extends StandardJaxrsAction { new WoField(Indexs.FIELD_UPDATETIME, "更新时间", Indexs.FIELD_TYPE_DATE), new WoField(Indexs.FIELD_SERIAL, "文号", Indexs.FIELD_TYPE_STRING), new WoField(Indexs.FIELD_PROCESSNAME, "流程", Indexs.FIELD_TYPE_STRING))); -// protected static final List FIXEDFIELD_PROCESS = ListUtils -// .unmodifiableList(Arrays.asList(new WoField(Indexs.FIELD_TITLE, "标题", Indexs.FIELD_TYPE_STRING), -// new WoField(Indexs.FIELD_CREATORPERSON, "创建者", Indexs.FIELD_TYPE_STRING), -// new WoField(Indexs.FIELD_CREATORUNIT, "部门", Indexs.FIELD_TYPE_STRING), -// new WoField(Indexs.FIELD_CREATETIME, "创建时间", Indexs.FIELD_TYPE_DATE), -// new WoField(Indexs.FIELD_UPDATETIME, "更新时间", Indexs.FIELD_TYPE_DATE), -// new WoField(Indexs.FIELD_SERIAL, "文号", Indexs.FIELD_TYPE_STRING))); + protected static final List FIXEDFIELD_APPINFO = ListUtils .unmodifiableList(Arrays.asList(new WoField(Indexs.FIELD_TITLE, "标题", Indexs.FIELD_TYPE_STRING), new WoField(Indexs.FIELD_CREATORPERSON, "创建者", Indexs.FIELD_TYPE_STRING), @@ -72,17 +106,10 @@ abstract class BaseAction extends StandardJaxrsAction { new WoField(Indexs.FIELD_UPDATETIME, "更新时间", Indexs.FIELD_TYPE_DATE), new WoField(Indexs.FIELD_CATEGORYNAME, "分类", Indexs.FIELD_TYPE_STRING), new WoField(Indexs.FIELD_DESCRIPTION, "说明", Indexs.FIELD_TYPE_STRING))); -// protected static final List FIXEDFIELD_CATEGORYINFO = ListUtils -// .unmodifiableList(Arrays.asList(new WoField(Indexs.FIELD_TITLE, "标题", Indexs.FIELD_TYPE_STRING), -// new WoField(Indexs.FIELD_CREATORPERSON, "创建者", Indexs.FIELD_TYPE_STRING), -// new WoField(Indexs.FIELD_CREATORUNIT, "部门", Indexs.FIELD_TYPE_STRING), -// new WoField(Indexs.FIELD_CREATETIME, "创建时间", Indexs.FIELD_TYPE_DATE), -// new WoField(Indexs.FIELD_UPDATETIME, "更新时间", Indexs.FIELD_TYPE_DATE), -// new WoField(Indexs.FIELD_DESCRIPTION, "说明", Indexs.FIELD_TYPE_STRING))); protected static final List FACET_FIELDS = ListUtils .unmodifiableList(Arrays.asList(Indexs.FIELD_CREATETIMEMONTH, Indexs.FIELD_UPDATETIMEMONTH, - Indexs.FIELD_CREATORUNIT, Indexs.FIELD_CREATORPERSON)); + Indexs.FIELD_CREATORUNIT, Indexs.FIELD_COMPLETED)); protected Optional searchQuery(String query, Analyzer analyzer) throws ParseException { query = Indexs.alignQuery(query); @@ -146,89 +173,277 @@ abstract class BaseAction extends StandardJaxrsAction { }).collect(Collectors.toList()); } - protected List getFixedFieldList(String category) { - if (StringUtils.equals(Indexs.CATEGORY_PROCESSPLATFORM, category)) { - return FIXEDFIELD_APPLICATION; - } else { - return FIXEDFIELD_APPINFO; + protected IndexReader[] indexReaders(List dirs) { + return dirs.stream().map(o -> Indexs.directory(o.getCategory(), o.getKey(), true)) + .filter(Optional::isPresent).map(Optional::get).map(o -> { + try { + return DirectoryReader.open(o); + } catch (IOException e) { + LOGGER.error(e); + } + return null; + }).filter(o -> !Objects.isNull(o)).toArray(s -> new IndexReader[s]); + } + + protected List getFixedFieldList(List list) { + List woFields = new ArrayList<>(); + if (list.contains(Indexs.CATEGORY_PROCESSPLATFORM)) { + woFields.addAll(FIXEDFIELD_APPLICATION); + } else if (list.contains(Indexs.CATEGORY_CMS)) { + woFields.addAll(FIXEDFIELD_APPINFO); } + return ListTools.trim(woFields, true, true); } - protected List getDynamicFieldList(IndexReader reader) { + protected List getDynamicFieldList(List categories, IndexReader reader) { + String[] names = listFieldNamesWithCategory(categories); List list = org.apache.lucene.luke.models.util.IndexUtils.getFieldNames(reader).stream() - .filter(o -> StringUtils.startsWithAny(o, Indexs.PREFIX_FIELD_DATA_STRING, - Indexs.PREFIX_FIELD_DATA_STRINGS, Indexs.PREFIX_FIELD_DATA_BOOLEAN, - Indexs.PREFIX_FIELD_DATA_BOOLEANS, Indexs.PREFIX_FIELD_DATA_NUMBER, - Indexs.PREFIX_FIELD_DATA_NUMBERS, Indexs.PREFIX_FIELD_DATA_DATE, - Indexs.PREFIX_FIELD_DATA_DATES)) + .filter(o -> StringUtils.startsWithAny(o, names)) .distinct().map(o -> org.apache.lucene.luke.models.util.IndexUtils.getFieldInfo(reader, o)).map(o -> { // LegacyNumericUtils. WoField woField = new WoField(); woField.setField(o.getName()); - if (StringUtils.startsWith(o.getName(), Indexs.PREFIX_FIELD_DATA_STRING)) { - woField.setName(StringUtils.substringAfter(o.getName(), Indexs.PREFIX_FIELD_DATA_STRING)); - woField.setFieldType(Indexs.FIELD_TYPE_STRING); - } else if (StringUtils.startsWith(o.getName(), Indexs.PREFIX_FIELD_DATA_STRINGS)) { - woField.setName(StringUtils.substringAfter(o.getName(), Indexs.PREFIX_FIELD_DATA_STRINGS)); - woField.setFieldType(Indexs.FIELD_TYPE_STRINGS); - } else if (StringUtils.startsWith(o.getName(), Indexs.PREFIX_FIELD_DATA_BOOLEAN)) { - woField.setName(StringUtils.substringAfter(o.getName(), Indexs.PREFIX_FIELD_DATA_BOOLEAN)); - woField.setFieldType(Indexs.FIELD_TYPE_BOOLEAN); - } else if (StringUtils.startsWith(o.getName(), Indexs.PREFIX_FIELD_DATA_BOOLEANS)) { - woField.setName( - StringUtils.substringAfter(o.getName(), Indexs.PREFIX_FIELD_DATA_BOOLEANS)); - woField.setFieldType(Indexs.FIELD_TYPE_BOOLEANS); - } else if (StringUtils.startsWith(o.getName(), Indexs.PREFIX_FIELD_DATA_NUMBER)) { - woField.setName(StringUtils.substringAfter(o.getName(), Indexs.PREFIX_FIELD_DATA_NUMBER)); - woField.setFieldType(Indexs.FIELD_TYPE_NUMBER); - } else if (StringUtils.startsWith(o.getName(), Indexs.PREFIX_FIELD_DATA_NUMBERS)) { - woField.setName(StringUtils.substringAfter(o.getName(), Indexs.PREFIX_FIELD_DATA_NUMBERS)); - woField.setFieldType(Indexs.FIELD_TYPE_NUMBERS); - } else if (StringUtils.startsWith(o.getName(), Indexs.PREFIX_FIELD_DATA_DATE)) { - woField.setName(StringUtils.substringAfter(o.getName(), Indexs.PREFIX_FIELD_DATA_DATE)); - woField.setFieldType(Indexs.FIELD_TYPE_DATE); - } else if (StringUtils.startsWith(o.getName(), Indexs.PREFIX_FIELD_DATA_DATES)) { - woField.setName(StringUtils.substringAfter(o.getName(), Indexs.PREFIX_FIELD_DATA_DATES)); - woField.setFieldType(Indexs.FIELD_TYPE_DATES); - } - + setDynamicFieldType(woField); return woField; }).collect(Collectors.toList()); + List os = new ArrayList<>(); list.stream().filter(o -> StringUtils.equalsAny(o.getFieldType(), Indexs.FIELD_TYPE_NUMBER, - Indexs.FIELD_TYPE_NUMBER)).forEach(o -> { - try { - Long maxLong = null; - Long minLong = null; - byte[] max = PointValues.getMaxPackedValue(reader, o.getField()); - if (null != max) { - maxLong = org.apache.lucene.util.NumericUtils.sortableBytesToLong(max, 0); - } - byte[] min = PointValues.getMinPackedValue(reader, o.getField()); - if (null != min) { - minLong = org.apache.lucene.util.NumericUtils.sortableBytesToLong(min, 0); - } - if ((null != maxLong) || (null != minLong)) { - if (StringUtils.equalsIgnoreCase(o.getFieldType(), Indexs.FIELD_TYPE_NUMBER)) { - if (null != maxLong) { - o.setMax(NumericUtils.sortableLongToDouble(maxLong)); - } - if (null != minLong) { - o.setMin(NumericUtils.sortableLongToDouble(minLong)); - } - } - if (StringUtils.equalsIgnoreCase(o.getFieldType(), Indexs.PREFIX_FIELD_DATA_DATE)) { - if (null != maxLong) { - o.setMax(DateTools.format(new Date(maxLong))); - } - if (null != minLong) { - o.setMin(DateTools.format(new Date(minLong))); - } + Indexs.FIELD_TYPE_DATE)).forEach(o -> setMinMax(reader, o)); + list.stream().map(o -> { + Integer order = null; + if (StringUtils.startsWith(o.getField(), Indexs.PREFIX_FIELD_PROCESSPLATFORM)) { + order = 0; + } else { + order = StringUtils.startsWith(o.getField(), Indexs.PREFIX_FIELD_CMS) ? 1 : 2; + } + return Pair.of(order, o); + }).collect(Collectors.groupingBy(Pair::first)).entrySet().stream() + .sorted(Comparator.comparing(Map.Entry::getKey)) + .forEach(o -> o.getValue().stream().map(Pair::second).map(p -> Pair.of(p.getName().charAt(0), p)) + .map(p -> { + if (Character.UnicodeBlock + .of(p.first()) == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS) { + return Pair.of(0, p.second()); + } else { + return Pair.of(1, p.second()); } - } - } catch (IOException e) { - LOGGER.error(e); - } - }); + }).collect(Collectors.groupingBy(Pair::first)).entrySet().stream() + .sorted(Comparator.comparing(Map.Entry::getKey)) + .forEach(p -> p.getValue().stream().map(Pair::second) + .sorted(Comparator.nullsLast(Comparator.comparing(WoField::getName))) + .forEach(os::add))); + return os; + } + + private void setDynamicFieldType(WoField woField) { + if (StringUtils.startsWith(woField.getField(), Indexs.PREFIX_FIELD_DATA)) { + setDynamicFieldTypeData(woField); + } else if (StringUtils.startsWith(woField.getField(), Indexs.PREFIX_FIELD_PROCESSPLATFORM)) { + setDynamicFieldTypeProcessPlatform(woField); + } else if (StringUtils.startsWith(woField.getField(), Indexs.PREFIX_FIELD_CMS)) { + setDynamicFieldTypeCms(woField); + } + } + + private void setMinMax(IndexReader reader, WoField o) { + try { + Long maxLong = null; + Long minLong = null; + byte[] max = PointValues.getMaxPackedValue(reader, o.getField()); + if (null != max) { + maxLong = org.apache.lucene.util.NumericUtils.sortableBytesToLong(max, 0); + } + byte[] min = PointValues.getMinPackedValue(reader, o.getField()); + if (null != min) { + minLong = org.apache.lucene.util.NumericUtils.sortableBytesToLong(min, 0); + } + if ((null != maxLong) || (null != minLong)) { + if (StringUtils.equalsIgnoreCase(o.getFieldType(), Indexs.FIELD_TYPE_NUMBER)) { + setMinMaxNumber(o, maxLong, minLong); + } + if (StringUtils.equalsIgnoreCase(o.getFieldType(), Indexs.FIELD_TYPE_DATE)) { + setMinMaxDate(o, maxLong, minLong); + } + } + } catch (IOException e) { + LOGGER.error(e); + } + } + + private void setMinMaxDate(WoField o, Long maxLong, Long minLong) { + if (null != maxLong) { + o.setMax(DateTools.format(new Date(maxLong))); + } + if (null != minLong) { + o.setMin(DateTools.format(new Date(minLong))); + } + } + + private void setMinMaxNumber(WoField o, Long maxLong, Long minLong) { + if (null != maxLong) { + o.setMax(NumericUtils.sortableLongToDouble(maxLong)); + } + if (null != minLong) { + o.setMin(NumericUtils.sortableLongToDouble(minLong)); + } + } + + private void setDynamicFieldTypeData(WoField woField) { + if (StringUtils.startsWith(woField.getField(), Indexs.PREFIX_FIELD_DATA_STRING)) { + woField.setName(StringUtils.substringAfter(woField.getField(), Indexs.PREFIX_FIELD_DATA_STRING)); + woField.setFieldType(Indexs.FIELD_TYPE_STRING); + } else if (StringUtils.startsWith(woField.getField(), Indexs.PREFIX_FIELD_DATA_STRINGS)) { + woField.setName(StringUtils.substringAfter(woField.getField(), Indexs.PREFIX_FIELD_DATA_STRINGS)); + woField.setFieldType(Indexs.FIELD_TYPE_STRINGS); + } else if (StringUtils.startsWith(woField.getField(), Indexs.PREFIX_FIELD_DATA_BOOLEAN)) { + woField.setName(StringUtils.substringAfter(woField.getField(), Indexs.PREFIX_FIELD_DATA_BOOLEAN)); + woField.setFieldType(Indexs.FIELD_TYPE_BOOLEAN); + } else if (StringUtils.startsWith(woField.getField(), Indexs.PREFIX_FIELD_DATA_BOOLEANS)) { + woField.setName( + StringUtils.substringAfter(woField.getField(), Indexs.PREFIX_FIELD_DATA_BOOLEANS)); + woField.setFieldType(Indexs.FIELD_TYPE_BOOLEANS); + } else if (StringUtils.startsWith(woField.getField(), Indexs.PREFIX_FIELD_DATA_NUMBER)) { + woField.setName(StringUtils.substringAfter(woField.getField(), Indexs.PREFIX_FIELD_DATA_NUMBER)); + woField.setFieldType(Indexs.FIELD_TYPE_NUMBER); + } else if (StringUtils.startsWith(woField.getField(), Indexs.PREFIX_FIELD_DATA_NUMBERS)) { + woField.setName(StringUtils.substringAfter(woField.getField(), Indexs.PREFIX_FIELD_DATA_NUMBERS)); + woField.setFieldType(Indexs.FIELD_TYPE_NUMBERS); + } else if (StringUtils.startsWith(woField.getField(), Indexs.PREFIX_FIELD_DATA_DATE)) { + woField.setName(StringUtils.substringAfter(woField.getField(), Indexs.PREFIX_FIELD_DATA_DATE)); + woField.setFieldType(Indexs.FIELD_TYPE_DATE); + } else if (StringUtils.startsWith(woField.getField(), Indexs.PREFIX_FIELD_DATA_DATES)) { + woField.setName(StringUtils.substringAfter(woField.getField(), Indexs.PREFIX_FIELD_DATA_DATES)); + woField.setFieldType(Indexs.FIELD_TYPE_DATES); + } + } + + private void setDynamicFieldTypeProcessPlatform(WoField woField) { + if (StringUtils.startsWith(woField.getField(), Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING)) { + woField.setName(PROCESSPLATFORM_FIELDNAME.getOrDefault(woField.getField(), + StringUtils.substringAfter(woField.getField(), Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING))); + woField.setFieldType(Indexs.FIELD_TYPE_STRING); + } else if (StringUtils.startsWith(woField.getField(), Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRINGS)) { + woField.setName( + PROCESSPLATFORM_FIELDNAME.getOrDefault(woField.getField(), StringUtils + .substringAfter(woField.getField(), Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRINGS))); + woField.setFieldType(Indexs.FIELD_TYPE_STRINGS); + } else if (StringUtils.startsWith(woField.getField(), Indexs.PREFIX_FIELD_PROCESSPLATFORM_BOOLEAN)) { + woField.setName(PROCESSPLATFORM_FIELDNAME.getOrDefault(woField.getField(), + StringUtils.substringAfter(woField.getField(), Indexs.PREFIX_FIELD_PROCESSPLATFORM_BOOLEAN))); + woField.setFieldType(Indexs.FIELD_TYPE_BOOLEAN); + } else if (StringUtils.startsWith(woField.getField(), Indexs.PREFIX_FIELD_PROCESSPLATFORM_BOOLEANS)) { + woField.setName(PROCESSPLATFORM_FIELDNAME.getOrDefault(woField.getField(), + StringUtils.substringAfter(woField.getField(), Indexs.PREFIX_FIELD_PROCESSPLATFORM_BOOLEANS))); + woField.setFieldType(Indexs.FIELD_TYPE_BOOLEANS); + } else if (StringUtils.startsWith(woField.getField(), Indexs.PREFIX_FIELD_PROCESSPLATFORM_NUMBER)) { + woField.setName(PROCESSPLATFORM_FIELDNAME.getOrDefault(woField.getField(), + StringUtils.substringAfter(woField.getField(), Indexs.PREFIX_FIELD_PROCESSPLATFORM_NUMBER))); + woField.setFieldType(Indexs.FIELD_TYPE_NUMBER); + } else if (StringUtils.startsWith(woField.getField(), Indexs.PREFIX_FIELD_PROCESSPLATFORM_NUMBERS)) { + woField.setName(PROCESSPLATFORM_FIELDNAME.getOrDefault(woField.getField(), + StringUtils.substringAfter(woField.getField(), Indexs.PREFIX_FIELD_PROCESSPLATFORM_NUMBERS))); + woField.setFieldType(Indexs.FIELD_TYPE_NUMBERS); + } else if (StringUtils.startsWith(woField.getField(), Indexs.PREFIX_FIELD_PROCESSPLATFORM_DATE)) { + woField.setName(PROCESSPLATFORM_FIELDNAME.getOrDefault(woField.getField(), + StringUtils.substringAfter(woField.getField(), Indexs.PREFIX_FIELD_PROCESSPLATFORM_DATE))); + woField.setFieldType(Indexs.FIELD_TYPE_DATE); + } else if (StringUtils.startsWith(woField.getField(), Indexs.PREFIX_FIELD_PROCESSPLATFORM_DATES)) { + woField.setName(PROCESSPLATFORM_FIELDNAME.getOrDefault(woField.getField(), + StringUtils.substringAfter(woField.getField(), Indexs.PREFIX_FIELD_PROCESSPLATFORM_DATES))); + woField.setFieldType(Indexs.FIELD_TYPE_DATES); + } + } + + private void setDynamicFieldTypeCms(WoField woField) { + if (StringUtils.startsWith(woField.getField(), Indexs.PREFIX_FIELD_CMS_STRING)) { + woField.setName(CMS_FIELDNAME.getOrDefault(woField.getField(), + StringUtils.substringAfter(woField.getField(), Indexs.PREFIX_FIELD_CMS_STRING))); + woField.setFieldType(Indexs.FIELD_TYPE_STRING); + } else if (StringUtils.startsWith(woField.getField(), Indexs.PREFIX_FIELD_CMS_STRINGS)) { + woField.setName(CMS_FIELDNAME.getOrDefault(woField.getField(), + StringUtils.substringAfter(woField.getField(), Indexs.PREFIX_FIELD_CMS_STRINGS))); + woField.setFieldType(Indexs.FIELD_TYPE_STRINGS); + } else if (StringUtils.startsWith(woField.getField(), Indexs.PREFIX_FIELD_CMS_BOOLEAN)) { + woField.setName(CMS_FIELDNAME.getOrDefault(woField.getField(), + StringUtils.substringAfter(woField.getField(), Indexs.PREFIX_FIELD_CMS_BOOLEAN))); + woField.setFieldType(Indexs.FIELD_TYPE_BOOLEAN); + } else if (StringUtils.startsWith(woField.getField(), Indexs.PREFIX_FIELD_CMS_BOOLEANS)) { + woField.setName(CMS_FIELDNAME.getOrDefault(woField.getField(), + StringUtils.substringAfter(woField.getField(), Indexs.PREFIX_FIELD_CMS_BOOLEANS))); + woField.setFieldType(Indexs.FIELD_TYPE_BOOLEANS); + } else if (StringUtils.startsWith(woField.getField(), Indexs.PREFIX_FIELD_CMS_NUMBER)) { + woField.setName(CMS_FIELDNAME.getOrDefault(woField.getField(), + StringUtils.substringAfter(woField.getField(), Indexs.PREFIX_FIELD_CMS_NUMBER))); + woField.setFieldType(Indexs.FIELD_TYPE_NUMBER); + } else if (StringUtils.startsWith(woField.getField(), Indexs.PREFIX_FIELD_CMS_NUMBERS)) { + woField.setName(CMS_FIELDNAME.getOrDefault(woField.getField(), + StringUtils.substringAfter(woField.getField(), Indexs.PREFIX_FIELD_CMS_NUMBERS))); + woField.setFieldType(Indexs.FIELD_TYPE_NUMBERS); + } else if (StringUtils.startsWith(woField.getField(), Indexs.PREFIX_FIELD_CMS_DATE)) { + woField.setName(CMS_FIELDNAME.getOrDefault(woField.getField(), + StringUtils.substringAfter(woField.getField(), Indexs.PREFIX_FIELD_CMS_DATE))); + woField.setFieldType(Indexs.FIELD_TYPE_DATE); + } else if (StringUtils.startsWith(woField.getField(), Indexs.PREFIX_FIELD_CMS_DATES)) { + woField.setName(CMS_FIELDNAME.getOrDefault(woField.getField(), + StringUtils.substringAfter(woField.getField(), Indexs.PREFIX_FIELD_CMS_DATES))); + woField.setFieldType(Indexs.FIELD_TYPE_DATES); + } + } + + private String[] listFieldNamesWithCategory(List categories) { + List names = new ArrayList<>(); + if (categories.contains(Indexs.CATEGORY_PROCESSPLATFORM)) { + names.addAll(Arrays.asList(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING, + Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRINGS, Indexs.PREFIX_FIELD_PROCESSPLATFORM_BOOLEAN, + Indexs.PREFIX_FIELD_PROCESSPLATFORM_BOOLEANS, Indexs.PREFIX_FIELD_PROCESSPLATFORM_NUMBER, + Indexs.PREFIX_FIELD_PROCESSPLATFORM_NUMBERS, Indexs.PREFIX_FIELD_PROCESSPLATFORM_DATE, + Indexs.PREFIX_FIELD_PROCESSPLATFORM_DATES)); + } + if (categories.contains(Indexs.CATEGORY_CMS)) { + names.addAll(Arrays.asList(Indexs.PREFIX_FIELD_CMS_STRING, + Indexs.PREFIX_FIELD_CMS_STRINGS, Indexs.PREFIX_FIELD_CMS_BOOLEAN, + Indexs.PREFIX_FIELD_CMS_BOOLEANS, Indexs.PREFIX_FIELD_CMS_NUMBER, + Indexs.PREFIX_FIELD_CMS_NUMBERS, Indexs.PREFIX_FIELD_CMS_DATE, + Indexs.PREFIX_FIELD_CMS_DATES)); + } + names.addAll(Arrays.asList(Indexs.PREFIX_FIELD_DATA_STRING, + Indexs.PREFIX_FIELD_DATA_STRINGS, Indexs.PREFIX_FIELD_DATA_BOOLEAN, + Indexs.PREFIX_FIELD_DATA_BOOLEANS, Indexs.PREFIX_FIELD_DATA_NUMBER, + Indexs.PREFIX_FIELD_DATA_NUMBERS, Indexs.PREFIX_FIELD_DATA_DATE, + Indexs.PREFIX_FIELD_DATA_DATES)); + return names.toArray(new String[] {}); + } + + protected List categories(List dirs) { + if (ListTools.isEmpty(dirs)) { + return new ArrayList<>(); + } + return dirs.stream() + .map(com.x.query.core.express.index.Directory::getCategory).filter(StringUtils::isNotBlank) + .collect(Collectors.toList()); + } + + protected List adjustFacetField(List categories, List filters) { + List list = FACET_FIELDS.stream().filter(o -> (!filters.contains(o))).collect(Collectors.toList()); + if (list.contains(Indexs.FIELD_PROCESSNAME)) { + list.removeAll(Arrays.asList(Indexs.FIELD_APPLICATIONNAME, Indexs.FIELD_PROCESSNAME, + Indexs.FIELD_APPNAME, Indexs.FIELD_CATEGORYNAME)); + } + if (list.contains(Indexs.FIELD_APPLICATIONNAME)) { + list.removeAll(Arrays.asList(Indexs.FIELD_APPLICATIONNAME, Indexs.FIELD_APPNAME, + Indexs.FIELD_CATEGORYNAME)); + } + if (list.contains(Indexs.FIELD_CATEGORYNAME)) { + list.removeAll(Arrays.asList(Indexs.FIELD_APPNAME, Indexs.FIELD_CATEGORYNAME, + Indexs.FIELD_APPLICATIONNAME, Indexs.FIELD_PROCESSNAME)); + } + if (list.contains(Indexs.FIELD_APPNAME)) { + list.removeAll(Arrays.asList(Indexs.FIELD_APPNAME, Indexs.FIELD_APPLICATIONNAME, + Indexs.FIELD_PROCESSNAME)); + } + if (!ListTools.contains(categories, Indexs.CATEGORY_PROCESSPLATFORM)) { + list.remove(Indexs.FIELD_COMPLETED); + } return list; } -} \ No newline at end of file +} diff --git a/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/morelikethis/ActionPost.java b/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/morelikethis/ActionPost.java index 97ab899b078180ed135d5ff4e5203b959a95e4f6..e5745bfd91a1568357e53e079258569f8f651f79 100644 --- a/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/morelikethis/ActionPost.java +++ b/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/morelikethis/ActionPost.java @@ -102,31 +102,31 @@ class ActionPost extends BaseAction { org.apache.lucene.document.Document document = reader.document(scoreDoc.doc); ActionPostWo.WoMoreLikeThis woMoreLikeThis = new ActionPostWo.WoMoreLikeThis(); woMoreLikeThis.setTitle( - Indexs.indexableFieldValue(document.getField(Indexs.FIELD_TITLE), + Indexs.indexableFieldValue(document.getFields(Indexs.FIELD_TITLE), Indexs.FIELD_TYPE_STRING)); woMoreLikeThis.setFlag( - Indexs.indexableFieldValue(document.getField(Indexs.FIELD_ID), + Indexs.indexableFieldValue(document.getFields(Indexs.FIELD_ID), Indexs.FIELD_TYPE_STRING)); woMoreLikeThis.setCategory( - Indexs.indexableFieldValue(document.getField(Indexs.FIELD_CATEGORY), + Indexs.indexableFieldValue(document.getFields(Indexs.FIELD_CATEGORY), Indexs.FIELD_TYPE_STRING)); woMoreLikeThis.setType( - Indexs.indexableFieldValue(document.getField(Indexs.FIELD_TYPE), + Indexs.indexableFieldValue(document.getFields(Indexs.FIELD_TYPE), Indexs.FIELD_TYPE_STRING)); woMoreLikeThis.setKey( - Indexs.indexableFieldValue(document.getField(Indexs.FIELD_KEY), + Indexs.indexableFieldValue(document.getFields(Indexs.FIELD_KEY), Indexs.FIELD_TYPE_STRING)); woMoreLikeThis.setCreateTime( - Indexs.indexableFieldValue(document.getField(Indexs.FIELD_CREATETIME), + Indexs.indexableFieldValue(document.getFields(Indexs.FIELD_CREATETIME), Indexs.FIELD_TYPE_DATE)); woMoreLikeThis.setUpdateTime( - Indexs.indexableFieldValue(document.getField(Indexs.FIELD_UPDATETIME), + Indexs.indexableFieldValue(document.getFields(Indexs.FIELD_UPDATETIME), Indexs.FIELD_TYPE_DATE)); woMoreLikeThis.setCreatorPerson(Indexs.indexableFieldValue( - document.getField(Indexs.FIELD_CREATORPERSON), + document.getFields(Indexs.FIELD_CREATORPERSON), Indexs.FIELD_TYPE_STRING)); woMoreLikeThis.setCreatorUnit(Indexs.indexableFieldValue( - document.getField(Indexs.FIELD_CREATORUNIT), + document.getFields(Indexs.FIELD_CREATORUNIT), Indexs.FIELD_TYPE_STRING)); woMoreLikeThis.setKey(document.get(Indexs.FIELD_KEY)); woMoreLikeThis.setScore(scoreDoc.score); diff --git a/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/morelikethis/BaseAction.java b/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/morelikethis/BaseAction.java index 535c03fe2b9524f1af6fa54203e69f3e291819d9..ad19cb3402850bcde32a59c148bb9cf20ba31a21 100644 --- a/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/morelikethis/BaseAction.java +++ b/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/morelikethis/BaseAction.java @@ -6,7 +6,6 @@ import java.util.Optional; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; import org.apache.lucene.index.Term; -import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.search.Query; import org.apache.lucene.search.TermQuery; diff --git a/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/morelikethis/MoreLikeThisAction.java b/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/morelikethis/MoreLikeThisAction.java index f7041f4812c427d02a16cd7066f7837a89f06b2c..a8db4c99a125f88ee560838411d86c8a2a2daf13 100644 --- a/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/morelikethis/MoreLikeThisAction.java +++ b/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/morelikethis/MoreLikeThisAction.java @@ -22,7 +22,6 @@ import com.x.base.core.project.logger.Logger; import com.x.base.core.project.logger.LoggerFactory; import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.parameters.RequestBody; diff --git a/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/search/ActionPost.java b/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/search/ActionPost.java index 9764780b419c3b66ab1733723a7f527a65225b29..e0487706dadc094efb61ea09779d3b69f5f3771c 100644 --- a/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/search/ActionPost.java +++ b/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/search/ActionPost.java @@ -99,8 +99,9 @@ class ActionPost extends BaseAction { final int facetMaxGroups = Config.query().index().getFacetMaxGroups(); final int searchMaxHits = Config.query().index().getSearchMaxHits(); TopScoreDocCollector topScoreDocCollector = TopScoreDocCollector.create(searchMaxHits, Integer.MAX_VALUE); - List>> firstPassGroupingCollectorPairs = Indexs - .adjustFacetField(wi.getFilterList().stream().map(Filter::getField).collect(Collectors.toList())) + List>> firstPassGroupingCollectorPairs = this + .adjustFacetField( + wi.getFilterList().stream().map(Filter::getField).collect(Collectors.toList())) .stream() .>>map( o -> Pair.of(o, diff --git a/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/search/ActionTest.java b/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/search/ActionTest.java index c4f0d0238683f06ac51db9a8b07541060aad4ff7..28949805308e1a4e3a89f8daa31fd318433d03ab 100644 --- a/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/search/ActionTest.java +++ b/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/search/ActionTest.java @@ -1,21 +1,10 @@ package com.x.query.assemble.surface.jaxrs.search; -import java.util.Optional; - -import org.apache.lucene.index.DirectoryReader; -import org.apache.lucene.index.IndexReader; -import org.apache.lucene.index.LeafReaderContext; -import org.apache.lucene.index.Terms; -import org.apache.lucene.index.TermsEnum; -import org.apache.lucene.store.Directory; -import org.apache.lucene.util.BytesRef; - import com.x.base.core.project.http.ActionResult; import com.x.base.core.project.http.EffectivePerson; import com.x.base.core.project.jaxrs.WrapString; import com.x.base.core.project.logger.Logger; import com.x.base.core.project.logger.LoggerFactory; -import com.x.query.core.express.index.Indexs; class ActionTest extends BaseAction { diff --git a/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/search/BaseAction.java b/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/search/BaseAction.java index 915722cf6b26aa1d932b6d15e85f403008dc4ca4..54b4b5e12fb2564b394f0e5baf887459240b09c0 100644 --- a/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/search/BaseAction.java +++ b/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/search/BaseAction.java @@ -1,5 +1,6 @@ package com.x.query.assemble.surface.jaxrs.search; +import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @@ -69,4 +70,26 @@ abstract class BaseAction extends StandardJaxrsAction { return Optional.of(builder.build()); } + protected List adjustFacetField(List filters) { + List list = FACET_FIELDS.stream().filter(o -> (!filters.contains(o))).collect(Collectors.toList()); + if (list.contains(Indexs.FIELD_PROCESSNAME)) { + list.removeAll(Arrays.asList(Indexs.FIELD_APPLICATIONNAME, Indexs.FIELD_PROCESSNAME, + Indexs.FIELD_APPNAME, Indexs.FIELD_CATEGORYNAME)); + } + if (list.contains(Indexs.FIELD_APPLICATIONNAME)) { + list.removeAll(Arrays.asList(Indexs.FIELD_APPLICATIONNAME, Indexs.FIELD_APPNAME, + Indexs.FIELD_CATEGORYNAME)); + } + if (list.contains(Indexs.FIELD_CATEGORYNAME)) { + list.removeAll(Arrays.asList(Indexs.FIELD_APPNAME, Indexs.FIELD_CATEGORYNAME, + Indexs.FIELD_APPLICATIONNAME, Indexs.FIELD_PROCESSNAME)); + } + if (list.contains(Indexs.FIELD_APPNAME)) { + list.removeAll(Arrays.asList(Indexs.FIELD_APPNAME, Indexs.FIELD_APPLICATIONNAME, + Indexs.FIELD_PROCESSNAME)); + } + list.remove(Indexs.FIELD_COMPLETED); + return list; + } + } \ No newline at end of file diff --git a/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/statement/ActionExecuteV2.java b/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/statement/ActionExecuteV2.java index 180bd60483183736b025a3972abb05769a5deee3..8fa3f154c18da769f7cdc53aae06e4a8a698ea46 100644 --- a/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/statement/ActionExecuteV2.java +++ b/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/statement/ActionExecuteV2.java @@ -13,7 +13,6 @@ import javax.script.Bindings; import javax.script.CompiledScript; import javax.script.ScriptContext; -import com.x.base.core.project.tools.StringTools; import org.apache.commons.collections4.list.TreeList; import org.apache.commons.lang3.StringUtils; diff --git a/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/view/BaseAction.java b/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/view/BaseAction.java index 739a2173c854e68358079ae22cd1b24f72d6f18f..96f980b3e68a04ec91134572e28591b176a3d785 100644 --- a/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/view/BaseAction.java +++ b/o2server/x_query_assemble_surface/src/main/java/com/x/query/assemble/surface/jaxrs/view/BaseAction.java @@ -2,10 +2,13 @@ package com.x.query.assemble.surface.jaxrs.view; import java.io.ByteArrayOutputStream; import java.text.SimpleDateFormat; -import java.util.*; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Optional; import java.util.concurrent.ExecutorService; -import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; diff --git a/o2server/x_query_core_express/src/main/java/com/x/query/core/express/assemble/surface/jaxrs/index/ActionExportWi.java b/o2server/x_query_core_express/src/main/java/com/x/query/core/express/assemble/surface/jaxrs/index/ActionExportWi.java index 4b387cd88f49a269866d136f58593e0335d58249..9f73d2b970e92983e4d9499d8f6619b99f221dc5 100644 --- a/o2server/x_query_core_express/src/main/java/com/x/query/core/express/assemble/surface/jaxrs/index/ActionExportWi.java +++ b/o2server/x_query_core_express/src/main/java/com/x/query/core/express/assemble/surface/jaxrs/index/ActionExportWi.java @@ -5,6 +5,7 @@ import java.util.List; import com.x.base.core.project.annotation.FieldDescribe; import com.x.base.core.project.gson.GsonPropertyObject; +import com.x.query.core.express.index.Directory; import com.x.query.core.express.index.Filter; import com.x.query.core.express.index.Sort; @@ -14,13 +15,9 @@ public class ActionExportWi extends GsonPropertyObject { private static final long serialVersionUID = 1360655000630283661L; - @FieldDescribe("分类.") - @Schema(description = "分类.") - private String category; - - @FieldDescribe("标识.") - @Schema(description = "标识.") - private String key; + @FieldDescribe("检索目录.") + @Schema(description = "检索目录.") + private List directoryList = new ArrayList<>(); @FieldDescribe("搜索内容.") @Schema(description = "搜索内容.") @@ -54,6 +51,14 @@ public class ActionExportWi extends GsonPropertyObject { @Schema(description = "排序字段.") Sort sort; + public List getDirectoryList() { + return directoryList; + } + + public void setDirectoryList(List directoryList) { + this.directoryList = directoryList; + } + public Sort getSort() { return sort; } @@ -102,22 +107,6 @@ public class ActionExportWi extends GsonPropertyObject { this.size = size; } - public String getCategory() { - return category; - } - - public void setCategory(String category) { - this.category = category; - } - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - public String getPerson() { return person; } diff --git a/o2server/x_query_core_express/src/main/java/com/x/query/core/express/assemble/surface/jaxrs/index/ActionPostWi.java b/o2server/x_query_core_express/src/main/java/com/x/query/core/express/assemble/surface/jaxrs/index/ActionPostWi.java index df706ba72fb936e8e4d2a8b0bd001889a663ff13..5d5425f9d6bc8c545de7315fa642e45f55fc3c55 100644 --- a/o2server/x_query_core_express/src/main/java/com/x/query/core/express/assemble/surface/jaxrs/index/ActionPostWi.java +++ b/o2server/x_query_core_express/src/main/java/com/x/query/core/express/assemble/surface/jaxrs/index/ActionPostWi.java @@ -5,6 +5,7 @@ import java.util.List; import com.x.base.core.project.annotation.FieldDescribe; import com.x.base.core.project.gson.GsonPropertyObject; +import com.x.query.core.express.index.Directory; import com.x.query.core.express.index.Filter; import com.x.query.core.express.index.Sort; @@ -16,7 +17,7 @@ public class ActionPostWi extends GsonPropertyObject { @FieldDescribe("检索目录.") @Schema(description = "检索目录.") - private List directoryList = new ArrayList<>(); + private List directoryList = new ArrayList<>(); @FieldDescribe("搜索内容.") @Schema(description = "搜索内容.") @@ -98,11 +99,11 @@ public class ActionPostWi extends GsonPropertyObject { this.size = size; } - public List getDirectoryList() { + public List getDirectoryList() { return directoryList; } - public void setDirectoryList(List directoryList) { + public void setDirectoryList(List directoryList) { this.directoryList = directoryList; } @@ -122,33 +123,4 @@ public class ActionPostWi extends GsonPropertyObject { this.filterList = filterList; } - @Schema(name = "com.x.query.core.express.assemble.surface.jaxrs.index.ActionPostWi$WiDirectory") - public static class WiDirectory { - - @FieldDescribe("分类.") - @Schema(description = "分类.") - private String category; - - @FieldDescribe("标识.") - @Schema(description = "标识.") - private String key; - - public String getCategory() { - return category; - } - - public void setCategory(String category) { - this.category = category; - } - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - } - } diff --git a/o2server/x_query_core_express/src/main/java/com/x/query/core/express/index/Directory.java b/o2server/x_query_core_express/src/main/java/com/x/query/core/express/index/Directory.java new file mode 100644 index 0000000000000000000000000000000000000000..2f2038d34022dc9409973e174fbb2dad4bad0374 --- /dev/null +++ b/o2server/x_query_core_express/src/main/java/com/x/query/core/express/index/Directory.java @@ -0,0 +1,34 @@ +package com.x.query.core.express.index; + +import com.x.base.core.project.annotation.FieldDescribe; + +import io.swagger.v3.oas.annotations.media.Schema; + +@Schema(name = "com.x.query.core.express.index$Directory") +public class Directory { + + @FieldDescribe("分类.") + @Schema(description = "分类.") + private String category; + + @FieldDescribe("标识.") + @Schema(description = "标识.") + private String key; + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + +} \ No newline at end of file diff --git a/o2server/x_query_core_express/src/main/java/com/x/query/core/express/index/Filter.java b/o2server/x_query_core_express/src/main/java/com/x/query/core/express/index/Filter.java index f92da614c321875ba21e608d85277ac61bf8a992..285f62de95a8f3e812a1bdb96e7fb46f79fb27a0 100644 --- a/o2server/x_query_core_express/src/main/java/com/x/query/core/express/index/Filter.java +++ b/o2server/x_query_core_express/src/main/java/com/x/query/core/express/index/Filter.java @@ -9,46 +9,46 @@ import io.swagger.v3.oas.annotations.media.Schema; @Schema(name = "com.x.query.core.express.index.Filter") public class Filter extends GsonPropertyObject { - private static final long serialVersionUID = 8404002412785606829L; + private static final long serialVersionUID = 8404002412785606829L; - String field; + String field; - List valueList; + List valueList; - String start; + String min; - String end; + String max; - public String getField() { - return field; - } + public String getField() { + return field; + } - public void setField(String field) { - this.field = field; - } + public void setField(String field) { + this.field = field; + } - public List getValueList() { - return valueList; - } + public List getValueList() { + return valueList; + } - public void setValueList(List valueList) { - this.valueList = valueList; - } + public void setValueList(List valueList) { + this.valueList = valueList; + } - public String getStart() { - return start; - } + public String getMin() { + return min; + } - public void setStart(String start) { - this.start = start; - } + public void setMin(String min) { + this.min = min; + } - public String getEnd() { - return end; - } + public String getMax() { + return max; + } - public void setEnd(String end) { - this.end = end; - } + public void setMax(String max) { + this.max = max; + } } diff --git a/o2server/x_query_core_express/src/main/java/com/x/query/core/express/index/Indexs.java b/o2server/x_query_core_express/src/main/java/com/x/query/core/express/index/Indexs.java index b77cff9310ed4b018bd2ca0a9ff9df4dd0001365..0c9b236744cc5156db0391322dc8bfa89ccc8879 100644 --- a/o2server/x_query_core_express/src/main/java/com/x/query/core/express/index/Indexs.java +++ b/o2server/x_query_core_express/src/main/java/com/x/query/core/express/index/Indexs.java @@ -8,16 +8,20 @@ import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.Date; import java.util.List; +import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.math.NumberUtils; import org.apache.hadoop.fs.CommonConfigurationKeysPublic; import org.apache.hadoop.fs.LocatedFileStatus; import org.apache.hadoop.fs.RemoteIterator; +import org.apache.lucene.document.LongPoint; import org.apache.lucene.index.IndexableField; import org.apache.lucene.index.Term; import org.apache.lucene.search.BooleanClause; @@ -33,6 +37,7 @@ import com.x.base.core.project.config.Config; import com.x.base.core.project.config.Query; import com.x.base.core.project.logger.Logger; import com.x.base.core.project.logger.LoggerFactory; +import com.x.base.core.project.tools.DateTools; import com.x.base.core.project.tools.ListTools; import com.x.base.core.project.tools.NumberTools; @@ -96,10 +101,13 @@ public class Indexs { public static final String FIELD_HIGHLIGHTING = "highlighting"; public static final String READERS_SYMBOL_ALL = "ALL"; + public static final String BOOLEAN_TRUE_STRING_VALUE = "true"; + public static final String BOOLEAN_FALSE_STRING_VALUE = "false"; + private static final List FACET_FIELDS = Stream.of(FIELD_CATEGORY, FIELD_CREATETIMEMONTH, FIELD_UPDATETIMEMONTH, FIELD_APPLICATIONNAME, FIELD_PROCESSNAME, FIELD_APPNAME, FIELD_CATEGORYNAME, - FIELD_CREATORPERSON, FIELD_CREATORUNIT) + FIELD_CREATORPERSON, FIELD_CREATORUNIT, FIELD_COMPLETED) .collect(Collectors.toUnmodifiableList()); private static final List FIXED_DATE_FIELDS = Stream @@ -125,6 +133,37 @@ public class Indexs { public static final String PREFIX_FIELD_DATA_DATE = PREFIX_FIELD_DATA + FIELD_TYPE_DATE + "_"; public static final String PREFIX_FIELD_DATA_DATES = PREFIX_FIELD_DATA + FIELD_TYPE_DATES + "_"; + public static final String PREFIX_FIELD_PROCESSPLATFORM = "processPlatform_"; + + public static final String FIELD_ROCESSPLATFORM_TASKPERSONNAMES = "taskPersonNames"; + public static final String FIELD_ROCESSPLATFORM_PRETASKPERSONNAMES = "preTaskPersonNames"; + + public static final String PREFIX_FIELD_PROCESSPLATFORM_STRING = PREFIX_FIELD_PROCESSPLATFORM + FIELD_TYPE_STRING + + "_"; + public static final String PREFIX_FIELD_PROCESSPLATFORM_STRINGS = PREFIX_FIELD_PROCESSPLATFORM + FIELD_TYPE_STRINGS + + "_"; + public static final String PREFIX_FIELD_PROCESSPLATFORM_BOOLEAN = PREFIX_FIELD_PROCESSPLATFORM + FIELD_TYPE_BOOLEAN + + "_"; + public static final String PREFIX_FIELD_PROCESSPLATFORM_BOOLEANS = PREFIX_FIELD_PROCESSPLATFORM + + FIELD_TYPE_BOOLEANS + "_"; + public static final String PREFIX_FIELD_PROCESSPLATFORM_NUMBER = PREFIX_FIELD_PROCESSPLATFORM + FIELD_TYPE_NUMBER + + "_"; + public static final String PREFIX_FIELD_PROCESSPLATFORM_NUMBERS = PREFIX_FIELD_PROCESSPLATFORM + FIELD_TYPE_NUMBERS + + "_"; + public static final String PREFIX_FIELD_PROCESSPLATFORM_DATE = PREFIX_FIELD_PROCESSPLATFORM + FIELD_TYPE_DATE + "_"; + public static final String PREFIX_FIELD_PROCESSPLATFORM_DATES = PREFIX_FIELD_PROCESSPLATFORM + FIELD_TYPE_DATES + + "_"; + + public static final String PREFIX_FIELD_CMS = "cms_"; + public static final String PREFIX_FIELD_CMS_STRING = PREFIX_FIELD_CMS + FIELD_TYPE_STRING + "_"; + public static final String PREFIX_FIELD_CMS_STRINGS = PREFIX_FIELD_CMS + FIELD_TYPE_STRINGS + "_"; + public static final String PREFIX_FIELD_CMS_BOOLEAN = PREFIX_FIELD_CMS + FIELD_TYPE_BOOLEAN + "_"; + public static final String PREFIX_FIELD_CMS_BOOLEANS = PREFIX_FIELD_CMS + FIELD_TYPE_BOOLEANS + "_"; + public static final String PREFIX_FIELD_CMS_NUMBER = PREFIX_FIELD_CMS + FIELD_TYPE_NUMBER + "_"; + public static final String PREFIX_FIELD_CMS_NUMBERS = PREFIX_FIELD_CMS + FIELD_TYPE_NUMBERS + "_"; + public static final String PREFIX_FIELD_CMS_DATE = PREFIX_FIELD_CMS + FIELD_TYPE_DATE + "_"; + public static final String PREFIX_FIELD_CMS_DATES = PREFIX_FIELD_CMS + FIELD_TYPE_DATES + "_"; + private static final String[] QUERY_IGNORES = new String[] { "[", "]", "*", "?" }; private static final String[] QUERY_IGNOREREPLACES = new String[] { "", "", "", "" }; @@ -308,8 +347,8 @@ public class Indexs { return list; } - public static Optional readersQuery(List readers) { - if (ListTools.isEmpty(readers)) { + public static Optional readersQuery(Collection readers) { + if ((null == readers) || readers.isEmpty()) { return Optional.empty(); } BooleanQuery.Builder builder = new BooleanQuery.Builder(); @@ -323,19 +362,39 @@ public class Indexs { if (ListTools.isEmpty(filters)) { return list; } - List fields = filters.stream().filter(o -> FACET_FIELDS.contains(o.getField())) - .collect(Collectors.toList()); - if (ListTools.isEmpty(fields)) { - return list; - } - fields.stream().map(Indexs::fitlerQuery).filter(Optional::isPresent).forEach(o -> list.add(o.get())); + filters.stream().map(Indexs::fitlerQuery).filter(Optional::isPresent).forEach(o -> list.add(o.get())); return list; } private static Optional fitlerQuery(Filter filter) { - if (ListTools.isEmpty(filter.getValueList())) { + if (ListTools.isEmpty(filter.getValueList()) && StringUtils.isEmpty(filter.getMin()) + && StringUtils.isEmpty(filter.getMax())) { return Optional.empty(); } + if (filter.getField().startsWith(PREFIX_FIELD_DATA_DATE)) { + if (!(StringUtils.isEmpty(filter.getMin()) && StringUtils.isEmpty(filter.getMax()))) { + return Optional + .of(LongPoint.newRangeQuery(filter.getField(), stringOfDateToLongElseMin(filter.getMin()), + stringOfDateToLongElseMax(filter.getMax()))); + } else { + return Optional.empty(); + } + } + if (filter.getField().startsWith(PREFIX_FIELD_DATA_NUMBER)) { + if (!(StringUtils.isEmpty(filter.getMin()) && StringUtils.isEmpty(filter.getMax()))) { + return Optional + .of(LongPoint.newRangeQuery(filter.getField(), stringOfNumberToLongElseMin(filter.getMin()), + stringOfNumberToLongElseMax(filter.getMax()))); + } else { + return Optional.empty(); + } + } + if (filter.getField().startsWith(PREFIX_FIELD_DATA_BOOLEAN)) { + String value = StringUtils.equalsIgnoreCase(filter.getValueList().get(0), Indexs.BOOLEAN_TRUE_STRING_VALUE) + ? BOOLEAN_TRUE_STRING_VALUE + : BOOLEAN_FALSE_STRING_VALUE; + return Optional.of(new TermQuery(new Term(filter.getField(), value))); + } BooleanQuery.Builder builder = new BooleanQuery.Builder(); filter.getValueList().stream().filter(StringUtils::isNotBlank) .map(o -> new TermQuery(new Term(filter.getField(), o))) @@ -343,7 +402,37 @@ public class Indexs { return Optional.of(builder.build()); } - public static List adjustFacetField(List filters) { + private static Long stringOfDateToLongElseMin(String text) { + try { + Date date = DateTools.parse(text); + return date.getTime(); + } catch (Exception e) { + LOGGER.error(new IllegalArgumentException("text:" + text + " can not parse to date.", e)); + } + return Long.MIN_VALUE; + } + + private static Long stringOfDateToLongElseMax(String text) { + try { + Date date = DateTools.parse(text); + return date.getTime(); + } catch (Exception e) { + LOGGER.error(new IllegalArgumentException("text:" + text + " can not parse to date.", e)); + } + return Long.MAX_VALUE; + } + + private static Long stringOfNumberToLongElseMin(String text) { + Double value = NumberUtils.toDouble(text, Double.MIN_VALUE); + return org.apache.lucene.util.NumericUtils.doubleToSortableLong(value.doubleValue()); + } + + private static Long stringOfNumberToLongElseMax(String text) { + Double value = NumberUtils.toDouble(text, Double.MAX_VALUE); + return org.apache.lucene.util.NumericUtils.doubleToSortableLong(value.doubleValue()); + } + + public static List adjustFacetField(List categories, List filters) { List list = FACET_FIELDS.stream().filter(o -> (!filters.contains(o))).collect(Collectors.toList()); if (list.contains(FIELD_PROCESSNAME)) { list.removeAll(Arrays.asList(FIELD_APPLICATIONNAME, FIELD_PROCESSNAME, @@ -361,6 +450,9 @@ public class Indexs { list.removeAll(Arrays.asList(FIELD_APPNAME, FIELD_APPLICATIONNAME, FIELD_PROCESSNAME)); } + if (!ListTools.contains(categories, Indexs.CATEGORY_PROCESSPLATFORM)) { + list.remove(Indexs.FIELD_COMPLETED); + } return list; } @@ -372,6 +464,20 @@ public class Indexs { */ public static Triple judgeField(String field) { + if (StringUtils.startsWith(field, Indexs.PREFIX_FIELD_DATA)) { + return judgeFieldData(field); + } else if (StringUtils.startsWith(field, Indexs.PREFIX_FIELD_PROCESSPLATFORM)) { + return judgeFieldProcessPlatform(field); + } else if (StringUtils.startsWith(field, Indexs.PREFIX_FIELD_CMS)) { + return judgeFieldCms(field); + } else if (FIXED_DATE_FIELDS.contains(field)) { + return Triple.of(field, field, Indexs.FIELD_TYPE_DATE); + } else { + return Triple.of(field, field, Indexs.FIELD_TYPE_STRING); + } + } + + private static Triple judgeFieldData(String field) { if (StringUtils.startsWith(field, Indexs.PREFIX_FIELD_DATA_STRING)) { return Triple.of(field, StringUtils.substringAfter(field, Indexs.PREFIX_FIELD_DATA_STRING), Indexs.FIELD_TYPE_STRING); @@ -396,29 +502,99 @@ public class Indexs { } else if (StringUtils.startsWith(field, Indexs.PREFIX_FIELD_DATA_BOOLEANS)) { return Triple.of(field, StringUtils.substringAfter(field, Indexs.PREFIX_FIELD_DATA_BOOLEANS), Indexs.FIELD_TYPE_BOOLEANS); - } else if (FIXED_DATE_FIELDS.contains(field)) { - return Triple.of(field, field, Indexs.FIELD_TYPE_DATE); - } else { - return Triple.of(field, field, Indexs.FIELD_TYPE_STRING); } + return Triple.of(field, StringUtils.substringAfter(field, Indexs.PREFIX_FIELD_DATA_STRING), + Indexs.FIELD_TYPE_STRING); } - @SuppressWarnings("unchecked") - public static T indexableFieldValue(IndexableField indexableField, String fileType) { - if (null == indexableField) { - return null; + private static Triple judgeFieldProcessPlatform(String field) { + if (StringUtils.startsWith(field, Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING)) { + return Triple.of(field, StringUtils.substringAfter(field, Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING), + Indexs.FIELD_TYPE_STRING); + } else if (StringUtils.startsWith(field, Indexs.PREFIX_FIELD_PROCESSPLATFORM_DATE)) { + return Triple.of(field, StringUtils.substringAfter(field, Indexs.PREFIX_FIELD_PROCESSPLATFORM_DATE), + Indexs.FIELD_TYPE_DATE); + } else if (StringUtils.startsWith(field, Indexs.PREFIX_FIELD_PROCESSPLATFORM_NUMBER)) { + return Triple.of(field, StringUtils.substringAfter(field, Indexs.PREFIX_FIELD_PROCESSPLATFORM_NUMBER), + Indexs.FIELD_TYPE_NUMBER); + } else if (StringUtils.startsWith(field, Indexs.PREFIX_FIELD_PROCESSPLATFORM_BOOLEAN)) { + return Triple.of(field, StringUtils.substringAfter(field, Indexs.PREFIX_FIELD_PROCESSPLATFORM_BOOLEAN), + Indexs.FIELD_TYPE_BOOLEAN); + } else if (StringUtils.startsWith(field, Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRINGS)) { + return Triple.of(field, StringUtils.substringAfter(field, Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRINGS), + Indexs.FIELD_TYPE_STRINGS); + } else if (StringUtils.startsWith(field, Indexs.PREFIX_FIELD_PROCESSPLATFORM_DATES)) { + return Triple.of(field, StringUtils.substringAfter(field, Indexs.PREFIX_FIELD_PROCESSPLATFORM_DATES), + Indexs.FIELD_TYPE_DATES); + } else if (StringUtils.startsWith(field, Indexs.PREFIX_FIELD_PROCESSPLATFORM_NUMBERS)) { + return Triple.of(field, StringUtils.substringAfter(field, Indexs.PREFIX_FIELD_PROCESSPLATFORM_NUMBERS), + Indexs.FIELD_TYPE_NUMBERS); + } else if (StringUtils.startsWith(field, Indexs.PREFIX_FIELD_PROCESSPLATFORM_BOOLEANS)) { + return Triple.of(field, StringUtils.substringAfter(field, Indexs.PREFIX_FIELD_PROCESSPLATFORM_BOOLEANS), + Indexs.FIELD_TYPE_BOOLEANS); } - if (StringUtils.equalsIgnoreCase(Indexs.FIELD_TYPE_DATE, fileType)) { - Number number = indexableField.numericValue(); + return Triple.of(field, StringUtils.substringAfter(field, Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING), + Indexs.FIELD_TYPE_STRING); + } + + private static Triple judgeFieldCms(String field) { + if (StringUtils.startsWith(field, Indexs.PREFIX_FIELD_CMS_STRING)) { + return Triple.of(field, StringUtils.substringAfter(field, Indexs.PREFIX_FIELD_CMS_STRING), + Indexs.FIELD_TYPE_STRING); + } else if (StringUtils.startsWith(field, Indexs.PREFIX_FIELD_CMS_DATE)) { + return Triple.of(field, StringUtils.substringAfter(field, Indexs.PREFIX_FIELD_CMS_DATE), + Indexs.FIELD_TYPE_DATE); + } else if (StringUtils.startsWith(field, Indexs.PREFIX_FIELD_CMS_NUMBER)) { + return Triple.of(field, StringUtils.substringAfter(field, Indexs.PREFIX_FIELD_CMS_NUMBER), + Indexs.FIELD_TYPE_NUMBER); + } else if (StringUtils.startsWith(field, Indexs.PREFIX_FIELD_CMS_BOOLEAN)) { + return Triple.of(field, StringUtils.substringAfter(field, Indexs.PREFIX_FIELD_CMS_BOOLEAN), + Indexs.FIELD_TYPE_BOOLEAN); + } else if (StringUtils.startsWith(field, Indexs.PREFIX_FIELD_CMS_STRINGS)) { + return Triple.of(field, StringUtils.substringAfter(field, Indexs.PREFIX_FIELD_CMS_STRINGS), + Indexs.FIELD_TYPE_STRINGS); + } else if (StringUtils.startsWith(field, Indexs.PREFIX_FIELD_CMS_DATES)) { + return Triple.of(field, StringUtils.substringAfter(field, Indexs.PREFIX_FIELD_CMS_DATES), + Indexs.FIELD_TYPE_DATES); + } else if (StringUtils.startsWith(field, Indexs.PREFIX_FIELD_CMS_NUMBERS)) { + return Triple.of(field, StringUtils.substringAfter(field, Indexs.PREFIX_FIELD_CMS_NUMBERS), + Indexs.FIELD_TYPE_NUMBERS); + } else if (StringUtils.startsWith(field, Indexs.PREFIX_FIELD_CMS_BOOLEANS)) { + return Triple.of(field, StringUtils.substringAfter(field, Indexs.PREFIX_FIELD_CMS_BOOLEANS), + Indexs.FIELD_TYPE_BOOLEANS); + } + return Triple.of(field, StringUtils.substringAfter(field, Indexs.PREFIX_FIELD_CMS_STRING), + Indexs.FIELD_TYPE_STRING); + } + + @SuppressWarnings("unchecked") + public static T indexableFieldValue(IndexableField[] indexableFields, String fileType) { + if (StringUtils.equalsIgnoreCase(Indexs.FIELD_TYPE_DATES, fileType)) { + return (T) Stream.of(indexableFields).map(IndexableField::numericValue).filter(o -> !Objects.isNull(o)) + .map(o -> new Date(o.longValue())).collect(Collectors.toList()); + } else if (StringUtils.equalsIgnoreCase(Indexs.FIELD_TYPE_NUMBERS, fileType)) { + return (T) Stream.of(indexableFields).map(IndexableField::numericValue).filter(o -> !Objects.isNull(o)) + .map(o -> Double.valueOf(NumericUtils.sortableLongToDouble(o.longValue()))) + .collect(Collectors.toList()); + } else if (StringUtils.equalsIgnoreCase(Indexs.FIELD_TYPE_BOOLEANS, fileType)) { + return (T) Stream.of(indexableFields).map(IndexableField::stringValue).filter(o -> !Objects.isNull(o)) + .map(o -> Boolean.valueOf(StringUtils.equalsIgnoreCase(o, BOOLEAN_TRUE_STRING_VALUE))) + .collect(Collectors.toList()); + } else if (StringUtils.equalsIgnoreCase(Indexs.FIELD_TYPE_STRINGS, fileType)) { + return (T) Stream.of(indexableFields).map(IndexableField::stringValue) + .filter(o -> !Objects.isNull(o)) + .collect(Collectors.toList()); + } else if (StringUtils.equalsIgnoreCase(Indexs.FIELD_TYPE_DATE, fileType)) { + Number number = indexableFields[0].numericValue(); return (null != number) ? (T) new Date(number.longValue()) : null; } else if (StringUtils.equalsIgnoreCase(Indexs.FIELD_TYPE_NUMBER, fileType)) { - Number number = indexableField.numericValue(); + Number number = indexableFields[0].numericValue(); return (null != number) ? (T) Double.valueOf(NumericUtils.sortableLongToDouble(number.longValue())) : null; } else if (StringUtils.equalsIgnoreCase(Indexs.FIELD_TYPE_BOOLEAN, fileType)) { - Number number = indexableField.numericValue(); - return (null != number) ? (T) Boolean.valueOf(number.longValue() != 0L) : null; + String str = indexableFields[0].stringValue(); + return (T) Boolean.valueOf(StringUtils.equalsIgnoreCase(str, BOOLEAN_TRUE_STRING_VALUE)); } else { - String str = indexableField.stringValue(); + String str = indexableFields[0].stringValue(); return (null != str) ? (T) str : null; } } diff --git a/o2server/x_query_core_express/src/main/java/com/x/query/core/express/index/WoField.java b/o2server/x_query_core_express/src/main/java/com/x/query/core/express/index/WoField.java index 6d1beb4e2eba2a692c57acd89e00e5e53e5639cb..099e5e83d6dd1fdd8063b49dff7f05354500134b 100644 --- a/o2server/x_query_core_express/src/main/java/com/x/query/core/express/index/WoField.java +++ b/o2server/x_query_core_express/src/main/java/com/x/query/core/express/index/WoField.java @@ -1,5 +1,7 @@ package com.x.query.core.express.index; +import java.util.Objects; + import com.x.base.core.project.annotation.FieldDescribe; import com.x.base.core.project.gson.GsonPropertyObject; @@ -20,6 +22,24 @@ public class WoField extends GsonPropertyObject { this.fieldType = fieldType; } + @Override + public int hashCode() { + return Objects.hash(field, fieldType, name); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + WoField other = (WoField) obj; + return Objects.equals(field, other.field) && Objects.equals(fieldType, other.fieldType) + && Objects.equals(name, other.name); + } + @FieldDescribe("字段标识.") @Schema(description = "字段标识.") private String field; diff --git a/o2server/x_query_service_processing/src/main/java/com/x/query/service/processing/index/Doc.java b/o2server/x_query_service_processing/src/main/java/com/x/query/service/processing/index/Doc.java index 6870b40f5f612ad4fb2cfede2f3d11802fd7b4ae..2589d2f5e34513023ba413b4680366c3511b48df 100644 --- a/o2server/x_query_service_processing/src/main/java/com/x/query/service/processing/index/Doc.java +++ b/o2server/x_query_service_processing/src/main/java/com/x/query/service/processing/index/Doc.java @@ -1,5 +1,6 @@ package com.x.query.service.processing.index; +import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; @@ -7,6 +8,7 @@ import java.util.Map; import java.util.Objects; import org.apache.commons.lang3.BooleanUtils; +import org.apache.commons.lang3.StringUtils; import org.apache.lucene.document.Field; import org.apache.lucene.document.LongPoint; import org.apache.lucene.document.NumericDocValuesField; @@ -51,8 +53,6 @@ public class Doc extends GsonPropertyObject { private String creatorUnit; - private Boolean completed; - private List readers; private Map stringRepo = new HashMap<>(); @@ -60,92 +60,10 @@ public class Doc extends GsonPropertyObject { private Map booleanRepo = new HashMap<>(); private Map numberRepo = new HashMap<>(); - private Map> stringListRepo = new HashMap<>(); - private Map> dateListRepo = new HashMap<>(); - private Map> booleanListRepo = new HashMap<>(); - private Map> numberListRepo = new HashMap<>(); - - private Map dataStringRepo = new HashMap<>(); - private Map dataDateRepo = new HashMap<>(); - private Map dataBooleanRepo = new HashMap<>(); - private Map dataNumberRepo = new HashMap<>(); - - private Map> dataStringListRepo = new HashMap<>(); - private Map> dataDateListRepo = new HashMap<>(); - private Map> dataBooleanListRepo = new HashMap<>(); - private Map> dataNumberListRepo = new HashMap<>(); - - public Boolean getCompleted() { - return completed; - } - - public void setCompleted(Boolean completed) { - this.completed = completed; - } - - public Map getStringRepo() { - return stringRepo; - } - - public Map getDateRepo() { - return dateRepo; - } - - public Map getBooleanRepo() { - return booleanRepo; - } - - public Map getNumberRepo() { - return numberRepo; - } - - public Map> getStringListRepo() { - return stringListRepo; - } - - public Map> getDateListRepo() { - return dateListRepo; - } - - public Map> getBooleanListRepo() { - return booleanListRepo; - } - - public Map> getNumberListRepo() { - return numberListRepo; - } - - public Map getDataStringRepo() { - return dataStringRepo; - } - - public Map getDataDateRepo() { - return dataDateRepo; - } - - public Map getDataBooleanRepo() { - return dataBooleanRepo; - } - - public Map getDataNumberRepo() { - return dataNumberRepo; - } - - public Map> getDataStringListRepo() { - return dataStringListRepo; - } - - public Map> getDataDateListRepo() { - return dataDateListRepo; - } - - public Map> getDataBooleanListRepo() { - return dataBooleanListRepo; - } - - public Map> getDataNumberListRepo() { - return dataNumberListRepo; - } + private Map> stringsRepo = new HashMap<>(); + private Map> datesRepo = new HashMap<>(); + private Map> booleansRepo = new HashMap<>(); + private Map> numbersRepo = new HashMap<>(); public String getAttachment() { return attachment; @@ -267,74 +185,66 @@ public class Doc extends GsonPropertyObject { this.updateTimeMonth = updateTimeMonth; } - public void addString(String name, String value) { - stringRepo.put(name, value); - } - - public void addDate(String name, Date value) { - dateRepo.put(name, value); - } - - public void addBoolean(String name, Boolean value) { - booleanRepo.put(name, value); - } - - public void addNumber(String name, Number value) { - numberRepo.put(name, value); - } - - public void addStringList(String name, List values) { - stringListRepo.put(name, values); - } - - public void addDateList(String name, List values) { - dateListRepo.put(name, values); - } - - public void addBooleanList(String name, List values) { - booleanListRepo.put(name, values); - } - - public void addNumberList(String name, List values) { - numberListRepo.put(name, values); - } - - public void dataAddString(String name, String value) { - dataStringRepo.put(name, value); + public Doc addString(String prefix, String field, String value) { + if (StringUtils.isNotBlank(value)) { + this.stringRepo.put(prefix + field, value); + } + return this; } - public void dataAddDate(String name, Date value) { - dataDateRepo.put(name, value); + public Doc addDate(String prefix, String field, Date value) { + if (null != value) { + this.dateRepo.put(prefix + field, value); + } + return this; } - public void dataAddBoolean(String name, Boolean value) { - dataBooleanRepo.put(name, value); + public Doc addBoolean(String prefix, String field, Boolean value) { + if (null != value) { + this.booleanRepo.put(prefix + field, value); + } + return this; } - public void dataAddNumber(String name, Number value) { - dataNumberRepo.put(name, value); + public Doc addNumber(String prefix, String field, Number value) { + if (null != value) { + this.numberRepo.put(prefix + field, value); + } + return this; } - public void dataAddStringList(String name, List values) { - dataStringListRepo.put(name, values); + public Doc addStrings(String prefix, String field, Collection values) { + if ((null != values) && (!values.isEmpty())) { + this.stringsRepo.put(prefix + field, values); + } + return this; } - public void dataAddDateList(String name, List values) { - dataDateListRepo.put(name, values); + public Doc addDates(String prefix, String field, Collection values) { + if ((null != values) && (!values.isEmpty())) { + this.datesRepo.put(prefix + field, values); + } + return this; } - public void dataAddBooleanList(String name, List values) { - dataBooleanListRepo.put(name, values); + public Doc addBooleans(String prefix, String field, Collection values) { + if ((null != values) && (!values.isEmpty())) { + this.booleansRepo.put(prefix + field, values); + } + return this; } - public void dataAddNumberList(String name, List values) { - dataNumberListRepo.put(name, values); + public Doc addNumbers(String prefix, String field, Collection values) { + if ((null != values) && (!values.isEmpty())) { + this.numbersRepo.put(prefix + field, values); + } + return this; } public org.apache.lucene.document.Document toDocument(boolean convertData) { org.apache.lucene.document.Document document = new org.apache.lucene.document.Document(); document.add(new StringField(Indexs.FIELD_ID, this.getId(), Field.Store.YES)); - document.add(new TextField(Indexs.FIELD_TITLE, Objects.toString(this.getTitle(), ""), Field.Store.YES)); + addTitle(document, this.getTitle()); document.add(new TextField(Indexs.FIELD_SUMMARY, Objects.toString(this.getSummary(), ""), Field.Store.YES)); document.add(new TextField(Indexs.FIELD_BODY, Objects.toString(this.getBody(), ""), Field.Store.YES)); document.add( @@ -349,28 +259,33 @@ public class Doc extends GsonPropertyObject { addDate(document, Indexs.FIELD_INDEXTIME, new Date()); addDate(document, Indexs.FIELD_CREATETIME, this.getCreateTime()); addDate(document, Indexs.FIELD_UPDATETIME, this.getUpdateTime()); - addBoolean(document, Indexs.FIELD_COMPLETED, this.getCompleted()); if (convertData) { - this.getStringRepo().entrySet().stream().filter(o -> null != o.getValue()) + this.stringRepo.entrySet().stream().filter(o -> null != o.getValue()) .forEach(o -> addString(document, o.getKey(), o.getValue())); - this.getDateRepo().entrySet().stream().filter(o -> null != o.getValue()) + this.dateRepo.entrySet().stream().filter(o -> null != o.getValue()) .forEach(o -> addDate(document, o.getKey(), o.getValue())); - this.getNumberRepo().entrySet().stream().filter(o -> null != o.getValue()) + this.numberRepo.entrySet().stream().filter(o -> null != o.getValue()) .forEach(o -> addNumber(document, o.getKey(), o.getValue())); - this.getBooleanRepo().entrySet().stream().filter(o -> null != o.getValue()) - .forEach(o -> addBoolean(document, o.getKey(), o.getValue())); - this.getDataStringRepo().entrySet().stream().filter(o -> null != o.getValue()) - .forEach(o -> addString(document, Indexs.PREFIX_FIELD_DATA_STRING + o.getKey(), o.getValue())); - this.getDataDateRepo().entrySet().stream().filter(o -> null != o.getValue()) - .forEach(o -> addDate(document, Indexs.PREFIX_FIELD_DATA_DATE + o.getKey(), o.getValue())); - this.getDataNumberRepo().entrySet().stream().filter(o -> null != o.getValue()) - .forEach(o -> addNumber(document, Indexs.PREFIX_FIELD_DATA_NUMBER + o.getKey(), o.getValue())); - this.getDataBooleanRepo().entrySet().stream().filter(o -> null != o.getValue()).forEach( - o -> addBoolean(document, Indexs.PREFIX_FIELD_DATA_BOOLEAN + o.getKey(), o.getValue())); + this.booleanRepo.entrySet().stream().filter(o -> null != o.getValue()).forEach( + o -> addBoolean(document, o.getKey(), o.getValue())); + this.stringsRepo.entrySet().stream().filter(o -> null != o.getValue()) + .forEach(o -> addStrings(document, o.getKey(), o.getValue())); + this.datesRepo.entrySet().stream().filter(o -> null != o.getValue()) + .forEach(o -> addDates(document, o.getKey(), o.getValue())); + this.numbersRepo.entrySet().stream().filter(o -> null != o.getValue()) + .forEach(o -> addNumbers(document, o.getKey(), o.getValue())); + this.booleansRepo.entrySet().stream().filter(o -> null != o.getValue()).forEach( + o -> addBooleans(document, o.getKey(), o.getValue())); } return document; } + private void addTitle(org.apache.lucene.document.Document document, String value) { + String str = Objects.toString(this.getTitle(), ""); + document.add(new TextField(Indexs.FIELD_TITLE, str, Field.Store.YES)); + document.add(new SortedDocValuesField(Indexs.FIELD_TITLE, new BytesRef(str))); + } + private void addString(org.apache.lucene.document.Document document, String field, String value) { document.add(new SortedDocValuesField(field, new BytesRef(value))); document.add(new StringField(field, value, Field.Store.YES)); @@ -391,10 +306,40 @@ public class Doc extends GsonPropertyObject { } private static void addBoolean(org.apache.lucene.document.Document document, String field, Boolean value) { - long store = BooleanUtils.isTrue(value) ? 1L : 0L; - document.add(new NumericDocValuesField(field, store)); - document.add(new LongPoint(field, store)); - document.add(new StoredField(field, store)); + String store = BooleanUtils.isTrue(value) ? Indexs.BOOLEAN_TRUE_STRING_VALUE + : Indexs.BOOLEAN_FALSE_STRING_VALUE; + document.add(new SortedDocValuesField(field, new BytesRef(store))); + document.add(new StringField(field, store, Field.Store.YES)); + } + + private void addStrings(org.apache.lucene.document.Document document, String field, Collection values) { + values.stream().filter(o -> !Objects.isNull(o)) + .forEach(o -> document.add(new StringField(field, o, Field.Store.YES))); + } + + private void addNumbers(org.apache.lucene.document.Document document, String field, Collection values) { + values.stream().filter(o -> !Objects.isNull(o)).forEach(o -> { + long store = org.apache.lucene.util.NumericUtils.doubleToSortableLong(o.doubleValue()); + document.add(new LongPoint(field, store)); + document.add(new StoredField(field, store)); + }); + } + + private void addDates(org.apache.lucene.document.Document document, String field, Collection values) { + values.stream().filter(o -> !Objects.isNull(o)).forEach(o -> { + long store = o.getTime(); + document.add(new LongPoint(field, store)); + document.add(new StoredField(field, store)); + }); + } + + private void addBooleans(org.apache.lucene.document.Document document, String field, + Collection values) { + values.stream().filter(o -> !Objects.isNull(o)).forEach(o -> { + String store = BooleanUtils.isTrue(o) ? Indexs.BOOLEAN_TRUE_STRING_VALUE + : Indexs.BOOLEAN_FALSE_STRING_VALUE; + document.add(new StringField(field, store, Field.Store.YES)); + }); } } \ No newline at end of file diff --git a/o2server/x_query_service_processing/src/main/java/com/x/query/service/processing/index/DocFunction.java b/o2server/x_query_service_processing/src/main/java/com/x/query/service/processing/index/DocFunction.java index 9be3c53d12fa73e103bb304930a3800085006572..d897150c39aea45a52efa4921a75a7b778e37d70 100644 --- a/o2server/x_query_service_processing/src/main/java/com/x/query/service/processing/index/DocFunction.java +++ b/o2server/x_query_service_processing/src/main/java/com/x/query/service/processing/index/DocFunction.java @@ -26,7 +26,6 @@ import com.x.base.core.entity.dataitem.ItemCategory; import com.x.base.core.project.bean.tuple.Pair; import com.x.base.core.project.config.Config; import com.x.base.core.project.config.StorageMapping; -import com.x.base.core.project.exception.ExceptionEntityNotExist; import com.x.base.core.project.gson.XGsonBuilder; import com.x.base.core.project.logger.Logger; import com.x.base.core.project.logger.LoggerFactory; @@ -38,6 +37,8 @@ import com.x.cms.core.entity.FileInfo; import com.x.processplatform.core.entity.content.Attachment; import com.x.processplatform.core.entity.content.Data; import com.x.processplatform.core.entity.content.Review; +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.WorkCompleted; import com.x.processplatform.core.entity.element.Process; @@ -56,6 +57,7 @@ public class DocFunction { private static final List PROCESSPLATFORM_REVIEW_FIELDS = new UnmodifiableList<>( Arrays.asList(Review.person_FIELDNAME)); + private static final List CMS_REVIEW_FIELDS = new UnmodifiableList<>( Arrays.asList(com.x.cms.core.entity.Review.permissionObj_FIELDNAME)); @@ -68,9 +70,9 @@ public class DocFunction { Work work = param.first().entityManagerContainer().find(param.second(), Work.class); if (null != work) { + LOGGER.debug("DocFunction wrapWork:{}.", param.second()); Doc doc = new Doc(); doc.setReaders(readers(param.first(), work)); - doc.setCompleted(false); doc.setId(work.getJob()); doc.setCategory(Indexs.CATEGORY_PROCESSPLATFORM); doc.setType(Indexs.TYPE_WORKCOMPLETED); @@ -82,15 +84,25 @@ public class DocFunction { doc.setUpdateTimeMonth(DateTools.format(work.getUpdateTime(), DateTools.format_yyyyMM)); doc.setCreatorPerson(OrganizationDefinition.name(work.getCreatorPerson())); doc.setCreatorUnit(OrganizationDefinition.name(work.getCreatorUnit())); - doc.addString(Indexs.FIELD_CREATORUNITLEVELNAME, work.getCreatorUnitLevelName()); - doc.addString(Indexs.FIELD_APPLICATION, work.getApplication()); - doc.addString(Indexs.FIELD_APPLICATIONNAME, work.getApplicationName()); - doc.addString(Indexs.FIELD_APPLICATIONALIAS, work.getApplicationAlias()); - doc.addString(Indexs.FIELD_PROCESS, work.getProcess()); - doc.addString(Indexs.FIELD_PROCESSNAME, work.getProcessName()); - doc.addString(Indexs.FIELD_PROCESSALIAS, work.getProcessAlias()); - doc.addString(Indexs.FIELD_JOB, work.getJob()); - doc.addString(Indexs.FIELD_SERIAL, work.getSerial()); + doc.addBoolean(Indexs.PREFIX_FIELD_PROCESSPLATFORM_BOOLEAN, TaskCompleted.completed_FIELDNAME, false); + doc.addString(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING, Work.creatorUnitLevelName_FIELDNAME, + work.getCreatorUnitLevelName()); + doc.addString(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING, Work.application_FIELDNAME, + work.getApplication()); + doc.addString(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING, Work.applicationName_FIELDNAME, + work.getApplicationName()); + doc.addString(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING, Work.applicationAlias_FIELDNAME, + work.getApplicationAlias()); + doc.addString(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING, Work.process_FIELDNAME, work.getProcess()); + doc.addString(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING, Work.processName_FIELDNAME, + work.getProcessName()); + doc.addString(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING, Work.processAlias_FIELDNAME, + work.getProcessAlias()); + doc.addString(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING, Work.job_FIELDNAME, work.getJob()); + doc.addString(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING, Work.serial_FIELDNAME, work.getSerial()); + doc.addString(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING, Work.activityName_FIELDNAME, + work.getActivityName()); + workAddTaskPersonNames(doc, param.first(), work); update(param.first(), work, doc); return Pair.of(work.getApplication(), Optional.of(doc)); } @@ -105,9 +117,9 @@ public class DocFunction { WorkCompleted workCompleted = param.first().entityManagerContainer().find(param.second(), WorkCompleted.class); if (null != workCompleted) { + LOGGER.debug("DocFunction wrapWorkCompleted:{}.", param.second()); Doc doc = new Doc(); doc.setReaders(readers(param.first(), workCompleted)); - doc.setCompleted(true); doc.setId(workCompleted.getJob()); doc.setCategory(Indexs.CATEGORY_PROCESSPLATFORM); doc.setType(Indexs.TYPE_WORKCOMPLETED); @@ -119,17 +131,29 @@ public class DocFunction { doc.setUpdateTimeMonth(DateTools.format(workCompleted.getUpdateTime(), DateTools.format_yyyyMM)); doc.setCreatorPerson(OrganizationDefinition.name(workCompleted.getCreatorPerson())); doc.setCreatorUnit(OrganizationDefinition.name(workCompleted.getCreatorUnit())); - doc.addString(Indexs.FIELD_CREATORUNITLEVELNAME, workCompleted.getCreatorUnitLevelName()); - doc.addString(Indexs.FIELD_APPLICATION, workCompleted.getApplication()); - doc.addString(Indexs.FIELD_APPLICATIONNAME, workCompleted.getApplicationName()); - doc.addString(Indexs.FIELD_APPLICATIONALIAS, workCompleted.getApplicationAlias()); - doc.addString(Indexs.FIELD_PROCESS, workCompleted.getProcess()); - doc.addString(Indexs.FIELD_PROCESSNAME, workCompleted.getProcessName()); - doc.addString(Indexs.FIELD_PROCESSALIAS, workCompleted.getProcessAlias()); - doc.addString(Indexs.FIELD_JOB, workCompleted.getJob()); - doc.addString(Indexs.FIELD_SERIAL, workCompleted.getSerial()); - doc.addBoolean(Indexs.FIELD_EXPIRED, workCompleted.getExpired()); - doc.addDate(Indexs.FIELD_EXPIRETIME, workCompleted.getExpireTime()); + doc.addBoolean(Indexs.PREFIX_FIELD_PROCESSPLATFORM_BOOLEAN, TaskCompleted.completed_FIELDNAME, true); + doc.addString(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING, WorkCompleted.creatorUnitLevelName_FIELDNAME, + workCompleted.getCreatorUnitLevelName()); + doc.addString(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING, WorkCompleted.application_FIELDNAME, + workCompleted.getApplication()); + doc.addString(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING, WorkCompleted.applicationName_FIELDNAME, + workCompleted.getApplicationName()); + doc.addString(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING, WorkCompleted.applicationAlias_FIELDNAME, + workCompleted.getApplicationAlias()); + doc.addString(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING, WorkCompleted.process_FIELDNAME, + workCompleted.getProcess()); + doc.addString(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING, WorkCompleted.processName_FIELDNAME, + workCompleted.getProcessName()); + doc.addString(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING, WorkCompleted.processAlias_FIELDNAME, + workCompleted.getProcessAlias()); + doc.addString(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING, WorkCompleted.job_FIELDNAME, + workCompleted.getJob()); + doc.addString(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRING, WorkCompleted.serial_FIELDNAME, + workCompleted.getSerial()); + doc.addBoolean(Indexs.PREFIX_FIELD_PROCESSPLATFORM_BOOLEAN, WorkCompleted.expired_FIELDNAME, + workCompleted.getExpired()); + doc.addDate(Indexs.PREFIX_FIELD_PROCESSPLATFORM_DATE, WorkCompleted.expireTime_FIELDNAME, + workCompleted.getExpireTime()); update(param.first(), workCompleted, doc); return Pair.of(workCompleted.getApplication(), Optional.of(doc)); } @@ -143,9 +167,9 @@ public class DocFunction { try { Document document = param.first().entityManagerContainer().find(param.second(), Document.class); if (null != document) { + LOGGER.debug("DocFunction wrapDocument:{}.", param.second()); Doc doc = new Doc(); doc.setReaders(readers(param.first(), document)); - doc.setCompleted(true); doc.setId(document.getId()); doc.setCategory(Indexs.CATEGORY_CMS); doc.setType(Indexs.TYPE_DOCUMENT); @@ -157,15 +181,19 @@ public class DocFunction { doc.setUpdateTimeMonth(DateTools.format(document.getUpdateTime(), DateTools.format_yyyyMM)); doc.setCreatorPerson(OrganizationDefinition.name(document.getCreatorPerson())); doc.setCreatorUnit(OrganizationDefinition.name(document.getCreatorUnitName())); - doc.addString(Indexs.FIELD_APPID, document.getAppId()); - doc.addString(Indexs.FIELD_APPNAME, document.getAppName()); - doc.addString(Indexs.FIELD_APPALIAS, document.getAppAlias()); - doc.addString(Indexs.FIELD_CATEGORYID, document.getCategoryId()); - doc.addString(Indexs.FIELD_CATEGORYNAME, document.getCategoryName()); - doc.addString(Indexs.FIELD_CATEGORYALIAS, document.getCategoryAlias()); - doc.addString(Indexs.FIELD_DESCRIPTION, document.getDescription()); - doc.addDate(Indexs.FIELD_PUBLISHTIME, document.getPublishTime()); - doc.addDate(Indexs.FIELD_MODIFYTIME, document.getModifyTime()); + doc.addString(Indexs.PREFIX_FIELD_CMS_STRING, Document.appId_FIELDNAME, + document.getAppId()); + doc.addString(Indexs.PREFIX_FIELD_CMS_STRING, Document.appName_FIELDNAME, + document.getAppName()); + doc.addString(Indexs.PREFIX_FIELD_CMS_STRING, Document.appAlias_FIELDNAME, document.getAppAlias()); + doc.addString(Indexs.PREFIX_FIELD_CMS_STRING, Document.categoryId_FIELDNAME, document.getCategoryId()); + doc.addString(Indexs.PREFIX_FIELD_CMS_STRING, Document.categoryName_FIELDNAME, + document.getCategoryName()); + doc.addString(Indexs.PREFIX_FIELD_CMS_STRING, Document.categoryAlias_FIELDNAME, + document.getCategoryAlias()); + doc.addString(Indexs.PREFIX_FIELD_CMS_STRING, Indexs.FIELD_DESCRIPTION, document.getDescription()); + doc.addDate(Indexs.PREFIX_FIELD_CMS_STRING, Indexs.FIELD_PUBLISHTIME, document.getPublishTime()); + doc.addDate(Indexs.PREFIX_FIELD_CMS_STRING, Indexs.FIELD_MODIFYTIME, document.getModifyTime()); update(param.first(), document, doc, Config.query().index().getDataStringThreshold()); return Pair.of(document.getAppId(), Optional.of(doc)); } @@ -194,6 +222,19 @@ public class DocFunction { return list.stream().distinct().collect(Collectors.toList()); } + private static void workAddTaskPersonNames(Doc doc, Business business, Work work) throws Exception { + List list = business.entityManagerContainer().listEqualAndEqual(Task.class, Task.job_FIELDNAME, + work.getJob(), Task.application_FIELDNAME, work.getApplication()); + doc.addStrings(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRINGS, Indexs.FIELD_ROCESSPLATFORM_TASKPERSONNAMES, + list.stream().map(Task::getPerson).filter(StringUtils::isNotBlank) + .map(OrganizationDefinition::name).distinct() + .collect(Collectors.toList())); + doc.addStrings(Indexs.PREFIX_FIELD_PROCESSPLATFORM_STRINGS, Indexs.FIELD_ROCESSPLATFORM_PRETASKPERSONNAMES, + list.stream().map(Task::getPerson).filter(StringUtils::isNotBlank) + .map(OrganizationDefinition::name).distinct() + .collect(Collectors.toList())); + } + private static List readers(Business business, WorkCompleted workCompleted) throws Exception { List list = business.entityManagerContainer() .fetchEqualAndEqual(Review.class, PROCESSPLATFORM_REVIEW_FIELDS, Review.job_FIELDNAME, @@ -226,8 +267,9 @@ public class DocFunction { } private static void update(Business business, Work work, Doc wrap) { + List items = null; try { - List items = business.entityManagerContainer().listEqualAndEqual(Item.class, + items = business.entityManagerContainer().listEqualAndEqual(Item.class, DataItem.bundle_FIELDNAME, work.getJob(), DataItem.itemCategory_FIELDNAME, ItemCategory.pp); if (!ListTools.isEmpty(items)) { @@ -243,13 +285,13 @@ public class DocFunction { LOGGER.warn("class:DocFunction, function:update work:{}, items is empty.", work.getId()); } } catch (Exception e) { - LOGGER.error(e); + LOGGER.error(new ExceptionWorkUpdate(e, work.getId(), items)); } } private static void update(Business business, WorkCompleted workCompleted, Doc wrap) { + List items = null; try { - List items = null; if (BooleanUtils.isTrue(workCompleted.getMerged())) { Data data = workCompleted.getProperties().getData(); items = CONVERTER.disassemble(gson.toJsonTree(data)); @@ -271,14 +313,15 @@ public class DocFunction { workCompleted.getId()); } } catch (Exception e) { - LOGGER.error(e); + LOGGER.error(new ExceptionWorkCompletedUpdate(e, workCompleted.getId(), items)); } } private static void update(Business business, com.x.cms.core.entity.Document document, Doc wrap, Integer dataStringThreshold) { + List items = null; try { - List items = business.entityManagerContainer().listEqualAndEqual(Item.class, + items = business.entityManagerContainer().listEqualAndEqual(Item.class, DataItem.bundle_FIELDNAME, document.getId(), DataItem.itemCategory_FIELDNAME, ItemCategory.cms); if (!ListTools.isEmpty(items)) { wrap.setBody(DataItemConverter.ItemText.text(items, true, true, true, true, true, ",")); @@ -293,7 +336,7 @@ public class DocFunction { LOGGER.warn("class:DocFunction, function:update document:{}, items is empty.", document.getId()); } } catch (Exception e) { - LOGGER.error(e); + LOGGER.error(new ExceptionDocumentUpdate(e, document.getId(), items)); } } @@ -317,18 +360,18 @@ public class DocFunction { if (StringUtils.length(value) <= dataStringThreshold) { if (BooleanUtils.isTrue(DateTools.isDateTimeOrDateOrTime(value))) { try { - doc.addDate(Indexs.PREFIX_FIELD_DATA_DATE + name, DateTools.parse(value)); + doc.addDate(Indexs.PREFIX_FIELD_DATA_DATE, name, DateTools.parse(value)); } catch (Exception e) { LOGGER.error(e); } } else { - doc.addString(Indexs.PREFIX_FIELD_DATA_STRING + name, value); + doc.addString(Indexs.PREFIX_FIELD_DATA_STRING, name, value); } } } else if (jsonPrimitive.isBoolean()) { - doc.addBoolean(Indexs.PREFIX_FIELD_DATA_BOOLEAN + name, jsonPrimitive.getAsBoolean()); + doc.addBoolean(Indexs.PREFIX_FIELD_DATA_BOOLEAN, name, jsonPrimitive.getAsBoolean()); } else if (jsonPrimitive.isNumber()) { - doc.addNumber(Indexs.PREFIX_FIELD_DATA_NUMBER + name, jsonPrimitive.getAsNumber()); + doc.addNumber(Indexs.PREFIX_FIELD_DATA_NUMBER, name, jsonPrimitive.getAsNumber()); } } @@ -344,10 +387,10 @@ public class DocFunction { if (BooleanUtils.isTrue(list.stream().map(JsonPrimitive::isString).reduce(true, (a, b) -> a && b))) { updateArrayString(doc, name, list); } else if (BooleanUtils.isTrue(list.stream().map(JsonPrimitive::isNumber).reduce(true, (a, b) -> a && b))) { - doc.addNumberList(Indexs.PREFIX_FIELD_DATA_NUMBERS + name, + doc.addNumbers(Indexs.PREFIX_FIELD_DATA_NUMBERS, name, list.stream().map(JsonPrimitive::getAsNumber).collect(Collectors.toList())); } else if (BooleanUtils.isTrue(list.stream().map(JsonPrimitive::isBoolean).reduce(true, (a, b) -> a && b))) { - doc.addBooleanList(Indexs.PREFIX_FIELD_DATA_BOOLEANS + name, + doc.addBooleans(Indexs.PREFIX_FIELD_DATA_BOOLEANS, name, list.stream().map(JsonPrimitive::getAsBoolean).collect(Collectors.toList())); } } @@ -356,7 +399,7 @@ public class DocFunction { List values = list.stream().map(JsonPrimitive::getAsString).collect(Collectors.toList()); if (BooleanUtils .isTrue(values.stream().map(DateTools::isDateTimeOrDateOrTime).reduce(true, (a, b) -> a && b))) { - wrap.addDateList(Indexs.PREFIX_FIELD_DATA_DATES + name, values.stream().map(s -> { + wrap.addDates(Indexs.PREFIX_FIELD_DATA_DATES, name, values.stream().map(s -> { try { return DateTools.parse(s); } catch (Exception e) { @@ -365,7 +408,7 @@ public class DocFunction { return null; }).collect(Collectors.toList())); } else { - wrap.addStringList(Indexs.PREFIX_FIELD_DATA_STRINGS + name, values); + wrap.addStrings(Indexs.PREFIX_FIELD_DATA_STRINGS, name, values); } } diff --git a/o2server/x_query_service_processing/src/main/java/com/x/query/service/processing/index/ExceptionDocumentUpdate.java b/o2server/x_query_service_processing/src/main/java/com/x/query/service/processing/index/ExceptionDocumentUpdate.java new file mode 100644 index 0000000000000000000000000000000000000000..ad02eb521311405e008f147bdb7af6d3114050cf --- /dev/null +++ b/o2server/x_query_service_processing/src/main/java/com/x/query/service/processing/index/ExceptionDocumentUpdate.java @@ -0,0 +1,15 @@ +package com.x.query.service.processing.index; + +import java.util.List; + +import com.x.base.core.project.exception.LanguagePromptException; +import com.x.query.core.entity.Item; + +class ExceptionDocumentUpdate extends LanguagePromptException { + + private static final long serialVersionUID = -9089355008820123519L; + + ExceptionDocumentUpdate(Throwable th, String document, List items) { + super(th, "update document:{} error, items:{}.", document, items); + } +} diff --git a/o2server/x_query_service_processing/src/main/java/com/x/query/service/processing/index/ExceptionWorkCompletedUpdate.java b/o2server/x_query_service_processing/src/main/java/com/x/query/service/processing/index/ExceptionWorkCompletedUpdate.java new file mode 100644 index 0000000000000000000000000000000000000000..274bccae01e30678595436038c39f48cebad6f9e --- /dev/null +++ b/o2server/x_query_service_processing/src/main/java/com/x/query/service/processing/index/ExceptionWorkCompletedUpdate.java @@ -0,0 +1,15 @@ +package com.x.query.service.processing.index; + +import java.util.List; + +import com.x.base.core.project.exception.LanguagePromptException; +import com.x.query.core.entity.Item; + +class ExceptionWorkCompletedUpdate extends LanguagePromptException { + + private static final long serialVersionUID = -9089355008820123519L; + + ExceptionWorkCompletedUpdate(Throwable th, String workCompketed, List items) { + super(th, "update workCompketed:{} error, items:{}.", workCompketed, items); + } +} diff --git a/o2server/x_query_service_processing/src/main/java/com/x/query/service/processing/index/ExceptionWorkUpdate.java b/o2server/x_query_service_processing/src/main/java/com/x/query/service/processing/index/ExceptionWorkUpdate.java new file mode 100644 index 0000000000000000000000000000000000000000..943983cee3f718976dd9329852fb15beea215a49 --- /dev/null +++ b/o2server/x_query_service_processing/src/main/java/com/x/query/service/processing/index/ExceptionWorkUpdate.java @@ -0,0 +1,15 @@ +package com.x.query.service.processing.index; + +import java.util.List; + +import com.x.base.core.project.exception.LanguagePromptException; +import com.x.query.core.entity.Item; + +class ExceptionWorkUpdate extends LanguagePromptException { + + private static final long serialVersionUID = -9089355008820123519L; + + ExceptionWorkUpdate(Throwable th, String work, List items) { + super(th, "update work:{} error, items:{}.", work, items); + } +}