From d08101e0685727a41f0a7dc010aa91d1f0cdddb5 Mon Sep 17 00:00:00 2001 From: yjf <2211675158@qq.com> Date: Fri, 1 Apr 2022 10:33:18 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=B7=A5=E5=85=B7=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src_core/com/tenwa/jbo/manager/BizObject.java | 177 + src_core/com/tenwa/jbo/manager/ConnUtil.java | 109 + .../com/tenwa/jbo/manager/DataObject.java | 51 + src_core/com/tenwa/jbo/manager/DataUtil.java | 4746 +++++++++++++++++ 4 files changed, 5083 insertions(+) create mode 100644 src_core/com/tenwa/jbo/manager/BizObject.java create mode 100644 src_core/com/tenwa/jbo/manager/ConnUtil.java create mode 100644 src_core/com/tenwa/jbo/manager/DataObject.java create mode 100644 src_core/com/tenwa/jbo/manager/DataUtil.java diff --git a/src_core/com/tenwa/jbo/manager/BizObject.java b/src_core/com/tenwa/jbo/manager/BizObject.java new file mode 100644 index 000000000..00c20673d --- /dev/null +++ b/src_core/com/tenwa/jbo/manager/BizObject.java @@ -0,0 +1,177 @@ +package com.tenwa.jbo.manager; + +import com.tenwa.comm.exception.BusinessException; +import org.apache.commons.lang.StringUtils; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class BizObject implements Cloneable { + + private String className; + private List datas; + + private BizObject(String className ) { + this.className = className; + } + + public static BizObject getBizObject(String className ) { + return new BizObject( className ); + } + + public void setAttributeValue( String columnName, Object value ) throws SQLException { + if ( columnName == null || "".equals( columnName ) ) { + throw new SQLException( "column name can not be null" ); + } + + if ( datas == null ) { + datas = new ArrayList(); + } + + if ( value == null || "".equals( value ) ) { + datas.add( new DataObject( columnName, "string", null ) ); + } else { + String type = value.getClass().getSimpleName().toLowerCase(); + if ( !DataObject.types.contains( type ) ) { + throw new SQLException( "unrecognized value type" ); + } + datas.add( new DataObject( columnName, type, value ) ); + } + } + + public List query(String params ) throws Exception { + return query( null, params ); + } + + public List query(List> params ) throws Exception { + return query( params, null ); + } + + public List query(List> paramList, String params ) throws Exception { + List bizObjects = DataUtil.getArrayList(); + String sql = "select * from " + this.getTableName(); + String sqlWhere = ""; + String[] sqlParam = null; + if ( StringUtils.isNotEmpty( params ) ) { + sqlWhere += " where 1 = 1"; + String[] ps = params.split( "," ); + sqlParam = new String[ ps.length ]; + int i = 0; + for ( String p : ps ) { + sqlWhere += " and " + p.split( "=" )[ 0 ] + " = ? "; + sqlParam[ i ++ ] = p.split( "=" )[ 1 ]; + } + } + List> datas; + if ( paramList != null ) { + List> pl = DataUtil.getArrayList(); + sqlWhere += " where 1 = 1"; + List keys = DataUtil.getArrayList(); + for ( int i = 0; i < paramList.size(); i ++ ) { + List p; + Map mp = paramList.get( i ); + int j = 0; + for ( Map.Entry m : mp.entrySet() ) { + String key = m.getKey(); + if ( !keys.contains( key ) ) { + String s = ""; + for ( int x = 0; x < paramList.size(); x ++ ) { + if ( s.length() > 0 ) { + s += ","; + } + s += "?"; + } + sqlWhere += " and " + m.getKey() + " in ( " + s + " )"; + keys.add( key ); + } + if ( pl.size() > j ) { + p = pl.get( j ); + } else { + p = DataUtil.getArrayList(); + pl.add( p ); + } + p.add( m.getValue() ); + j ++; + } + } + List r = DataUtil.getArrayList(); + for ( List p : pl ) { + r.addAll( p ); + } + datas = DataUtil.query( sql + sqlWhere, null, r.toArray() ); + } else { + datas = DataUtil.query( sql + sqlWhere, null, sqlParam ); + } + for ( Map data : datas ) { + BizObject bo = (BizObject) this.clone(); + for ( Map.Entry entry : data.entrySet() ) { + bo.setAttributeValue( entry.getKey(), entry.getValue() ); + } + bizObjects.add( bo ); + } + + return bizObjects; + } + + public String getTableName() { + if ( this.className.indexOf( "." ) != -1 ) { + return this.className.substring( this.className.lastIndexOf( "." ) + 1 ); + } + return this.className; + } + + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public List getDatas() { + return this.datas; + } + + public String getAttribute( String key ) throws Exception { + for ( DataObject data : this.datas ) { + if ( data.getColumnName().equalsIgnoreCase( key ) ) { + return DataUtil.getString( data.getColumnValue() ); + } + } + throw new BusinessException( "column name not found" ); + } + + public void setAttributes( List datas ) { + this.datas = datas; + } + + public void removeColumn( String columnName ) { + int removeIndex = -1; + for ( int i = 0; i < getDatas().size(); i ++ ) { + DataObject dataObject = getDatas().get( i ); + if ( columnName.equals( dataObject.getColumnName() ) ) { + removeIndex = i; + break; + } + } + getDatas().remove( removeIndex ); + } + + @Override + public BizObject clone() throws CloneNotSupportedException { + BizObject newBo = getBizObject( this.getClassName() ); + List dataObjects = this.getDatas(); + if ( dataObjects == null ) { + return newBo; + } + for ( DataObject dataObject : dataObjects ) { + try { + newBo.setAttributeValue( dataObject.getColumnName(), dataObject.getColumnValue() ); + } catch ( SQLException e ) { + } + } + return newBo; + } +} diff --git a/src_core/com/tenwa/jbo/manager/ConnUtil.java b/src_core/com/tenwa/jbo/manager/ConnUtil.java new file mode 100644 index 000000000..69a05d826 --- /dev/null +++ b/src_core/com/tenwa/jbo/manager/ConnUtil.java @@ -0,0 +1,109 @@ +package com.tenwa.jbo.manager; + +import com.amarsoft.are.jbo.JBOException; +import com.amarsoft.are.jbo.JBOFactory; +import com.amarsoft.are.jbo.JBOTransaction; +import com.amarsoft.awe.util.Transaction; + +import java.sql.Connection; + +public class ConnUtil { + + private Connection connection; + private JBOTransaction jboTransaction; + private Transaction transaction; + private boolean flag = false; + + public ConnUtil() throws Exception { + this.flag = true; + this.jboTransaction = JBOFactory.createJBOTransaction(); + this.transaction = Transaction.createTransaction( this.jboTransaction ); + this.connection = this.transaction.getConnection( this.transaction ); + } + + public ConnUtil(JBOTransaction jboTransaction ) throws Exception { + if ( jboTransaction == null ) { + this.flag = true; + this.jboTransaction = JBOFactory.createJBOTransaction(); + } else { + this.jboTransaction = jboTransaction; + } + this.transaction = Transaction.createTransaction( this.jboTransaction ); + this.connection = this.transaction.getConnection( this.transaction ); + } + + public ConnUtil(Transaction transaction ) throws Exception { + if ( transaction == null ) { + this.flag = true; + this.transaction = Transaction.createTransaction( JBOFactory.createJBOTransaction() ); + } else { + this.transaction = transaction; + } + this.jboTransaction = this.transaction.getTransaction(); + this.connection = this.transaction.getConnection( transaction ); + } + + public JBOTransaction getJboTransaction() { + return jboTransaction; + } + + public void setJboTransaction(JBOTransaction jboTransaction) { + this.jboTransaction = jboTransaction; + } + + public Transaction getTransaction() { + return transaction; + } + + public void setTransaction(Transaction transaction) { + this.transaction = transaction; + } + + public Connection getConnection() { + return this.connection; + } + + public void setConnection(Connection connection) { + this.connection = connection; + } + + public void commit() throws JBOException { + if ( this.transaction != null && this.flag ) { + this.transaction.commit(); + this.transaction = null; + } + } + + public void rollback() throws JBOException { + if ( this.transaction != null && this.flag ) { + this.transaction.rollback(); + this.transaction = null; + } + } + + public void close() throws JBOException { + if ( this.transaction != null && this.flag ) { + this.transaction.disConnect(); + this.transaction = null; + } + } + + /** + * 在类被销毁时,判断内部链接是否存在,如果存在,则关闭连接 + * @throws Throwable + */ + @Override + protected void finalize() throws Throwable { + if ( connection != null && !connection.isClosed() && this.flag ) { + connection.close(); + } + + if ( transaction != null && this.flag ) { + transaction.rollback(); + } + + if ( jboTransaction != null && this.flag ) { + jboTransaction.rollback(); + } + } +} diff --git a/src_core/com/tenwa/jbo/manager/DataObject.java b/src_core/com/tenwa/jbo/manager/DataObject.java new file mode 100644 index 000000000..58e353b05 --- /dev/null +++ b/src_core/com/tenwa/jbo/manager/DataObject.java @@ -0,0 +1,51 @@ +package com.tenwa.jbo.manager; + +import java.util.Arrays; +import java.util.List; + +/** + * 数据存储对象 + */ +public class DataObject { + + private String columnName; + /** + * 目前只有string, int, long, double, boolean, date, bigdecimal, serializable + */ + private String columnType; + private Object columnValue; + + public static List types = Arrays.asList( new String[]{ "string", "int", "integer", "long", "double", "boolean", "date", "bigdecimal" } ); + + public DataObject(String columnName, String columnType, Object columnValue) { + this.columnName = columnName; + this.columnType = columnType; + this.columnValue = columnValue; + } + + public String getColumnName() { + return columnName; + } + + public void setColumnName(String columnName) { + this.columnName = columnName; + } + + public String getColumnType() { + return columnType; + } + + public void setColumnType(String columnType) { + this.columnType = columnType; + } + + public Object getColumnValue() { + return columnValue; + } + + public void setColumnValue(Object columnValue) { + this.columnValue = columnValue; + } + + +} diff --git a/src_core/com/tenwa/jbo/manager/DataUtil.java b/src_core/com/tenwa/jbo/manager/DataUtil.java new file mode 100644 index 000000000..bd51acbb4 --- /dev/null +++ b/src_core/com/tenwa/jbo/manager/DataUtil.java @@ -0,0 +1,4746 @@ +package com.tenwa.jbo.manager; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.amarsoft.app.als.sys.tools.DateUtil; +import com.amarsoft.app.util.ProductParamUtil; +import com.amarsoft.app.util.StringUtil; +import com.amarsoft.are.ARE; +import com.amarsoft.are.jbo.*; +import com.amarsoft.are.jbo.impl.StateBizObject; +import com.amarsoft.are.lang.DataElement; +import com.amarsoft.are.util.ASValuePool; +import com.amarsoft.are.util.StringFunction; +import com.amarsoft.awe.control.model.Page; +import com.amarsoft.awe.control.model.Parameter; +import com.amarsoft.awe.dw.ASColumn; +import com.amarsoft.awe.dw.ASDataObject; +import com.amarsoft.awe.dw.ASDataObjectFilter; +import com.amarsoft.awe.dw.ASObjectModel; +import com.amarsoft.awe.dw.datamodel.CatalogModel; +import com.amarsoft.awe.dw.datamodel.StyleModel; +import com.amarsoft.biz.bizlet.Bizlet; +import com.amarsoft.context.ASUser; +import com.amarsoft.dict.als.cache.AWEDataWindowCache; +import com.amarsoft.dict.als.cache.CodeCache; +import com.amarsoft.dict.als.manage.CodeManager; +import com.amarsoft.dict.als.object.Item; +import com.sun.xml.internal.stream.XMLInputFactoryImpl; +import com.sun.xml.internal.stream.XMLOutputFactoryImpl; +import com.tenwa.flow.treeview.action.BaseInitTreeView; +import com.tenwa.flow.treeview.action.TreeItemData; +import com.tenwa.reckon.bean.TabCalBean; +import com.tenwa.reckon.util.UUIDUtil; +import org.apache.commons.lang.StringUtils; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLOutputFactory; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.lang.reflect.Method; +import java.math.BigDecimal; +import java.net.URLDecoder; +import java.sql.*; +import java.sql.Date; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class DataUtil { + + public static ThreadLocal> threadParams = new ThreadLocal<>(); + + public static Map getThreadParams() { + return threadParams.get(); + } + + public static void setThreadParams(Map params) { + threadParams.set(params); + } + + public static Object getThreadParam(String key) { + if (threadParams.get() != null) { + return threadParams.get().get(key); + } + return null; + } + + public static void setThreadParam(String key, Object value) { + Map params = threadParams.get(); + if (params == null) { + params = new ConcurrentHashMap<>(); + } + params.put(key, value); + setThreadParams(params); + } + + public static void removeThreadParams() { + threadParams.remove(); + } + + public static ThreadLocal> paramHolder = new ThreadLocal<>(); + + public static void setHolderParam(Map params) { + paramHolder.set(params); + } + + public static Map getHolderParam() { + return paramHolder.get(); + } + + public static void removeHolderParam() { + paramHolder.remove(); + } + + /** + * 流程参数变更类型 + */ + public static final String TYPE01 = "new variable"; + public static final String TYPE02 = "variable is cleared"; + public static final String TYPE03 = "no change"; + public static final String TYPE04 = "change in type"; + public static final String TYPE05 = "unresolved data type"; + public static final String TYPE06 = ""; + + public static List getArrayList() { + return Collections.synchronizedList(new ArrayList<>()); + } + + /** + * 批处理插入数据 + * + * @param tableName 表名 + * @param dataList 字段信息[字段名称、字段类型、字段值] + * @param tx 事务,可传可不传 + * @return + * @throws Exception + */ + @SuppressWarnings("unchecked") + public static int[] insert(String tableName, List dataList, JBOTransaction tx) throws Exception { + if (tableName == null || "".equals(tableName)) { + return new int[]{0}; + } + if (dataList == null || dataList.size() == 0) { + return new int[]{0}; + } + + List> datas = getArrayList(); + for (int i = 0; i < dataList.size(); i++) { + if (dataList.get(0) instanceof com.tenwa.jbo.manager.BizObject) { + datas.add(((com.tenwa.jbo.manager.BizObject) dataList.get(i)).getDatas()); + } else if (dataList.get(0) instanceof com.amarsoft.are.jbo.BizObject) { + com.amarsoft.are.jbo.BizObject bo = (com.amarsoft.are.jbo.BizObject) dataList.get(i); + datas.add(getDataObjectByJBO(bo)); + } else { + datas.add((List) dataList.get(i)); + } + } + // 生成SQL + StringBuffer table = new StringBuffer("INSERT INTO " + tableName); + StringBuffer column = new StringBuffer("("); + StringBuffer value = new StringBuffer("("); + for (DataObject col : datas.get(0)) { + if (column.length() > 1) { + column.append(","); + value.append(","); + } + column.append(col.getColumnName()); + value.append("?"); + } + column.append(")"); + value.append(")"); + String sql = table.append(column).append(" VALUES").append(value).toString(); + + ConnUtil connUtil = new ConnUtil(tx); + Connection conn = connUtil.getConnection(); + StringBuffer log = new StringBuffer("*************************************************[insert] " + tableName + "**************************************************"); + log.append("\n"); + log.append(sql); + System.out.println("======" + log.toString()); + PreparedStatement ps = null; + int[] result; + try { + ps = conn.prepareStatement(sql); + setParameter(ps, datas, log); + result = ps.executeBatch(); + + if (ARE.getLog().isInfoEnabled()) { + ARE.getLog().info(log.toString()); + ARE.getLog().info("*************************************************[insert] " + tableName + "**************************************************"); + } + connUtil.commit(); + } catch (Exception e) { + e.printStackTrace(); + connUtil.rollback(); + throw e; + } finally { + if (ps != null) ps.close(); + } + return result; + } + + public static int[] update(List dataList, String... keys) throws Exception { + return update(dataList, null, null, keys); + } + + public static int[] update(Object data, JBOTransaction tx, String... keys) throws Exception { + List dataList = getArrayList(); + String tableName = ""; + Object obj = null; + String type = data.getClass().getSimpleName(); + if ("ArrayList".equals(type) || "SynchronizedRandomAccessList".equals(type)) { + obj = ((List) data).get(0); + dataList.addAll((List) data); + } else { + obj = data; + dataList.add(data); + } + if (obj instanceof BizObject) { + tableName = ((BizObject) obj).getTableName(); + } else if (obj instanceof com.amarsoft.are.jbo.BizObject) { + tableName = ((com.amarsoft.are.jbo.BizObject) obj).getBizObjectClass().getName(); + String pattern = "\\d"; + if (Pattern.matches(pattern, tableName.substring(tableName.length() - 1))) { + tableName = tableName.substring(0, tableName.lastIndexOf("X")); + } + } + return update(tableName, dataList, null, tx, keys); + } + + public static int[] update(List dataList, JBOTransaction tx, String... keys) throws Exception { + String tableName = ""; + if (dataList.get(0) instanceof BizObject) { + tableName = ((BizObject) dataList.get(0)).getTableName(); + } else if (dataList.get(0) instanceof com.amarsoft.are.jbo.BizObject) { + tableName = ((com.amarsoft.are.jbo.BizObject) dataList.get(0)).getBizObjectClass().getName(); + } + return update(tableName, dataList, null, tx, keys); + } + + public static int[] update(List dataList, String excludeFields, JBOTransaction tx, String... keys) throws Exception { + String tableName = ""; + if (dataList.get(0) instanceof BizObject) { + tableName = ((BizObject) dataList.get(0)).getTableName(); + } else if (dataList.get(0) instanceof com.amarsoft.are.jbo.BizObject) { + tableName = ((com.amarsoft.are.jbo.BizObject) dataList.get(0)).getBizObjectClass().getName(); + } + return update(tableName, dataList, excludeFields, tx, keys); + } + + public static int[] update(String tableName, List dataList, JBOTransaction tx, String... keys) throws Exception { + return update(tableName, dataList, null, tx, keys); + } + + /** + * 批处理更新数据 + * + * @param tableName 表名 + * @param dataList 字段信息[字段名称、字段类型、字段值] + * @param tx 事务,可传可不传 + * @return + * @throws Exception + */ + public static int[] update(String tableName, List dataList, String excludeFields, JBOTransaction tx, String... keys) throws Exception { + if (tableName == null || "".equals(tableName)) { + return new int[]{0}; + } + if (dataList == null || dataList.size() == 0) { + return new int[]{0}; + } + // 生成SQL + StringBuffer table = new StringBuffer("UPDATE " + tableName); + StringBuffer column = new StringBuffer(); + StringBuffer key = new StringBuffer(); + column.append(" SET "); + List> datas = getArrayList(); + List> removeDataObjects = getArrayList(); + for (int i = 0; i < dataList.size(); i++) { + List data = null; + if (dataList.get(0) instanceof com.tenwa.jbo.manager.BizObject) { + data = ((com.tenwa.jbo.manager.BizObject) dataList.get(i)).getDatas(); + } else if (dataList.get(0) instanceof com.amarsoft.are.jbo.BizObject) { + com.amarsoft.are.jbo.BizObject bo = (com.amarsoft.are.jbo.BizObject) dataList.get(i); + data = getDataObjectByJBO(bo); + } else { + data = (List) dataList.get(i); + } + datas.add(data); + if (StringUtils.isNotEmpty(excludeFields)) { + List removeDataObject = getArrayList(); + for (String removeColumName : excludeFields.toUpperCase().split(",")) { + for (DataObject dataObject : data) { + if (dataObject.getColumnName().toUpperCase().equals(removeColumName)) { + removeDataObject.add(dataObject); + } + } + } + removeDataObjects.add(removeDataObject); + } + } + + for (int i = 0; i < removeDataObjects.size(); i++) { + for (int j = 0; j < removeDataObjects.get(i).size(); j++) { + datas.get(i).remove(removeDataObjects.get(i).get(j)); + } + } + + // 调整因where导致的下标调整 + int num = 1; + Map index = new ConcurrentHashMap<>(); + for (int i = 0; i < datas.get(0).size(); i++) { + DataObject col = datas.get(0).get(i); + if (keys != null && keys.length > 0) { + if (Arrays.stream(keys).anyMatch(str -> str.equalsIgnoreCase(col.getColumnName()))) continue; + } + if (!column.toString().trim().equals("SET")) { + column.append(", "); + } + index.put(col.getColumnName().toUpperCase(), num++); + column.append(col.getColumnName().toUpperCase()).append(" = ?"); + } + + if (keys != null && keys.length > 0) { + key.append(" WHERE "); + for (int j = 0; j < keys.length; j++) { + if (j > 0) { + key.append(" AND "); + } + index.put(keys[j].toUpperCase(), num++); + key.append(keys[j]).append(" = ?"); + } + } + String sql = table.append(column).append(key).toString(); + + ConnUtil connUtil = new ConnUtil(tx); + Connection conn = connUtil.getConnection(); + StringBuffer log = new StringBuffer("*************************************************[update] " + tableName + "**************************************************"); + log.append("\n"); + log.append(sql); + PreparedStatement ps = null; + int[] result; + try { + ps = conn.prepareStatement(sql); + setParameter(ps, datas, log, index); + result = ps.executeBatch(); + + if (ARE.getLog().isInfoEnabled()) { + ARE.getLog().info(log.toString()); + ARE.getLog().info("*************************************************[update] " + tableName + "**************************************************"); + } + connUtil.commit(); + } catch (Exception e) { + e.printStackTrace(); + connUtil.rollback(); + throw e; + } finally { + if (ps != null) ps.close(); + } + return result; + } + + public static void setParameter(PreparedStatement ps, List> datas, StringBuffer log) throws Exception { + setParameter(ps, datas, log, null); + } + + public static void setParameter(PreparedStatement ps, List> datas, StringBuffer log, Map colIndex) throws Exception { + for (int i = 0; i < datas.size(); i++) { + List cols = datas.get(i); + if (cols.size() == 0) { + throw new SQLException("index " + i + " data is empty"); + } + log.append("\n{"); + for (int j = 0; j < cols.size(); j++) { + DataObject col = cols.get(j); + int index; + if (colIndex != null) { + index = colIndex.get(col.getColumnName().toUpperCase()); + } else { + index = j + 1; + } + if (j > 0) { + log.append(", "); + } + log.append(col.getColumnName()).append("=").append(col.getColumnValue()); + switch (col.getColumnType()) { + case "string": + ps.setString(index, StringUtil.empty2Other(col.getColumnValue(), "")); + break; + case "int": + case "integer": + ps.setInt(index, col.getColumnValue() == null ? 0 : (int) col.getColumnValue()); + break; + case "long": + ps.setLong(index, col.getColumnValue() == null ? 0 : (long) col.getColumnValue()); + break; + case "double": + ps.setDouble(index, col.getColumnValue() == null ? 0.0 : (double) col.getColumnValue()); + break; + case "boolean": + if (col.getColumnValue() == null) { + ps.setNull(index, Types.BOOLEAN); + } else { + ps.setBoolean(index, (boolean) col.getColumnValue()); + } + break; + case "bigdecimal": + ps.setBigDecimal(index, col.getColumnValue() == null ? BigDecimal.ZERO : (BigDecimal) col.getColumnValue()); + break; + case "blob": + if (col.getColumnValue() == null) { + ps.setNull(index, Types.BLOB); + } else { + ps.setBlob(index, (Blob) col.getColumnValue()); + } + break; + case "serializable": + if (col.getColumnValue() == null) { + ps.setNull(index, Types.VARCHAR); + } else { + ByteArrayOutputStream bytesOut = null; + ObjectOutputStream objectOut = null; + try { + bytesOut = new ByteArrayOutputStream(); + objectOut = new ObjectOutputStream(bytesOut); + objectOut.writeObject(col.getColumnValue()); + objectOut.flush(); + bytesOut.flush(); + byte[] buf = bytesOut.toByteArray(); + ByteArrayInputStream bytesIn = new ByteArrayInputStream(buf); + ps.setBinaryStream(index, bytesIn, buf.length); + } catch (Exception e) { + throw e; + } finally { + if (objectOut != null) objectOut.close(); + if (bytesOut != null) bytesOut.close(); + } + } + break; + case "date": + if (col.getColumnValue() == null) { + ps.setNull(index, Types.DATE); + } else { + ps.setObject(index, new Timestamp(((Date) col.getColumnValue()).getTime())); + } + break; + // TODO 谁要谁补 + } + } + log.append("}"); + ps.addBatch(); + } + } + + public static int[] insert(BizObject data, JBOTransaction tx) throws Exception { + List datas = getArrayList(); + datas.add(data); + return insert(datas, tx); + } + + public static int[] insert(List dataList, JBOTransaction tx) throws Exception { + String tableName = ""; + if (dataList.get(0) instanceof BizObject) { + tableName = ((BizObject) dataList.get(0)).getTableName(); + } else if (dataList.get(0) instanceof com.amarsoft.are.jbo.BizObject) { + tableName = ((com.amarsoft.are.jbo.BizObject) dataList.get(0)).getBizObjectClass().getName(); + } + return insert(tableName, dataList, tx); + } + + public static int[] insert(String tableName, List datas) throws Exception { + return insert(tableName, datas, null); + } + + public static int insert(List bos) throws Exception { + return insertBizObject(bos, null); + } + + public static int insertBizObject(List bos, JBOTransaction tx) throws Exception { + Map>> datasWillBeSaved = new HashMap<>(); + ConnUtil connUtil = new ConnUtil(tx); + tx = connUtil.getJboTransaction(); + int num = 0; + try { + for (com.amarsoft.are.jbo.BizObject bo : bos) { + String tableName = bo.getBizObjectClass().getName(); + List> datas = datasWillBeSaved.get(tableName); + if (datas == null) { + datas = getArrayList(); + datasWillBeSaved.put(tableName, datas); + } + datas.add(getDataObjectByJBO(bo)); + } + for (Map.Entry>> dataWillBeSaved : datasWillBeSaved.entrySet()) { + num += sum(insert(dataWillBeSaved.getKey(), (List) dataWillBeSaved.getValue(), tx)); + } + connUtil.commit(); + } catch (Exception e) { + connUtil.rollback(); + throw e; + } + return num; + } + + public static int sum(int[] nums) { + int n = 0; + for (int num : nums) { + n += num; + } + return n; + } + + public static Map getMap() { + return getMap(null); + } + + public static Map getMap(String... keyValues) { + Map map = new ConcurrentHashMap<>(); + if (keyValues != null && keyValues.length % 2 == 0) { + for (int i = 0; i < keyValues.length; i++) { + map.put(keyValues[i], keyValues[i + 1]); + i++; + } + } + return map; + } + + public static int[] copy(String fromJBOClassName, String toJBOClassName, String fp, String td, String tc, String excludeColumns, String cf, boolean createKey, JBOTransaction tx) throws Exception { + Map fromParams = getParams(fp); + Map toDeleteParams = getParams(td); + List> setToColumnValues = getParamList(tc); + Map convertFields = getParams(cf); + return copy(fromJBOClassName, toJBOClassName, fromParams, toDeleteParams, setToColumnValues, excludeColumns, convertFields, createKey, tx); + } + + /** + * 复制数据方法 + * + * @param fromJBOClassName 来源JBO类名 + * @param toJBOClassName 去向JBO类名 + * @param fromParams 来源条件参数 + * @param toDeleteParams 去向删除条件参数 + * @param setToColumnValues 去向个别字段设置值 + * @param excludeColumns 去向过滤字段 + * @param convertFields 来源到去向间不同名,相同内容的字段转换如( PID -> ID ) + * @param createKey 去向是否创建主键( UUID ), 如果设置的转换字段中包含去向主键,则这个参数不生效 + * @param tx 事务 + * @return 返回执行结果行数 + * @throws Exception + * @author + */ + public static int[] copy(String fromJBOClassName, String toJBOClassName, Map fromParams, Map toDeleteParams, List> setToColumnValues, String excludeColumns, Map convertFields, boolean createKey, JBOTransaction tx) throws Exception { + ConnUtil connUtil = new ConnUtil(tx); + tx = connUtil.getJboTransaction(); + int[] result = new int[0]; + try { + String fromTableName = fromJBOClassName.substring(fromJBOClassName.lastIndexOf(".") + 1); + String toTableName = toJBOClassName.substring(toJBOClassName.lastIndexOf(".") + 1); + + // 删除To数据 + if (toDeleteParams != null && !toDeleteParams.isEmpty()) { + String sql = "DELETE FROM " + toTableName + " WHERE"; + String[] params = new String[toDeleteParams.size()]; + int i = 0; + for (Map.Entry entry : toDeleteParams.entrySet()) { + if (!sql.endsWith("WHERE")) { + sql += " AND"; + } + sql += " " + entry.getKey() + " = ?"; + params[i] = entry.getValue(); + i++; + } + DataUtil.executeUpdate(sql, tx, params); + } + + List> fromDatas; + + if (fromParams == null || fromParams.isEmpty()) { + String sql = "SELECT * FROM " + fromTableName; + fromDatas = DataUtil.query2(sql, tx); + } else { + String[] fromP = new String[fromParams.size()]; + StringBuffer sql = new StringBuffer("SELECT * FROM ").append(fromTableName).append(" WHERE"); + int i = 0; + for (Map.Entry f : fromParams.entrySet()) { + if (i > 0) { + sql.append(" AND"); + } + fromP[i] = f.getValue(); + sql.append(" ").append(f.getKey()).append(" = ?"); + i++; + } + fromDatas = DataUtil.query2(sql.toString(), tx, fromP); + } + + List datas = getArrayList(); + if (setToColumnValues != null && setToColumnValues.size() > 0) { + for (Map setToColumnValue : setToColumnValues) { + datas.addAll(getInsertDataByMap(fromJBOClassName, fromDatas, excludeColumns, convertFields, createKey, setToColumnValue)); + } + } else { + datas.addAll(getInsertDataByMap(fromJBOClassName, fromDatas, excludeColumns, convertFields, createKey, null)); + } + + insert(toTableName, datas, tx); + connUtil.commit(); + } catch (Exception e) { + connUtil.rollback(); + throw e; + } + return result; + } + + public static int[] copy(String fromJBOClassName, String toJBOClassName, Map fromParams, Map toDeleteParams, Map setToColumnValue, String excludeColumns, Map convertFields, boolean createKey, JBOTransaction tx) throws Exception { + if (setToColumnValue != null && !setToColumnValue.isEmpty()) { + List> setToColumnValues = getArrayList(); + setToColumnValues.add(setToColumnValue); + return copy(fromJBOClassName, toJBOClassName, fromParams, toDeleteParams, setToColumnValues, excludeColumns, convertFields, createKey, tx); + } else { + return copy(fromJBOClassName, toJBOClassName, fromParams, toDeleteParams, (List) setToColumnValue, excludeColumns, convertFields, createKey, tx); + } + } + + public static int[] copyData(String fromJBOName, String toTableName, Map fromParams, Map setToColumnValue, Map convertFields, JBOTransaction tx) throws Exception { + return copyData(fromJBOName, toTableName, fromParams, null, null, null, convertFields, true, tx); + } + + public static int[] copyData(String fromJBOName, String toTableName, Map fromParams, Map toParams, Map setToColumnValue, String excludeColumns, Map convertFields, boolean createKey, JBOTransaction tx) throws Exception { + return copyData(fromJBOName, null, toTableName, fromParams, toParams, setToColumnValue, excludeColumns, convertFields, createKey, tx); + } + + public static int[] copyData(String fromJBOName, List bos, String toTableName, Map fromParams, Map toParams, Map setToColumnValue, String excludeColumns, Map convertFields, boolean createKey, JBOTransaction tx) throws Exception { + if (setToColumnValue != null && !setToColumnValue.isEmpty()) { + List> setToColumnValues = getArrayList(); + setToColumnValues.add(setToColumnValue); + return copyData(fromJBOName, bos, toTableName, fromParams, toParams, setToColumnValues, excludeColumns, convertFields, createKey, tx); + } else { + return copyData(fromJBOName, bos, toTableName, fromParams, toParams, (List) setToColumnValue, excludeColumns, convertFields, createKey, tx); + } + } + + public static int[] copyData(List bos, String toTableName, Map setToColumnValue, Map fieldMapping, boolean createKey, JBOTransaction tx) throws Exception { + return copyData(null, bos, toTableName, null, null, setToColumnValue, null, fieldMapping, createKey, tx); + } + + public static int[] copyData(List bos, String toTableName, Map fromParams, Map setToColumnValue, String excludeColumns, Map fieldMapping, boolean createKey, JBOTransaction tx) throws Exception { + return copyData(null, bos, toTableName, fromParams, null, setToColumnValue, excludeColumns, fieldMapping, createKey, tx); + } + + public static int[] copyData(List bos, String toTableName, Map fromParams, Map toParams, Map setToColumnValue, String excludeColumns, Map fieldMapping, boolean createKey, JBOTransaction tx) throws Exception { + return copyData(null, bos, toTableName, fromParams, toParams, setToColumnValue, excludeColumns, fieldMapping, createKey, tx); + } + + public static int[] copyData(String fromJBOName, List bos, String toTableName, Map fromParams, Map toParams, List> setToColumnValues, String excludeColumns, Map fieldMapping, boolean createKey, JBOTransaction tx) throws Exception { + ConnUtil connUtil = new ConnUtil(tx); + tx = connUtil.getJboTransaction(); + int[] result; + try { + if (toTableName.indexOf(".") != -2) { + toTableName = toTableName.substring(toTableName.lastIndexOf(".") + 1); + } + // 删除To数据 + if (toParams != null && !toParams.isEmpty()) { + String sql = "DELETE FROM " + toTableName + " WHERE"; + String[] params = new String[toParams.size()]; + int i = 0; + for (Map.Entry entry : toParams.entrySet()) { + if (!sql.endsWith("WHERE")) { + sql += " AND"; + } + if (entry.getKey().startsWith("!")) { + sql += " " + entry.getKey().substring(1) + " <> ? "; + } else { + sql += " " + entry.getKey() + " = ?"; + } + params[i] = entry.getValue(); + i++; + } + DataUtil.executeUpdate(sql, tx, params); + } + + List fromJBO = null; + if (bos != null) { + fromJBO = bos; + } else { + BizObjectManager fromJBOManager = JBOFactory.getBizObjectManager(fromJBOName, tx); + String fromSql = getSqlByParams(fromParams); + BizObjectQuery fromJBOQuery = fromJBOManager.createQuery(fromSql); + setParameter(fromJBOQuery, fromParams); + fromJBO = fromJBOQuery.getResultList(false); + } + if (fromJBO.size() > 0) { + List datas = getArrayList(); + if (setToColumnValues != null && setToColumnValues.size() > 0) { + for (Map setToColumnValue : setToColumnValues) { + datas.addAll(getInsertDataByJBO(fromJBO, excludeColumns, fieldMapping, createKey, setToColumnValue)); + } + } else { + datas.addAll(getInsertDataByJBO(fromJBO, excludeColumns, fieldMapping, createKey, null)); + } + + result = insert(toTableName, datas, tx); + } else { + if (ARE.getLog().isInfoEnabled()) { + ARE.getLog().info("FROM " + fromJBOName + " DATA NOT FOUND"); + } + result = new int[0]; + } + connUtil.commit(); + } catch (Exception e) { + connUtil.rollback(); + throw e; + } + return result; + } + + public static int[] copyDataBySql(String sql, String toJBOClassName, String fp, String td, String tc, String excludeColumns, String cf, boolean createKey, JBOTransaction tx) throws Exception { + Map fromParams = getParams(fp); + Map toDeleteParams = getParams(td); + List> setToColumnValues = getParamList(tc); + Map convertFields = getParams(cf); + return copyDataBySql(sql, toJBOClassName, fromParams, toDeleteParams, setToColumnValues, excludeColumns, convertFields, createKey, tx); + } + + public static int[] copyDataBySql(String sql, String toJBOClassName, Map fromParams, Map toParams, List> setToColumnValues, String excludeColumns, Map fieldMapping, boolean createKey, JBOTransaction tx) throws Exception { + ConnUtil connUtil = new ConnUtil(tx); + tx = connUtil.getJboTransaction(); + int[] result; + try { + String oldToJBOClassName = toJBOClassName; + if (toJBOClassName.indexOf(".") != -2) { + toJBOClassName = toJBOClassName.substring(toJBOClassName.lastIndexOf(".") + 1); + } + // 删除To数据 + if (toParams != null && !toParams.isEmpty()) { + String delSql = "DELETE FROM " + toJBOClassName + " WHERE"; + String[] params = new String[toParams.size()]; + int i = 0; + for (Map.Entry entry : toParams.entrySet()) { + if (!sql.endsWith("WHERE")) { + delSql += " AND"; + } + delSql += " " + entry.getKey() + " = ?"; + params[i] = entry.getValue(); + i++; + } + DataUtil.executeUpdate(delSql, tx, params); + } + + List fromJBO = convertListToJBO2(oldToJBOClassName, query(sql, fromParams, tx)); + if (fromJBO.size() > 0) { + List datas = getArrayList(); + if (setToColumnValues != null && setToColumnValues.size() > 0) { + for (Map setToColumnValue : setToColumnValues) { + datas.addAll(getInsertDataByJBO(fromJBO, excludeColumns, fieldMapping, createKey, setToColumnValue)); + } + } else { + datas.addAll(getInsertDataByJBO(fromJBO, excludeColumns, fieldMapping, createKey, null)); + } + + result = insert(toJBOClassName, datas, tx); + } else { + if (ARE.getLog().isInfoEnabled()) { + ARE.getLog().info("FROM SQL [" + sql + "] DATA NOT FOUND"); + } + result = new int[0]; + } + connUtil.commit(); + } catch (Exception e) { + connUtil.rollback(); + throw e; + } + return result; + } + + public static List getDataObjectByMap(Map columns) { + List data = getArrayList(); + for (Map.Entry column : columns.entrySet()) { + data.add(new DataObject(column.getKey().toUpperCase(), "string", column.getValue())); + } + return data; + } + + public static String getSqlByParams(Map params) { + if (params == null || params.isEmpty()) { + return "1 = 1"; + } + StringBuffer sql = new StringBuffer(); + for (String key : params.keySet()) { + if (sql.length() > 0) { + sql.append(" AND "); + } + sql.append(key.toUpperCase()).append("=:").append(key.toUpperCase()); + } + return sql.toString(); + } + + public static void setParameter(BizObjectQuery query, Map params) { + if (params != null && !params.isEmpty()) { + for (Map.Entry param : params.entrySet()) { + query.setParameter(param.getKey().toUpperCase(), param.getValue()); + } + } + } + + public static List> getInsertDataByJBO(List jbos) { + return getInsertDataByJBO(jbos, null, null, false, null); + } + + public static List> getInsertDataByJBO(List jbos, String excludeColumns) { + return getInsertDataByJBO(jbos, excludeColumns, null, false, null); + } + + public static List> getInsertDataByJBO(List jbos, String excludeColumns, Map fieldMapping, boolean createKey, Map setToColumnValue) { + List> datas = getArrayList(); + for (com.amarsoft.are.jbo.BizObject jbo : jbos) { + List data = getDataObjectByJBO(jbo, fieldMapping, createKey, excludeColumns); + datas.add(getCleanData(data, setToColumnValue)); + } + return datas; + } + + public static List> getInsertDataByMap(String fromJBOClassName, List> fromDatas, String excludeColumns, Map fieldMapping, boolean createKey, Map setToColumnValue) throws Exception { + List> datas = getArrayList(); + for (List f : fromDatas) { + List data = getDataObjectByMap(fromJBOClassName, f, fieldMapping, createKey, excludeColumns); + datas.add(getCleanData(data, setToColumnValue)); + } + return datas; + } + + public static List getCleanData(List data, Map setToColumnValue) { + if (setToColumnValue != null && !setToColumnValue.isEmpty()) { + List toData = getDataObjectByMap(setToColumnValue); + List notContainsData = getArrayList(); + for (DataObject d1 : toData) { + boolean flag = false; + for (DataObject d2 : data) { + if (d2.getColumnName().equals(d1.getColumnName())) { + d2.setColumnType(d1.getColumnType()); + d2.setColumnValue(d1.getColumnValue()); + flag = true; + break; + } + } + if (!flag) { + notContainsData.add(d1); + } + } + data.addAll(notContainsData); + } + return data; + } + + public static List getDataObjectByMap(String fromJBOClassName, List data, Map fieldMapping, boolean createKey, String excludeColumns) throws Exception { + List rData = getArrayList(); + BizObjectClass fromBizObjectClass = JBOFactory.getBizObjectClass(fromJBOClassName); + DataElement[] attributes = fromBizObjectClass.getAttributes(); + List excludeColumnsList = new ArrayList<>(); + if (excludeColumns != null && !"".equals(excludeColumns)) { + String[] keys = excludeColumns.toUpperCase().split(","); + for (String key : keys) { + excludeColumnsList.add(key); + } + } + if (createKey) { + String[] keys = fromBizObjectClass.getKeyAttributes(); + for (String key : keys) { + String value = ""; + try { + for (DataObject dataObject : data) { + if (dataObject.getColumnName().equals(key)) { + value = getString(dataObject.getColumnValue()); + break; + } + } + } catch (Exception e) { + e.printStackTrace(); + } + + if (fieldMapping != null && fieldMapping.containsValue(key) && !"".equals(value)) { + continue; + } + excludeColumnsList.add(key.toUpperCase()); + rData.add(new DataObject(key, "string", UUIDUtil.getUUID())); + } + } + + for (DataElement de : attributes) { + if (fieldMapping != null && !fieldMapping.isEmpty() && fieldMapping.containsKey(de.getName().toUpperCase())) { + DataObject dataObject = getDataObject(data, de.getName()); + dataObject.setColumnName(fieldMapping.get(de.getName().toUpperCase()).toUpperCase()); + rData.add(dataObject); + continue; + } + if (excludeColumnsList.size() > 0 && excludeColumnsList.contains(de.getName().toUpperCase())) { + continue; + } + + rData.add(getDataObject(data, de.getName())); + } + + return rData; + } + + public static DataObject getDataObject(List data, String colName) { + for (DataObject dataObject : data) { + if (dataObject.getColumnName().equalsIgnoreCase(colName)) { + return new DataObject(dataObject.getColumnName(), dataObject.getColumnType(), dataObject.getColumnValue()); + } + } + System.out.println(colName + "========="); + return null; + } + + public static List getDataObjectByJBO(com.amarsoft.are.jbo.BizObject jbo) { + return getDataObjectByJBO(jbo, null, false, null); + } + + public static List getDataObjectByJBO(com.amarsoft.are.jbo.BizObject jbo, Map fieldMapping, boolean createKey, String excludeColumns) { + if (jbo == null) { + return null; + } + List data = getArrayList(); + if (createKey) { + String[] keys = jbo.getBizObjectClass().getKeyAttributes(); + if (excludeColumns == null) { + excludeColumns = ""; + } + + for (String key : keys) { + String value = ""; + try { + value = jbo.getAttribute(key).getString(); + } catch (Exception e) { + e.printStackTrace(); + } + + if (fieldMapping != null && fieldMapping.containsValue(key) && !"".equals(value)) { + continue; + } + if (!"".equals(excludeColumns)) { + excludeColumns += ","; + } + excludeColumns += key; + data.add(new DataObject(key, "string", UUIDUtil.getUUID())); + } + } + for (DataElement de : jbo.getAttributes()) { + if (fieldMapping != null && !fieldMapping.isEmpty() && fieldMapping.containsKey(de.getName().toUpperCase())) { + data.add(new DataObject(fieldMapping.get(de.getName().toUpperCase()).toUpperCase(), "string", de.isNull() ? "" : de.getString())); + continue; + } + if (excludeColumns != null && excludeColumns.toUpperCase().contains(de.getName().toUpperCase())) { + continue; + } + switch (de.getType()) { + case 1: + data.add(new DataObject(de.getName().toUpperCase(), "int", de.isNull() ? 0 : de.getInt())); + break; + case 2: + data.add(new DataObject(de.getName().toUpperCase(), "long", de.isNull() ? 0 : de.getLong())); + break; + case 4: + data.add(new DataObject(de.getName().toUpperCase(), "double", de.isNull() ? 0.0 : de.getDouble())); + break; + case 8: + data.add(new DataObject(de.getName().toUpperCase(), "boolean", de.isNull() ? null : de.getBoolean())); + break; + case 16: + data.add(new DataObject(de.getName().toUpperCase(), "date", de.isNull() ? null : de.getDate())); + break; + default: + data.add(new DataObject(de.getName().toUpperCase(), "string", de.isNull() ? "" : de.getString())); + } + } + return data; + } + + public static int executeUpdate(String sql) throws Exception { + return executeUpdate(sql, null, null); + } + + public static int executeUpdate(String sql, Object... params) throws Exception { + return executeUpdate(sql, null, null, params); + } + + public static int executeUpdate(String sql, JBOTransaction tx) throws Exception { + return executeUpdate(sql, tx, null); + } + + public static int executeUpdate(String sql, JBOTransaction tx, Object... params) throws Exception { + return executeUpdate(sql, null, tx, params); + } + + public static int executeUpdate(String sql, List> paramList, JBOTransaction tx, Object... params) throws Exception { + ConnUtil connUtil = new ConnUtil(tx); + PreparedStatement ps = null; + int num; + try { + Connection conn = connUtil.getConnection(); + ps = conn.prepareStatement(sql); + if (paramList == null) { + setParameter(ps, params); + num = ps.executeUpdate(); + } else { + setParameterList(paramList, ps, params); + num = sum(ps.executeBatch()); + } + connUtil.commit(); + } catch (Exception e) { + connUtil.rollback(); + throw e; + } finally { + if (ps != null) { + ps.close(); + } + } + return num; + } + + public static void setParameterList(List> paramList, PreparedStatement preparedStatement, Object... params) throws Exception { + for (List param : paramList) { + int i = 0; + for (int j = 0; j < param.size(); j++) { + preparedStatement.setObject(++i, param.get(j)); + } + if (params != null) { + for (int x = 0; x < params.length; x++) { + preparedStatement.setObject(i + 1, params[x]); + } + } + preparedStatement.addBatch(); + } + } + + public static void setParameter(PreparedStatement preparedStatement, Object... params) throws Exception { + if (params != null) { + for (int i = 0; i < params.length; i++) { + preparedStatement.setObject(i + 1, params[i]); + } + } + } + + public static List> convertArrayToList(String[] array) { + if (array == null || array.length == 0) { + return null; + } + List> lists = getArrayList(); + for (String a : array) { + List list = getArrayList(); + list.add(a); + lists.add(list); + } + + return lists; + } + + public static String getValueBySql(String sql) throws Exception { + return getValueBySql(sql, null, null); + } + + public static String getValueBySql(String sql, Object... params) throws Exception { + return getValueBySql(sql, null, params); + } + + public static String getValueBySql(String sql, JBOTransaction tx, Object... params) throws Exception { + List> list = query(sql, tx, params); + if (list.isEmpty()) { + throw new SQLException("no data found"); + } + if (list.size() > 1) { + throw new SQLException("find multiline data"); + } + Map data = list.get(0); + if (data.values().size() > 1) { + throw new SQLException("find multiple columns"); + } + return data.values().iterator().next(); + } + + public static Map queryOneRow(String sql, JBOTransaction tx, Object... params) throws Exception { + List> list = query(sql, tx, params); + if (list.isEmpty()) { + throw new SQLException("no data found"); + } + if (list.size() > 1) { + throw new SQLException("find multiline data"); + } + Map data = list.get(0); + return data; + } + + public static List> query(String sql, Map params, JBOTransaction tx) throws Exception { + if (!sql.toLowerCase().contains("where")) { + sql += " where 1 = 1"; + } + String[] p = new String[params.size()]; + String where = sql.substring(sql.toLowerCase().lastIndexOf("where") + 5); + int i = 0; + for (Map.Entry param : params.entrySet()) { + String key = param.getKey(); + String value = param.getValue(); + if (where.contains(key)) { + continue; + } + sql += " and " + key + " = ?"; + p[i++] = value; + } + return query(sql, tx, p); + } + + public static List> query(String sql) throws Exception { + return query(sql, (JBOTransaction) null, null); + } + + public static List> query(String sql, Object... params) throws Exception { + return query(sql, null, params); + } + + public static List> query(String sql, JBOTransaction tx) throws Exception { + return query(sql, tx, null); + } + + public static List> query(final String sql, JBOTransaction tx, final Object... params) throws Exception { + ConnUtil connUtil = new ConnUtil(tx); + Connection conn; + PreparedStatement ps = null; + ResultSet rs = null; + List> list = getArrayList(); + try { + conn = connUtil.getConnection(); + ps = conn.prepareStatement(sql); + setParameter(ps, params); + + rs = ps.executeQuery(); + ResultSetMetaData rsmd = rs.getMetaData(); + + while (rs.next()) { + Map result = new HashMap<>(); + for (int i = 1; i <= rsmd.getColumnCount(); i++) { + String colName = rsmd.getColumnLabel(i); + result.put(colName, rs.getString(colName)); + } + list.add(result); + } + connUtil.commit(); + } catch (Exception e) { + connUtil.rollback(); + throw e; + } finally { + if (rs != null) { + rs.close(); + } + if (ps != null) { + ps.close(); + } + } + return list; + } + + public static List queryOneColumn(final String sql, JBOTransaction tx, final Object... params) throws Exception { + ConnUtil connUtil = new ConnUtil(tx); + Connection conn; + PreparedStatement ps = null; + ResultSet rs = null; + List list = getArrayList(); + try { + conn = connUtil.getConnection(); + ps = conn.prepareStatement(sql); + setParameter(ps, params); + + rs = ps.executeQuery(); + ResultSetMetaData rsmd = rs.getMetaData(); + + while (rs.next()) { + String value = ""; + for (int i = 1; i <= rsmd.getColumnCount(); i++) { + String colName = rsmd.getColumnLabel(i); + value = rs.getString(colName); + } + list.add(value); + } + connUtil.commit(); + } catch (Exception e) { + connUtil.rollback(); + throw e; + } finally { + if (rs != null) { + rs.close(); + } + if (ps != null) { + ps.close(); + } + } + return list; + } + + public static List> query2(final String sql, JBOTransaction tx, final Object... params) throws Exception { + ConnUtil connUtil = new ConnUtil(tx); + Connection conn; + PreparedStatement ps = null; + ResultSet rs = null; + List> list = getArrayList(); + try { + conn = connUtil.getConnection(); + ps = conn.prepareStatement(sql); + setParameter(ps, params); + + rs = ps.executeQuery(); + ResultSetMetaData rsmd = rs.getMetaData(); + + while (rs.next()) { + List data = getArrayList(); + for (int i = 1; i <= rsmd.getColumnCount(); i++) { + String colName = rsmd.getColumnLabel(i); + int typeNum = rsmd.getColumnType(i); + Object value; + String colType; + switch (typeNum) { + case 2004: + value = rs.getBlob(colName); + colType = "blob"; + break; + default: + value = rs.getString(colName); + colType = "string"; + break; + } + data.add(new DataObject(colName.toUpperCase(), colType, value)); + } + list.add(data); + } + connUtil.commit(); + } catch (Exception e) { + connUtil.rollback(); + throw e; + } finally { + if (rs != null) { + rs.close(); + } + if (ps != null) { + ps.close(); + } + } + return list; + } + + public static Map flowVariablesHis(String flowunid, String taskId) throws Exception { + return flowVariables("flow_varinst_his", null, flowunid, taskId); + } + + public static Map flowVariablesHis(JBOTransaction tx, String flowunid, String taskId) throws Exception { + return flowVariables("flow_varinst_his", tx, flowunid, taskId); + } + + public static Map flowVariables(String flowunid) throws Exception { + return flowVariables("flow_varinst", null, flowunid, ""); + } + + public static Map flowVariables(String flowunid, String taskId) throws Exception { + return flowVariables("flow_varinst", null, flowunid, taskId); + } + + public static Map flowVariables(JBOTransaction tx, String flowunid, String taskId) throws Exception { + return flowVariables("flow_varinst", tx, flowunid, taskId); + } + + public static Map flowVariables(JBOTransaction tx, String flowunid) throws Exception { + return flowVariables("flow_varinst", tx, flowunid, ""); + } + + public static Map flowVariables(String tableName, JBOTransaction tx, String flowunid, String taskId) throws Exception { + return flowVariables(tableName, tx, flowunid, taskId, null); + } + + public static Map flowVariables(String tableName, JBOTransaction tx, String flowunid, String taskId, String name) throws Exception { + ConnUtil connUtil = new ConnUtil(tx); + PreparedStatement ps = null; + ResultSet rs = null; + Map variables = new ConcurrentHashMap<>(); + try { + Connection conn = connUtil.getConnection(); + if (StringUtils.isEmpty(name)) { + ps = conn.prepareStatement("select name_, value_, var_type_, bytes_ from " + tableName + " where flow_unid_ = ?" + ("".equals(taskId) ? "" : " and task_id_ = ?")); + } else { + name = getSqlInCondition(name.split(",")); + ps = conn.prepareStatement("select name_, value_, var_type_, bytes_ from " + tableName + " where name_ in ( " + name + " ) and flow_unid_ = ?" + ("".equals(taskId) ? "" : " and task_id_ = ?")); + } + if ("".equals(taskId)) { + setParameter(ps, flowunid); + } else { + setParameter(ps, flowunid, taskId); + } + rs = ps.executeQuery(); + + while (rs.next()) { + String type = rs.getString("var_type_"); + if ("serializable".equals(type)) { + variables.put(rs.getString("name_"), getObject(rs.getBytes("bytes_"))); + } else { + variables.put(rs.getString("name_"), getString(rs.getObject("value_"))); + } + } + connUtil.commit(); + } catch (Exception e) { + connUtil.rollback(); + throw e; + } finally { + if (rs != null) { + rs.close(); + } + if (ps != null) { + ps.close(); + } + } + return variables; + } + + public static String getStringOptionByItem(Item[] items) { + if (items == null) { + return ""; + } + + List> maps = getArrayList(); + Arrays.stream(items).forEach(item -> { + Map map = new ConcurrentHashMap<>(); + map.put("label", item.getItemName()); + map.put("value", item.getItemNo()); + maps.add(map); + }); + + return JSON.toJSONString(maps); + } + + public static String getStringByItem(Item[] items) { + if (items == null) { + return ""; + } + + Map map = new ConcurrentHashMap<>(); + + Arrays.stream(items).forEach(item -> map.put(item.getItemNo(), item.getItemName())); + + return JSON.toJSONString(map); + } + + public static String getStringByStyleModel(List styleModels) { + if (styleModels == null) { + return ""; + } + Map map = new ConcurrentHashMap<>(); + + styleModels.forEach(styleModel -> map.put(styleModel.getStyleId(), styleModel.getStyleName())); + + return JSON.toJSONString(map); + } + + public static String getStringOptionByStyleModel(List styleModels) { + if (styleModels == null) { + return ""; + } + List> maps = getArrayList(); + styleModels.forEach(styleModel -> { + Map map = new ConcurrentHashMap<>(); + map.put("label", styleModel.getStyleName()); + map.put("value", styleModel.getStyleId()); + maps.add(map); + }); + + return JSON.toJSONString(maps); + } + + + public static String getStringByJBOClass(String[] cls) { + if (cls == null) { + return ""; + } + + List> maps = getArrayList(); + + Arrays.stream(cls).forEach(c -> { + String packageName = c.substring(0, c.lastIndexOf(".")); + boolean flag = false; + + try { + BizObjectClass boc = JBOFactory.getBizObjectClass(c); + String classLabel = boc.getLabel(); + String[] keys = boc.getKeyAttributes(); + String jboWhere = getSqlWhereByDataElement(keys); + + for (Map map : maps) { + if (packageName.equals(map.get("label"))) { + map.get("label"); + Map jbo = new HashMap<>(); + jbo.put("label", c.substring(c.lastIndexOf(".") + 1)); + jbo.put("package", packageName); + jbo.put("classLabel", classLabel); + jbo.put("jboWhere", jboWhere); + ((List>) map.get("children")).add(jbo); + flag = true; + break; + } + } + if (!flag) { + Map map = new ConcurrentHashMap<>(); + map.put("label", packageName); + List> jbos = getArrayList(); + Map jbo = new ConcurrentHashMap<>(); + jbo.put("label", c.substring(c.lastIndexOf(".") + 1)); + jbo.put("package", packageName); + jbo.put("classLabel", classLabel); + jbo.put("jboWhere", jboWhere); + jbos.add(jbo); + map.put("children", jbos); + maps.add(map); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + }); + + return JSON.toJSONString(maps); + } + + public static String getSqlWhereByDataElement(String[] keys) { + if (keys == null || keys.length == 0) { + return ""; + } + StringBuffer sql = new StringBuffer(); + Arrays.stream(keys).forEach(key -> { + if (sql.length() > 0) { + sql.append(" AND "); + } + sql.append(key).append("=:").append(key); + }); + return sql.toString(); + } + + public static XMLInputFactory getXmlInputFactory() { + return new XMLInputFactoryImpl(); + } + + public static XMLOutputFactory getXmlOutputFactory() { + return new XMLOutputFactoryImpl(); + } + + public static JSONObject toJSON(com.amarsoft.are.jbo.BizObject bo) throws Exception { + if (bo == null) { + return null; + } + + DataElement[] dataElements = bo.getAttributes(); + JSONObject jsonObject = new JSONObject(); + for (DataElement dataElement : dataElements) { + jsonObject.put(dataElement.getName(), bo.getAttribute(dataElement.getName()).getString().replaceAll("\"", "\\\\\"").replaceAll("'", "\\\\'").replaceAll("<", "@^@").replaceAll(">", "@v@").replaceAll("\\+", "@*@")); + } + return jsonObject; + } + + public static JSONObject bizObjectToJSON(BizObject bo) throws Exception { + if (bo == null) { + return null; + } + + List dataObjects = bo.getDatas(); + JSONObject jsonObject = new JSONObject(); + for (DataObject dataObject : dataObjects) { + jsonObject.put(dataObject.getColumnName(), dataObject.getColumnValue()); + } + return jsonObject; + } + + public static String toJSONString(com.amarsoft.are.jbo.BizObject bo) throws Exception { + return toJSON(bo).toJSONString(); + } + + public static String toJSONArrayString(List bos) throws Exception { + JSONArray jsonArray = new JSONArray(); + for (com.amarsoft.are.jbo.BizObject bo : bos) { + jsonArray.add(toJSON(bo)); + } + return jsonArray.toJSONString(); + } + + public static String bizObject2JSONArrayString(List bos) throws Exception { + JSONArray jsonArray = new JSONArray(); + for (BizObject bo : bos) { + jsonArray.add(bizObjectToJSON(bo)); + } + return jsonArray.toJSONString(); + } + + public static String toString(Object object) throws Exception { + if (object instanceof StateBizObject || object instanceof com.amarsoft.are.jbo.BizObject) { + return toString((com.amarsoft.are.jbo.BizObject) object); + } else { + return toArrayString((List) object); + } + } + + public static String toString(com.amarsoft.are.jbo.BizObject bizObject) throws Exception { + if (bizObject == null) { + return ""; + } + + StringBuffer stringBuffer = new StringBuffer("{"); + + for (DataElement dataElement : bizObject.getAttributes()) { + if (stringBuffer.length() > 1) { + stringBuffer.append(", "); + } + stringBuffer.append(dataElement.getName()).append(":").append(bizObject.getAttribute(dataElement.getName()).toString()); + } + + stringBuffer.append("}"); + return stringBuffer.toString(); + } + + public static String toArrayString(List bizObjects) throws Exception { + if (bizObjects == null) { + return ""; + } + StringBuffer stringBuffer = new StringBuffer("["); + for (int i = 0; i < bizObjects.size(); i++) { + if (i > 0) { + stringBuffer.append(", "); + } + com.amarsoft.are.jbo.BizObject bizObject = bizObjects.get(i); + stringBuffer.append("{"); + for (int j = 0; j < bizObject.getAttributes().length; j++) { + DataElement dataElement = bizObject.getAttributes()[j]; + if (j > 1) { + stringBuffer.append(", "); + } + stringBuffer.append(dataElement.getName()).append(":").append(bizObject.getAttribute(dataElement.getName()).toString()); + } + + stringBuffer.append("}"); + } + stringBuffer.append("]"); + + return stringBuffer.toString(); + } + + public static String getString(Object obj) { + if (obj == null) { + return ""; + } + + return String.valueOf(obj); + } + + public static String null2String(String str, String toString) { + return StringUtils.isEmpty(str) ? toString : str; + } + + public static String caseWhen(String caseStr, String... whenThen) { + caseStr = getString(caseStr).trim(); + if (whenThen == null || whenThen.length % 2 != 0) return caseStr; + for (int i = 0; i < whenThen.length; i++) { + if (caseStr.equals(whenThen[i])) { + return whenThen[i + 1]; + } + } + return caseStr; + } + + public static Object getObject(byte[] bytes) throws Exception { + if (bytes == null) { + return ""; + } + + ByteArrayInputStream bytesIn = null; + ObjectInputStream objectInputStream = null; + Object obj; + + try { + bytesIn = new ByteArrayInputStream(bytes); + objectInputStream = new ObjectInputStream(bytesIn); + obj = objectInputStream.readObject(); + } catch (Exception e) { + throw e; + } finally { + if (objectInputStream != null) objectInputStream.close(); + if (bytesIn != null) bytesIn.close(); + } + + return obj; + } + + public static String getObjectType(Object obj) { + if (obj == null) { + return "serializable"; + } + + return obj.getClass().isPrimitive() ? obj.getClass().getName() : "String".equals(obj.getClass().getSimpleName()) ? "String" : "serializable"; + } + + public static String getValueString(Object value) { + if (value == null || "".equals(value)) { + return null; + } + + return "'" + String.valueOf(value) + .replaceAll("'", "''") + .replaceAll("\\$", "\\\\\\$") + "'"; + } + + public static Integer getInteger(Object value) { + if (value == null || "".equals(value)) { + return null; + } + + return Integer.parseInt(value.toString()); + } + + public static Map jsonToMap(JSONObject jsonObject) { + Map result = new ConcurrentHashMap<>(); + if (jsonObject == null) { + return result; + } + + + jsonObject.entrySet().forEach(stringObjectEntry -> { + result.put(stringObjectEntry.getKey(), getString(stringObjectEntry.getValue())); + }); + + return result; + } + + public static Map convertMap(Map map) { + Map result = new ConcurrentHashMap<>(); + if (map == null) { + return result; + } + + map.forEach((k, v) -> result.put(k, getString(v))); + return result; + } + + public static void saveOrUpdateFlowTaskVariables(String flowunid, String taskId, Map flowVariables) throws Exception { + saveOrUpdateFlowTaskVariables(null, flowunid, taskId, flowVariables, "save"); + } + + public static void saveOrUpdateFlowTaskVariables(String flowunid, String taskId, Map flowVariables, String type) throws Exception { + saveOrUpdateFlowTaskVariables(null, flowunid, taskId, flowVariables, type); + } + + public static void saveOrUpdateFlowTaskVariables(JBOTransaction tx, String flowunid, String taskId, Map flowVariables, String type) throws Exception { + saveOrUpdateFlowTaskVariables(tx, flowunid, taskId, flowVariables, type, null); + } + + public static void saveOrUpdateFlowTaskVariables(JBOTransaction tx, String flowunid, String taskId, Map flowVariables, String type, String name) throws Exception { + if (flowVariables == null || flowunid == null || "".equals(flowunid)) { + return; + } + + ConnUtil connUtil = new ConnUtil(tx); + tx = connUtil.getJboTransaction(); + + try { + + Map oldFlowVariables = null; + if (StringUtils.isNotEmpty(name)) { + oldFlowVariables = flowVariables("FLOW_VARINST", tx, flowunid, taskId, name); + } else { + oldFlowVariables = flowVariables(tx, flowunid); + } + + if (flowVariables.isEmpty()) { + flowVariables = oldFlowVariables; + } + + saveOrUpdateFlowTaskVariables(tx, flowunid, taskId, flowVariables, oldFlowVariables); + + Map fromParams = new ConcurrentHashMap<>(); + fromParams.put("FLOW_UNID_", flowunid); + fromParams.put("TASK_ID_", taskId); + + if ("join".equals(type)) { // 处理并行分支参数 + executeUpdate("insert into flow_varinst( id_, flow_unid_, task_id_, name_, var_type_, value_, bytes_, inputtime_, updatetime_, json_value_ ) " + + "select sys_guid(), a.flow_unid_, c.serialno, a.name_, a.var_type_, a.value_, a.bytes_, a.inputtime_, a.updatetime_, a.json_value_ from flow_varinst_his a " + + "left join flow_task b on a.task_id_ = b.serialno left join flow_task c on c.relativeserialno = b.relativeserialno where c.serialno = ? and not exists ( select 1 from flow_varinst where a.flow_unid_ = flow_unid_ and a.name_ = name_ )", tx, taskId); + executeUpdate("insert into flow_varinst_diff( id_, flow_unid_, task_id_, name_, var_type_, value_old_, value_new_, bytes_old_, bytes_new_, diff_value_, inputtime_, updatetime_ ) " + + "select sys_guid(), a.flow_unid_, c.serialno, a.name_, a.var_type_, a.value_old_, a.value_new_, a.bytes_old_, a.bytes_new_, a.diff_value_, a.inputtime_, a.updatetime_ from flow_varinst_diff_his a " + + "left join flow_task b on a.task_id_ = b.serialno left join flow_task c on c.relativeserialno = b.relativeserialno where c.serialno = ? and not exists ( select 1 from flow_varinst_diff where a.flow_unid_ = flow_unid_ and a.name_ = name_ )", tx, taskId); + type = "task"; + } + + if (!"save".equals(type)) { + copy("jbo.sys.FLOW_VARINST", "jbo.sys.FLOW_VARINST_HIS", fromParams, null, (Map) null, null, null, true, tx); + copy("jbo.sys.FLOW_VARINST_DIFF", "jbo.sys.FLOW_VARINST_DIFF_HIS", fromParams, null, (Map) null, null, null, true, tx); + } + + if ("task".equals(type)) { + List> taskIds = DataUtil.query("SELECT SERIALNO AS TASK_ID_ FROM FLOW_TASK WHERE OBJECTNO = ? AND RELATIVESERIALNO = ?", tx, flowunid, taskId); + copy("jbo.sys.FLOW_VARINST", "jbo.sys.FLOW_VARINST", fromParams, null, taskIds, null, null, true, tx); + copy("jbo.sys.FLOW_VARINST_DIFF", "jbo.sys.FLOW_VARINST_DIFF", fromParams, null, taskIds, null, null, true, tx); + } + + if (!"save".equals(type)) { + if ("end".equals(type)) { + DataUtil.executeUpdate("DELETE FROM FLOW_VARINST WHERE FLOW_UNID_ = ?", tx, flowunid); + DataUtil.executeUpdate("DELETE FROM FLOW_VARINST_DIFF WHERE FLOW_UNID_ = ?", tx, flowunid); + } else { + DataUtil.executeUpdate("DELETE FROM FLOW_VARINST WHERE FLOW_UNID_ = ? AND TASK_ID_ = ?", tx, flowunid, taskId); + DataUtil.executeUpdate("DELETE FROM FLOW_VARINST_DIFF WHERE FLOW_UNID_ = ? AND TASK_ID_ = ?", tx, flowunid, taskId); + } + } + + connUtil.commit(); + } catch (Exception e) { + connUtil.rollback(); + throw e; + } + } + + public static Map getBizletAttrs(Bizlet bizlet) throws Exception { + Map result = new ConcurrentHashMap<>(); + if (bizlet == null) { + return result; + } + + ASValuePool attributes = bizlet.getAttributes(); + for (Object key : attributes.getKeys()) { + Object value = attributes.getAttribute(key.toString()) == null ? "" : attributes.getAttribute(key.toString()); + result.put(key.toString(), value); + } + return result; + } + + public static void saveOrUpdateFlowTaskVariables(JBOTransaction tx, String flowunid, String taskId, Map newMap, Map oldMap) throws Exception { + List> flowParamsInstances = getArrayList(); + List> flowParamsSerializableInstances = getArrayList(); + List> flowParamsUpdateInstances = getArrayList(); + List> flowParamsSerializableUpdateInstances = getArrayList(); + List> flowParamsDiffInstances = getArrayList(); + List> flowParamsSerializableDiffInstances = getArrayList(); + List> flowParamsDiffUpdateInstances = getArrayList(); + List> flowParamsSerializableDiffUpdateInstances = getArrayList(); + String now = DateUtil.getTodayNow(); + String type; + + Map map; + boolean flag = false; + if (oldMap != null && oldMap.size() > newMap.size()) { + flag = true; + map = oldMap; + } else { + map = newMap; + } + + if (oldMap != null && newMap != null) { + for (Map.Entry flowVariable : newMap.entrySet()) { + String key = flowVariable.getKey(); + if (key.endsWith("@temp")) { + continue; + } + if (!oldMap.containsKey(key)) { + Object value = flowVariable.getValue(); + String varType = getObjectType(value); + calculateTaskVariableDifferences(flowParamsInstances, + flowParamsSerializableInstances, + flowParamsUpdateInstances, + flowParamsSerializableUpdateInstances, + flowParamsDiffInstances, + flowParamsSerializableDiffInstances, + flowParamsDiffUpdateInstances, + flowParamsSerializableDiffUpdateInstances, + value, null, varType, "insert", flowunid, taskId, key, now); + } + } + } + + for (Map.Entry flowVariable : map.entrySet()) { + Object value; + Object oldValue; + String key = flowVariable.getKey(); + if (key.endsWith("@temp")) { + continue; + } + if (flag) { + value = newMap.get(key) == null ? "" : newMap.get(key); + oldValue = flowVariable.getValue(); + } else { + value = flowVariable.getValue(); + if (oldMap == null) { + continue; + } else { + if (!oldMap.containsKey(key)) { + continue; + } + oldValue = oldMap.get(key); + } + + } + String varType = getObjectType(value); + type = oldValue == null ? "insert" : "update"; + calculateTaskVariableDifferences(flowParamsInstances, + flowParamsSerializableInstances, + flowParamsUpdateInstances, + flowParamsSerializableUpdateInstances, + flowParamsDiffInstances, + flowParamsSerializableDiffInstances, + flowParamsDiffUpdateInstances, + flowParamsSerializableDiffUpdateInstances, + value, oldValue, varType, type, flowunid, taskId, key, now); + } + + execute(tx, flowParamsInstances, flowParamsSerializableInstances, flowParamsUpdateInstances, flowParamsSerializableUpdateInstances, flowParamsDiffInstances, flowParamsSerializableDiffInstances, flowParamsDiffUpdateInstances, flowParamsSerializableDiffUpdateInstances); + + } + + public static void execute(JBOTransaction tx, + List flowParamsInstances, + List flowParamsSerializableInstances, + List flowParamsUpdateInstances, + List flowParamsSerializableUpdateInstances, + List flowParamsDiffInstances, + List flowParamsSerializableDiffInstances, + List flowParamsDiffUpdateInstances, + List flowParamsSerializableDiffUpdateInstances) throws Exception { + if (flowParamsInstances.size() > 0) { + insert("FLOW_VARINST", flowParamsInstances, tx); + } + if (flowParamsSerializableInstances.size() > 0) { + insert("FLOW_VARINST", flowParamsSerializableInstances, tx); + } + if (flowParamsDiffInstances.size() > 0) { + insert("FLOW_VARINST_DIFF", flowParamsDiffInstances, tx); + } + if (flowParamsSerializableUpdateInstances.size() > 0) { + insert("FLOW_VARINST_DIFF", flowParamsSerializableUpdateInstances, tx); + } + if (flowParamsUpdateInstances.size() > 0) { + update("FLOW_VARINST", flowParamsUpdateInstances, tx, "FLOW_UNID_", "TASK_ID_", "NAME_"); + } + if (flowParamsSerializableDiffInstances.size() > 0) { + update("FLOW_VARINST", flowParamsSerializableDiffInstances, tx, "FLOW_UNID_", "TASK_ID_", "NAME_"); + } + if (flowParamsDiffUpdateInstances.size() > 0) { + update("FLOW_VARINST_DIFF", flowParamsDiffUpdateInstances, tx, "FLOW_UNID_", "TASK_ID_", "NAME_"); + } + if (flowParamsSerializableDiffUpdateInstances.size() > 0) { + update("FLOW_VARINST_DIFF", flowParamsSerializableDiffUpdateInstances, tx, "FLOW_UNID_", "TASK_ID_", "NAME_"); + } + } + + public static void calculateTaskVariableDifferences(List> flowParamsInstances, + List> flowParamsSerializableInstances, + List> flowParamsUpdateInstances, + List> flowParamsSerializableUpdateInstances, + List> flowParamsDiffInstances, + List> flowParamsSerializableDiffInstances, + List> flowParamsDiffUpdateInstances, + List> flowParamsSerializableDiffUpdateInstances, + Object value, + Object oldValue, + String varType, + String type, + String flowunid, + String taskId, + String key, + String now) { + + List dataObjects = getArrayList(); + List dataObjectUpdates = getArrayList(); + List dataObjectDiffs = getArrayList(); + List dataObjectUpdateDiffs = getArrayList(); + if ("insert".equals(type)) { + dataObjects.add(new DataObject("ID_", "string", UUIDUtil.getUUID())); + dataObjectDiffs.add(new DataObject("ID_", "string", UUIDUtil.getUUID())); + dataObjects.add(new DataObject("INPUTTIME_", "string", now)); + dataObjectDiffs.add(new DataObject("INPUTTIME_", "string", now)); + dataObjects.add(new DataObject("FLOW_UNID_", "string", flowunid)); + dataObjectDiffs.add(new DataObject("TASK_ID_", "string", taskId)); + dataObjects.add(new DataObject("TASK_ID_", "string", taskId)); + dataObjectDiffs.add(new DataObject("FLOW_UNID_", "string", flowunid)); + dataObjects.add(new DataObject("NAME_", "string", key)); + dataObjectDiffs.add(new DataObject("NAME_", "string", key)); + dataObjects.add(new DataObject("VAR_TYPE_", "string", varType)); + dataObjectDiffs.add(new DataObject("VAR_TYPE_", "string", varType)); + } else { + dataObjectUpdates.add(new DataObject("UPDATETIME_", "string", now)); + dataObjectUpdateDiffs.add(new DataObject("UPDATETIME_", "string", now)); + dataObjectUpdates.add(new DataObject("VAR_TYPE_", "string", varType)); + dataObjectUpdateDiffs.add(new DataObject("VAR_TYPE_", "string", varType)); + + dataObjectUpdates.add(new DataObject("FLOW_UNID_", "string", flowunid)); + dataObjectUpdates.add(new DataObject("TASK_ID_", "string", taskId)); + dataObjectUpdates.add(new DataObject("NAME_", "string", key)); + dataObjectUpdateDiffs.add(new DataObject("FLOW_UNID_", "string", flowunid)); + dataObjectUpdateDiffs.add(new DataObject("TASK_ID_", "string", taskId)); + dataObjectUpdateDiffs.add(new DataObject("NAME_", "string", key)); + } + + if (!"serializable".equals(varType)) { + if ("insert".equals(type)) { + dataObjects.add(new DataObject("VALUE_", "string", value)); + dataObjectDiffs.add(new DataObject("VALUE_OLD_", "string", value)); + } else { + dataObjectUpdates.add(new DataObject("VALUE_", "string", value)); + dataObjectUpdateDiffs.add(new DataObject("VALUE_NEW_", "string", value)); + } + } else { + if ("insert".equals(type)) { + dataObjects.add(new DataObject("BYTES_", "serializable", value)); + try { // JSON解析异常暂时忽略 + dataObjects.add(new DataObject("JSON_VALUE_", "string", toString(value))); + } catch (Exception e) { + e.printStackTrace(); + } + dataObjectDiffs.add(new DataObject("BYTES_OLD_", "serializable", value)); + } else { + dataObjectUpdates.add(new DataObject("BYTES_", "serializable", value)); + try { // JSON解析异常暂时忽略 + dataObjectUpdates.add(new DataObject("JSON_VALUE_", "string", toString(value))); + } catch (Exception e) { + e.printStackTrace(); + } + dataObjectUpdateDiffs.add(new DataObject("BYTES_NEW_", "serializable", value)); + } + } + + if ("update".equals(type)) { + dataObjectUpdateDiffs.add(new DataObject("DIFF_VALUE_", "string", computationalDifference(value, oldValue))); + } + + if (!"serializable".equals(varType)) { + if (dataObjects.size() > 0) { + flowParamsInstances.add(dataObjects); + } + if (dataObjectDiffs.size() > 0) { + flowParamsDiffInstances.add(dataObjectDiffs); + } + if (dataObjectUpdates.size() > 0) { + flowParamsUpdateInstances.add(dataObjectUpdates); + } + if (dataObjectUpdateDiffs.size() > 0) { + flowParamsDiffUpdateInstances.add(dataObjectUpdateDiffs); + } + } else { + if (dataObjects.size() > 0) { + flowParamsSerializableInstances.add(dataObjects); + } + if (dataObjectDiffs.size() > 0) { + flowParamsSerializableUpdateInstances.add(dataObjectDiffs); + } + if (dataObjectUpdates.size() > 0) { + flowParamsSerializableDiffInstances.add(dataObjectUpdates); + } + if (dataObjectUpdateDiffs.size() > 0) { + flowParamsSerializableDiffUpdateInstances.add(dataObjectUpdateDiffs); + } + } + } + + public static String getFlowDiffType(String type) { + String result = ""; + + switch (type) { + case "01": + result = TYPE01; + break; + case "02": + result = TYPE02; + break; + case "03": + result = TYPE03; + break; + case "04": + result = TYPE04; + break; + case "05": + result = TYPE05; + break; + } + + return result; + } + + public static boolean compareClassName(String name1, String name2) { + String pattern = "\\d"; + if (Pattern.matches(pattern, name1.substring(name1.length() - 1))) { + name1 = name1.substring(0, name1.lastIndexOf("X")); + } + if (Pattern.matches(pattern, name2.substring(name2.length() - 1))) { + name2 = name2.substring(0, name2.lastIndexOf("X")); + } + + return name1.equals(name2); + } + + public static void getBizObjectDiff(Object newValue, Object oldValue, StringBuffer stringBuffer) throws JBOException { + getBizObjectDiff(newValue, oldValue, null, stringBuffer); + } + + public static void getBizObjectDiff(Object newValue, Object oldValue, Integer index, StringBuffer stringBuffer) throws JBOException { + com.amarsoft.are.jbo.BizObject newBizObject = (com.amarsoft.are.jbo.BizObject) newValue; + com.amarsoft.are.jbo.BizObject oldBizObject = (com.amarsoft.are.jbo.BizObject) oldValue; + String newBean = newBizObject.getBizObjectClass().getPackageName() + "." + newBizObject.getBizObjectClass().getName(); + String oldBean = oldBizObject.getBizObjectClass().getPackageName() + "." + oldBizObject.getBizObjectClass().getName(); + + if (!compareClassName(newBean, oldBean)) { + if (index != null) { + stringBuffer.append("第").append(index + 1).append("行数据 "); + } + stringBuffer.append("原JBO类型:[ ").append(oldBean).append(" ] -> 转换为:[ ").append(newBean).append(" ]"); + return; + } + + for (DataElement dataElement : newBizObject.getAttributes()) { + String name = dataElement.getName(); + String nv = newBizObject.getAttribute(name).getString(); + String ov = oldBizObject.getAttribute(name).getString(); + if (!nv.equals(ov)) { + if (index != null) { + stringBuffer.append("第").append(index + 1).append("行数据 "); + } + stringBuffer.append("属性[ ").append(name).append(" ] 原始值:[ ").append(ov).append(" ] -> 变更后值:[ ").append(nv).append(" ]"); + stringBuffer.append("\n"); + } + } + } + + public static void getJSONObjectDiff(Object newValue, Object oldValue, StringBuffer stringBuffer) { + getJSONObjectDiff(newValue, oldValue, null, stringBuffer); + } + + public static void getJSONObjectDiff(Object newValue, Object oldValue, Integer index, StringBuffer stringBuffer) { + JSONObject newJSONObject = (JSONObject) newValue; + JSONObject oldJSONObject = (JSONObject) oldValue; + + for (Map.Entry entry : newJSONObject.entrySet()) { + String name = entry.getKey(); + Object nv = entry.getValue(); + Object ov = oldJSONObject.get(name); + + StringBuffer str = new StringBuffer(); + if (nv == ov) { + continue; + } else if (nv == null && ov != null) { + str.append("属性[ ").append(name).append(" ] 原始值:[ ").append(ov).append(" ] -> 变更后值:[ null ]"); + } else if (ov == null && nv != null) { + str.append("属性[ ").append(name).append(" ] 原始值:[ null ] -> 变更后值:[ ").append(nv).append(" ]"); + } else { + String nType = nv.getClass().getName(); + String oType = ov.getClass().getName(); + if (!compareClassName(nType, oType)) { + if ("".equals(ov)) { + str.append("属性[ ").append(name).append(" ] 原始值:[ null ] -> 变更后值:[ ").append(nv).append(" ]"); + } else { + str.append("属性[ ").append(name).append(" ] 原始值类型:[ ").append(oType).append(" ] -> 变更后值类型:[ ").append(nType).append(" ]"); + } + } else { + try { + str.append("属性[ ").append(name).append(" ]"); + if (!"java.lang.String".equals(nType)) { + str.append("变更内容如下: \n"); + } + getDiff(nv, ov, nType, str); + } catch (Exception e) { + e.printStackTrace(); + stringBuffer.append("差异计算产生异常: [ ").append(e.getMessage()).append(" ]"); + } + } + } + + if (index != null && str.length() > 0) { + stringBuffer.append("第").append(index + 1).append("行数据 "); + } + + stringBuffer.append(str).append("\n"); + } + } + + public static void getDiff(Object newValue, Object oldValue, String varType, StringBuffer stringBuffer) throws Exception { + getDiff(newValue, oldValue, varType, null, stringBuffer); + } + + public static void getDiff(Object newValue, Object oldValue, String varType, Integer index, StringBuffer stringBuffer) throws Exception { + Object o = null; + + if (newValue == null && oldValue != null) { + o = oldValue; + } else if (oldValue == null && newValue != null) { + o = newValue; + } + + if (o != null) { + if (index != null) { + stringBuffer.append("第").append(index + 1).append("行数据 "); + } + String type = o.getClass().getName(); + + if (newValue == null) { + stringBuffer.append("原始数据为:[ "); + } else { + stringBuffer.append("新数据数据为:[ "); + } + + switch (type) { + case "com.amarsoft.are.jbo.BizObject": + case "com.amarsoft.are.jbo.impl.StateBizObject": + stringBuffer.append(toString((com.amarsoft.are.jbo.BizObject) o)).append(" ]\n"); + break; + default: + stringBuffer.append(o.toString()).append(" ]\n"); + } + return; + } + + switch (varType) { + // 字符串差异 + case "java.lang.String": + stringBuffer.append("原始值:[ ").append(oldValue.toString()).append(" ] -> 变更后值:[ ").append(newValue.toString()).append(" ]"); + break; + // BizObject差异 + case "com.amarsoft.are.jbo.BizObject": + case "com.amarsoft.are.jbo.impl.StateBizObject": + getBizObjectDiff(newValue, oldValue, index, stringBuffer); + break; + // com.alibaba.fastjson.JSONObject差异 + case "com.alibaba.fastjson.JSONObject": + getJSONObjectDiff(newValue, oldValue, index, stringBuffer); + break; + // 集合判断 + case "java.util.ArrayList": + case "java.util.Collections$SynchronizedRandomAccessList": + List nList = (List) newValue; + List oList = (List) oldValue; + int i = 0; + if (nList.size() > oList.size()) { + for (Object target : nList) { + Object obj; + if (i >= oList.size()) { + obj = null; + } else { + obj = oList.get(i); + } + String type = target.getClass().getName(); + getDiff(target, obj, type, i++, stringBuffer); + } + } else { + for (Object target : oList) { + Object obj; + if (i >= nList.size()) { + obj = null; + } else { + obj = nList.get(i); + } + String type = target.getClass().getName(); + getDiff(obj, target, type, i++, stringBuffer); + } + } + break; + default: + stringBuffer.append(getFlowDiffType("05")); + } + } + + /** + * 简易差异算法 + */ + public static String computationalDifference(Object newValue, Object oldValue) { + StringBuffer stringBuffer = new StringBuffer(); + + if (oldValue == null && newValue != null) { + stringBuffer.append(getFlowDiffType("01")); + } else if (newValue == null && oldValue != null) { + stringBuffer.append(getFlowDiffType("02")); + } else if (newValue == oldValue || getString(newValue).equals(getString(oldValue))) { + stringBuffer.append(getFlowDiffType("03")); + } else { + String nVarType = newValue.getClass().getName(); + String oVarType = oldValue.getClass().getName(); + if (!nVarType.equals(oVarType)) { + stringBuffer.append(getFlowDiffType("04")); + return stringBuffer.toString(); + } + + try { + getDiff(newValue, oldValue, nVarType, stringBuffer); + } catch (Exception e) { + e.printStackTrace(); + stringBuffer.append("差异计算产生异常: [ ").append(e.getMessage()).append(" ]"); + } + } + + if (stringBuffer.length() == 0) { + stringBuffer.append(getFlowDiffType("03")); + } + + return stringBuffer.toString(); + } + + public static DataElement[] createJBOAttributes(String[] attributes, BizObjectManager bizObjectManager) throws Exception { + BizObjectClass managedClass = bizObjectManager.getManagedClass(); + DataElement[] attribute = new DataElement[attributes.length]; + List result = getArrayList(); + + for (int i = 0; i < attributes.length; ++i) { + + if (managedClass.indexOfAttribute(attributes[i]) == -1) { + attribute[i] = new DataElement(attributes[i]); + result.add(attribute[i]); + } + } + + return result.toArray(new DataElement[0]); + } + + public static com.amarsoft.are.jbo.BizObject getBizObject(String templateNo) throws Exception { + return getBizObject(templateNo, (BizObjectManager) null); + } + + public static com.amarsoft.are.jbo.BizObject getBizObject(String templateNo, BizObjectManager bizObjectManager) throws Exception { + ASObjectModel asObjectModel = new ASObjectModel(templateNo); + Vector columns = asObjectModel.Columns; + List attributes = getArrayList(); + + for (ASColumn column : columns) { + if (!column.getAttribute("ISINUSE").equals("0")) { + attributes.add(column.getAttribute("COLNAME")); + } + } + + bizObjectManager = bizObjectManager == null ? JBOFactory.getBizObjectManager(asObjectModel.getJboClass()) : bizObjectManager; + return bizObjectManager.newObject(createJBOAttributes(attributes.toArray(new String[0]), bizObjectManager)); + } + + public static Object getBizObject(String templateNo, Bizlet bizlet, String type) throws Exception { + ASObjectModel asObjectModel = new ASObjectModel(templateNo); + Page page = new Page(null); + ASUser user = ASUser.getUser(bizlet.getAttribute("CurUserID").toString(), null); + page.setUser(user); + asObjectModel.setCurPage(page); + asObjectModel.init(); + + BizObjectManager bizObjectManager = JBOFactory.getBizObjectManager(asObjectModel.getJboClass()); + String where = wrapSharpChar(asObjectModel.getJboWhere()); + String sql = wrapSharpChar(asObjectModel.getJboSql()); + List params = getArrayList(); + getContents(params, where, "\\:[a-zA-Z0-9_]+"); + BizObjectQuery boq = bizObjectManager.createQuery(sql); + ASValuePool as = bizlet.getAttributes(); + for (String p : params) { + p = p.replaceAll(":", ""); + for (Object obj : as.getKeys()) { + String key = (String) obj; + if (p.equalsIgnoreCase(key)) { + boq.setParameter(p, bizlet.getAttribute(key).toString()); + break; + } + } + } + if ("list".equals(type)) { + return boq.getResultList(false); + } else { + return boq.getSingleResult(false); + } + } + + public static String wrapSharpChar(String where) { + List strs = getArrayList(); + getContents(strs, where, "'#[a-zA-Z0-9_%]+?'"); + + for (int i = 0; i < strs.size(); i++) { + String value = strs.get(i); + if (value.endsWith("%'")) { + value = value.substring(2, value.length() - 2); + where = where.replaceAll("'#" + value + "%'", ":" + value + "%"); + } else { + value = value.substring(2, value.length() - 1); + where = where.replaceAll("'#" + value + "'", ":" + value); + } + } + + return where; + } + + public static List getContents(List strs, String content, String pattern) { + String str; + + Pattern p = Pattern.compile(pattern); + Matcher m = p.matcher(content); + + while (m.find()) { + for (int i = 0; i <= m.groupCount(); i++) { + str = m.group(i); + strs.add(str); + } + } + + return strs; + } + + public static com.amarsoft.are.jbo.BizObject getTemplateJBO(String templateNo) throws Exception { + return getTemplateJBO(templateNo, null); + } + + public static com.amarsoft.are.jbo.BizObject getTemplateJBO(String templateNo, Bizlet bizlet) throws Exception { + return getTemplateJBO(templateNo, bizlet, null); + } + + /** + * 根据流程变量,初始化模板 + * + * @param bizlet 模板对应JBO + * @param templateNo 模板编号 + * @param excludeAttribute 流程变量里存在,但不需要加入模板的属性 + * @return + * @throws Exception + */ + public static com.amarsoft.are.jbo.BizObject getTemplateJBO(String templateNo, Bizlet bizlet, String... excludeAttribute) throws Exception { + com.amarsoft.are.jbo.BizObject bizObject = getBizObject(templateNo); + + if (bizlet == null) { + return bizObject; + } + + ASValuePool asValuePool = bizlet.getAttributes(); + + for (Object key : asValuePool.getKeys()) { + if (excludeAttribute != null && Arrays.stream(excludeAttribute).anyMatch(str -> str.equalsIgnoreCase(key.toString()))) continue; + if (bizObject.indexOfAttribute(key.toString()) == -1) continue; + bizObject.setAttributeValue(key.toString(), asValuePool.getAttribute(key.toString())); + } + + return bizObject; + } + + public static List getTemplateJBOs(String templateNo, List bizObjects, Bizlet bizlet, String... excludeAttribute) throws Exception { + if (bizlet == null) { + return bizObjects; + } + + return convertJBO2Template(templateNo, bizObjects, bizlet, excludeAttribute); + } + + public static List convertListToJBO2(String jboClassName, List> datas) throws Exception { + return convertListToJBO(null, jboClassName, datas); + } + + public static List convertListToJBO(String templateNo, List> datas) throws Exception { + return convertListToJBO(templateNo, null, datas); + } + + public static List convertListToJBO(String templateNo, String jboClassName, List> datas) throws Exception { + if (datas == null || datas.isEmpty()) { + List a = DataUtil.getArrayList(); + return a; + } + List bos = getArrayList(); + com.amarsoft.are.jbo.BizObject bizObject; + if (StringUtils.isNotEmpty(templateNo)) { + bizObject = getBizObject(templateNo); + } else { + bizObject = JBOFactory.getBizObjectManager(jboClassName).newObject(); + } + for (Map data : datas) { + com.amarsoft.are.jbo.BizObject bo = (com.amarsoft.are.jbo.BizObject) bizObject.clone(); + for (Map.Entry entry : data.entrySet()) { + boolean flag = false; + for (DataElement attribute : bizObject.getAttributes()) { + if (entry.getKey().equals(attribute.getName())) { + flag = true; + break; + } + } + if (flag) { + bo.setAttributeValue(entry.getKey(), entry.getValue()); + } + } + bos.add(bo); + } + + return bos; + } + + public static com.amarsoft.are.jbo.BizObject convertMapToJBO(String templateNo, List> datas) throws Exception { + if (datas == null || datas.isEmpty()) { + return null; + } + com.amarsoft.are.jbo.BizObject bizObject = getBizObject(templateNo); + Map data = datas.get(0); + for (Map.Entry entry : data.entrySet()) { + bizObject.setAttributeValue(entry.getKey(), entry.getValue()); + } + + return bizObject; + } + + /** + * 将JBO对象转换为模板对象 + * + * @param templateNo 模板名 + * @param bizObjects JBO数据 + */ + public static List convertJBO2Template(String templateNo, List bizObjects, Bizlet bizlet, String... excludeAttribute) throws Exception { + if (bizObjects == null || bizObjects.size() == 0) { + return null; + } + + List bos = getArrayList(); + com.amarsoft.are.jbo.BizObject bo = getBizObject(templateNo); + + for (com.amarsoft.are.jbo.BizObject bizObject : bizObjects) { + com.amarsoft.are.jbo.BizObject newBo = (com.amarsoft.are.jbo.BizObject) bo.clone(); + if (bizlet != null) { + ASValuePool asValuePool = bizlet.getAttributes(); + for (Object key : asValuePool.getKeys()) { + if (excludeAttribute != null && Arrays.stream(excludeAttribute).anyMatch(str -> str.equalsIgnoreCase(key.toString()))) continue; + if (newBo.indexOfAttribute(key.toString()) == -1) continue; + newBo.setAttributeValue(key.toString(), asValuePool.getAttribute(key.toString())); + } + } + + for (DataElement dataElement : bizObject.getAttributes()) { + newBo.setAttributeValue(dataElement.getName(), bizObject.getAttribute(dataElement.getName())); + } + + bos.add(newBo); + } + + return bos; + } + + public static com.amarsoft.are.jbo.BizObject convertBizObjectToBizObject(BizObject bo) throws Exception { + com.amarsoft.are.jbo.BizObject bizObject = JBOFactory.getBizObjectManager(bo.getClassName()).newObject(); + for (DataObject dataObject : bo.getDatas()) { + bizObject.setAttributeValue(dataObject.getColumnName(), dataObject.getColumnValue()); + } + return bizObject; + } + + public static com.amarsoft.are.jbo.BizObject convertJSON2BizObjects(String templateNo, BizObjectManager bizObjectManager, JSONObject jsonObject) throws Exception { + if (templateNo == null || "".equals(templateNo) || jsonObject == null) { + return null; + } + + com.amarsoft.are.jbo.BizObject bizObject = getBizObject(templateNo, bizObjectManager); + + for (Map.Entry entry : jsonObject.entrySet()) { + try { + bizObject.setAttributeValue(entry.getKey(), entry.getValue()); + } catch (Exception e) { + } + } + + return bizObject; + } + + public static List setPageSize(List bos, int maxRow, int firstRow) { + if (bos.size() == 0) { + return bos; + } + List newBos = getArrayList(); + for (int i = firstRow; i < maxRow; i++) { + newBos.add(bos.get(i)); + } + return newBos; + } + + public static List convertJSON2BizObjects(String templateNo, BizObjectManager bizObjectManager, JSONArray jsonArray) throws Exception { + if (templateNo == null || "".equals(templateNo) || jsonArray == null) { + return null; + } + + List bizObjects = getArrayList(); + com.amarsoft.are.jbo.BizObject bizObjectO = getBizObject(templateNo, bizObjectManager); + + for (int i = 0; i < jsonArray.size(); i++) { + JSONObject jsonObject = jsonArray.getJSONObject(i); + if (jsonObject == null) { + continue; + } + com.amarsoft.are.jbo.BizObject bizObject = (com.amarsoft.are.jbo.BizObject) bizObjectO.clone(); + + for (Map.Entry entry : jsonObject.entrySet()) { + bizObject.setAttributeValue(entry.getKey(), entry.getValue()); + } + + bizObjects.add(bizObject); + } + + return bizObjects; + } + + public static String convertMapToParams(LinkedHashMap map) { + if (map == null || map.isEmpty()) { + return ""; + } + StringBuffer stringBuffer = new StringBuffer(); + for (Map.Entry entry : map.entrySet()) { + if (stringBuffer.length() > 0) { + stringBuffer.append("△"); + } + stringBuffer.append(entry.getKey()).append("□").append(entry.getValue()); + } + return stringBuffer.toString(); + } + + public static LinkedHashMap convertParamsToMap(String params) { + if (StringUtils.isEmpty(params)) { + return null; + } + String[] p = params.split("△"); + LinkedHashMap map = new LinkedHashMap<>(p.length, 0.75f, true); + for (String s : p) { + String[] v = s.split("□"); + if (v.length == 1) { + map.put(v[0], ""); + } else { + map.put(v[0], v[1]); + } + } + return map; + } + + /** + * 流程初始化方法设置流程详情页面模板数据 + * + * @param templateNo + * @param bizlet + * @param excludeAttribute + * @throws Exception + */ + public static void setTemplateDataToFlowVariables(String templateNo, Bizlet bizlet, String... excludeAttribute) throws Exception { + setTemplateDataToFlowVariables(templateNo, null, bizlet, excludeAttribute); + } + + public static void setTemplateDataToFlowVariables(String templateNo, com.amarsoft.are.jbo.BizObject data, Bizlet bizlet, String... excludeAttribute) throws Exception { + if (data == null) { + bizlet.setAttribute(templateNo, getTemplateJBO(templateNo, bizlet, excludeAttribute)); + } else { + bizlet.setAttribute(templateNo, data); + } + } + + public static void setTemplateData(Bizlet bizlet, String templateNo, String sql, JBOTransaction tx, String... params) throws Exception { + bizlet.setAttribute(templateNo, convertMapToJBO(templateNo, DataUtil.query(sql, tx, params))); + } + + public static void setTemplateData(String templateNo, Bizlet bizlet) throws Exception { + setTemplateData(templateNo, bizlet, null); + } + + public static void setListTemplateData(Bizlet bizlet, String templateNo, String sql, JBOTransaction tx, String... params) throws Exception { + bizlet.setAttribute(templateNo, convertListToJBO(templateNo, DataUtil.query(sql, tx, params))); + } + + public static void setListTemplateData(String templateNo, Bizlet bizlet) throws Exception { + setListTemplateData(templateNo, bizlet, null); + } + + public static void setTemplateData(String templateNo, Bizlet bizlet, String params) throws Exception { + if (StringUtils.isNotEmpty(params)) { + // TODO + } else { + bizlet.setAttribute(templateNo, getBizObject(templateNo, bizlet, "info")); + } + } + + public static void setListTemplateData(String templateNo, Bizlet bizlet, String params) throws Exception { + if (StringUtils.isNotEmpty(params)) { + // TODO + } else { + bizlet.setAttribute(templateNo, getBizObject(templateNo, bizlet, "list")); + } + } + + /** + * 流程初始化方法设置流程列表页面模板数据 + * + * @param templateNo + * @param bizlet + * @param excludeAttribute + * @throws Exception + */ + public static void setListTemplateDataToFlowVariables(String templateNo, Bizlet bizlet, String... excludeAttribute) throws Exception { + setListTemplateDataToFlowVariables(templateNo, null, bizlet, excludeAttribute); + } + + public static void setListTemplateDataToFlowVariables(String templateNo, List datas, Bizlet bizlet, String... excludeAttribute) throws Exception { + if (datas == null) { + bizlet.setAttribute(templateNo, getTemplateJBOs(templateNo, null, bizlet, excludeAttribute)); + } else { + bizlet.setAttribute(templateNo, datas); + } + } + + public static String toString(Map map) throws Exception { + if (map == null) { + return ""; + } + return JSON.toJSONString(convertToMapString(map)); + } + + public static String toJSONString(Map map) throws Exception { + if (map == null || map.isEmpty()) { + return "{}"; + } + StringBuffer stringBuffer = new StringBuffer("{"); + for (Map.Entry entry : map.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + if (stringBuffer.length() > 1) { + stringBuffer.append(", "); + } + stringBuffer.append("\"").append(key).append("\"").append(":"); + if (value == null) { + continue; + } else { + String type = value.getClass().getSimpleName(); + if ("StateBizObject".equals(type) || "BizObject".equals(type)) { + stringBuffer.append(toJSONString((com.amarsoft.are.jbo.BizObject) value)); + } else if ("ArrayList".equals(type) || "SynchronizedRandomAccessList".equals(type)) { + List list = (List) value; + if (list.size() > 0) { + Object obj = list.get(0); + if ("StateBizObject".equals(obj.getClass().getSimpleName()) || "BizObject".equals(obj.getClass().getSimpleName())) { + stringBuffer.append(toJSONArrayString(list)); + } else { + stringBuffer.append(JSON.toJSONString(list)); + } + } else { + stringBuffer.append("[]"); + } + } else if ("String".equals(type)) { + String v = value.toString(); + stringBuffer.append("\"").append(v.replaceAll("\"", "\\\\\"").replaceAll("'", "\\\\'").replaceAll("\n", "
").replaceAll("<", "@^@").replaceAll(">", "@v@").replaceAll("\\+", "@*@")).append("\""); + } else { + stringBuffer.append(JSON.toJSONString(value)); + } + } + } + stringBuffer.append("}"); + + return stringBuffer.toString(); + } + + public static Map convertToMapString(Map map) throws Exception { + Map result = new ConcurrentHashMap<>(); + if (map == null) { + return result; + } + for (Map.Entry entry : map.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + if (value == null) { + continue; + } else { + String type = value.getClass().getSimpleName(); + if ("StateBizObject".equals(type) || "BizObject".equals(type)) { + result.put(key, toJSONString((com.amarsoft.are.jbo.BizObject) value)); + } else if ("java.util.ArrayList".equals(type) || "java.util.Collections$SynchronizedRandomAccessList".equals(type) || "SynchronizedRandomAccessList".equals(type)) { + List list = (List) value; + if (list.size() > 0) { + Object obj = list.get(0); + if ("StateBizObject".equals(obj.getClass().getSimpleName()) || "BizObject".equals(obj.getClass().getSimpleName())) { + result.put(key, toJSONArrayString(list)); + } else { + result.put(key, JSON.toJSONString(list)); + } + } else { + result.put(key, "[]"); + } + } else if ("String".equals(type)) { + result.put(key, value.toString()); + } else { + result.put(key, JSON.toJSONString(value)); + } + } + } + + return result; + } + + public static Map convertJSONToMap(JSONObject jsonObject) { + Map map = new ConcurrentHashMap<>(); + jsonObject.keySet().forEach(key -> { + Object value = jsonObject.get(key); + value = value == null ? "" : value; + CatalogModel catalogModel = AWEDataWindowCache.getInstance().getCatalogModel(key.split("~")[0]); + if (catalogModel != null) { + BizObjectManager bizObjectManager; + try { + bizObjectManager = JBOFactory.getBizObjectManager(catalogModel.getJboClass()); + if (value instanceof JSONObject) { + value = convertJSON2BizObjects(key.split("~")[0], bizObjectManager, (JSONObject) value); + } else if (value instanceof JSONArray) { + value = convertJSON2BizObjects(key.split("~")[0], bizObjectManager, (JSONArray) value); + } + } catch (Exception e) { + e.printStackTrace(); + } + map.put(key, value); + } else { + map.put(key, value); + } + }); + return map; + } + + public static Map convertStringToMap(String jsonString) { + Map result = new ConcurrentHashMap<>(); + if (jsonString == null || "".equals(jsonString)) { + return result; + } + + return convertJSONToMap(JSON.parseObject(jsonString)); + } + + public static JSONObject convertJSONKeyUpperCase(JSONObject jsonObject) { + JSONObject data = new JSONObject(); + jsonObject.forEach((k, v) -> data.put(k.toUpperCase(), v)); + + return data; + } + + public static String convertMapToArrayString(List> datas) { + if (datas == null || datas.size() == 0) { + return "[]"; + } + + JSONArray jsonArray = new JSONArray(); + for (Map data : datas) { + jsonArray.add(convertMapToJSON(data)); + } + + return jsonArray.toJSONString(); + } + + public static JSONObject convertMapToJSON(Map data) { + JSONObject jsonObject = new JSONObject(); + for (Map.Entry o : data.entrySet()) { + jsonObject.put(o.getKey(), o.getValue()); + } + + return jsonObject; + } + + public static List> convertMapStringToMapObject(List> data) { + List> newData = getArrayList(); + data.forEach(m -> { + Map nm = new ConcurrentHashMap<>(); + m.forEach((k, v) -> { + nm.put(k, getString(v)); + }); + newData.add(nm); + }); + + return newData; + } + + public static String convertMapObjectToArrayString(List> datas) { + if (datas == null || datas.size() == 0) { + return "[]"; + } + + JSONArray jsonArray = new JSONArray(); + for (Map data : datas) { + jsonArray.add(convertMapObjectToJSON(data)); + } + + return jsonArray.toJSONString(); + } + + public static JSONObject convertMapObjectToJSON(Map data) { + JSONObject jsonObject = new JSONObject(); + for (Map.Entry o : data.entrySet()) { + jsonObject.put(o.getKey(), o.getValue()); + } + + return jsonObject; + } + + public static List convertJSONToBizObject(String tableName, JSONArray datas, String excludeFields) throws Exception { + if (StringUtils.isEmpty(tableName) || datas == null || datas.isEmpty()) { + return null; + } + if (tableName.contains(".")) { + tableName = tableName.substring(tableName.lastIndexOf(".") + 1).toUpperCase(); + } + List bos = getArrayList(); + for (int i = 0; i < datas.size(); i++) { + BizObject bo = BizObject.getBizObject(tableName); + JSONObject data = datas.getJSONObject(i); + for (Map.Entry entry : data.entrySet()) { + if (excludeFields != null && excludeFields.toUpperCase().contains(entry.getKey().toUpperCase())) { + continue; + } + bo.setAttributeValue(entry.getKey().toUpperCase(), entry.getValue()); + } + bos.add(bo); + } + + return bos; + } + + public static Object getIgnoreValue(JSONObject target, String key) { + if (target == null || StringUtils.isEmpty(key)) { + return null; + } + for (Map.Entry entry : target.entrySet()) { + if (key.equalsIgnoreCase(entry.getKey())) { + return entry.getValue(); + } + } + return null; + } + + /** + * 为JSONArray以UniCode方式排序, 默认值为字符串类型 + * + * @param jsonArray 数组对象 + * @param sSortIndex 排序关键字 + * @param sSortDirect 升序降序 + * @return 排序后的数组 + */ + public static JSONArray sortJSON(JSONArray jsonArray, String sSortIndex, String sSortDirect) { + if (jsonArray == null) { + return new JSONArray(); + } + + // 排序前后对应下标 + JSONObject sortIndexs = new JSONObject(); + + int n = 0; + while (n < jsonArray.size()) { + sortIndexs.put(n + "", n); + n++; + } + + // 过渡对象 + JSONObject temp; + // 排序 + for (int i = 0; i < jsonArray.size() - 1; i++) { + for (int j = 0; j < jsonArray.size() - 1 - i; j++) { + Object obj1 = getIgnoreValue(jsonArray.getJSONObject(j), sSortIndex); + if (obj1 == null) { + jsonArray.add(new JSONObject()); + return jsonArray; + } + String value1 = obj1 + ""; + Object obj2 = getIgnoreValue(jsonArray.getJSONObject(j + 1), sSortIndex); + if (obj2 == null) { + jsonArray.add(new JSONObject()); + return jsonArray; + } + String value2 = obj2 + ""; + boolean compareFlag = "desc".equalsIgnoreCase(sSortDirect) ? + compareString(value1, value2) < 0 : compareString(value1, value2) > 0; + if (compareFlag) { + int excludeIndex = 0; + if (sortIndexs.containsValue(j)) { + excludeIndex = getOriIndex(sortIndexs, j, null); + sortIndexs.put(excludeIndex + "", j + 1); + } + if (sortIndexs.containsValue(j + 1)) { + sortIndexs.put(getOriIndex(sortIndexs, j + 1, excludeIndex) + "", j); + } + temp = jsonArray.getJSONObject(j); + jsonArray.set(j, jsonArray.getJSONObject(j + 1)); + jsonArray.set(j + 1, temp); + } + } + } + + jsonArray.add(sortIndexs); + return jsonArray; + } + + public static int getOriIndex(JSONObject jsonObject, int index, Integer excludeIndex) { + int n = 0; + for (Map.Entry entry : jsonObject.entrySet()) { + if (excludeIndex != null && Integer.parseInt(entry.getKey()) == excludeIndex) { + continue; + } + if (Integer.parseInt(entry.getValue() + "") == index) { + n = Integer.parseInt(entry.getKey()); + break; + } + } + + return n; + } + + public static int compareString(String a, String b) { + char[] c1 = a.toCharArray(); + char[] c2 = b.toCharArray(); + + int n = c1.length == 0 && c2.length > 0 ? -1 : c1.length > 0 && c2.length == 0 ? 1 : 0; + if (n != 0) { + return n; + } + if (c1.length == 0 && c2.length == 0) { + return 0; + } + for (int i = 0; i < c1.length; i++) { + if (Integer.toHexString(c1[i]).equals(Integer.toHexString(c2[i]))) { + continue; + } else { + n = Integer.parseInt(Integer.toHexString(c1[i])) - Integer.parseInt(Integer.toHexString(c2[i])); + break; + } + } + + return n; + } + + public static int compareNumber(String a, String b) { + BigDecimal numberA; + BigDecimal numberB; + try { + numberA = new BigDecimal(a); + } catch (Exception e) { + return -1; + } + try { + numberB = new BigDecimal(b); + } catch (Exception e) { + return 1; + } + return numberA.compareTo(numberB); + } + + public static JSONArray filterJSON(JSONArray jsonArray, Vector filters, Vector columns) { + if (jsonArray == null) { + return new JSONArray(); + } + List removeObject = getArrayList(); + for (int i = 0; i < jsonArray.size(); i++) { + JSONObject obj = jsonArray.getJSONObject(i); + List flags = getArrayList(); + for (int j = 0; j < filters.size(); j++) { + ASDataObjectFilter asDataObjectFilter = filters.get(j); + if (".'SEARCH'".equals(asDataObjectFilter.sFilterColumnID)) { + String value = asDataObjectFilter.sFilterInputs[j][1]; + if (StringUtils.isEmpty(value)) { + break; + } + boolean flag = false; + for (ASColumn column : columns) { + String colName = column.getAttribute("COLNAME"); + String actValue = getString(getIgnoreValue(obj, colName)); + String colVisible = column.getAttribute("COLVISIBLE"); + if ("1".equals(colVisible)) { + if (actValue.contains(value)) { + flag = true; + break; + } + } + } + flags.add(flag); + } else { + String columnId = asDataObjectFilter.sFilterColumnID.split("\\.")[1]; + String operator = asDataObjectFilter.sOperator; + if (operator == null) { + operator = ""; + } + String type = asDataObjectFilter.sEditStyle; + if ("".equals(operator)) { + flags.add(true); + continue; + } + boolean flag = false; + String actValue = getString(getIgnoreValue(obj, columnId)); + String value = getFilterValue(asDataObjectFilter.sFilterInputs); + switch (operator) { + case "BeginsWith": + if (actValue.startsWith(value)) { + flag = true; + } + break; + case "Equals": + if (actValue.equals(value)) { + flag = true; + } + break; + case "NotBeginsWith": + if (!actValue.startsWith(value)) { + flag = true; + } + break; + case "Not": + if (!actValue.equals(value)) { + flag = true; + } + break; + case "BigThan": + switch (type) { + case "Text": + if (compareString(actValue, value) > 0) { + flag = true; + } + break; + case "Date": + if (compareTo(actValue, value) > 0) { + flag = true; + } + break; + } + break; + case "LessThan": + switch (type) { + case "Text": + if (compareString(actValue, value) < 0) { + flag = true; + } + break; + case "Date": + if (compareTo(actValue, value) < 0) { + flag = true; + } + break; + } + break; + case "LessEqualsThan": + switch (type) { + case "Text": + if (compareString(actValue, value) <= 0) { + flag = true; + } + break; + case "Date": + if (compareTo(actValue, value) <= 0) { + flag = true; + } + break; + } + break; + case "Area": + // TODO + break; + + } + flags.add(flag); + } + } + boolean f = false; + for (Boolean flag : flags) { + if (!flag) { + f = true; + break; + } + } + if (f) { + removeObject.add(obj); + } + } + for (JSONObject obj : removeObject) { + jsonArray.remove(obj); + } + jsonArray.add(new JSONObject()); + return jsonArray; + } + + public static String getFilterValue(String[][] sFilterInputs) { + String result = ""; + for (String[] sFilterInput : sFilterInputs) { + if (StringUtils.isEmpty(sFilterInput[1])) { + continue; + } + if (result.length() > 0) { + result += "@"; + } + result += sFilterInput[1]; + } + return result; + } + + public static String getTemplateDefaultValue(ASDataObject doTemp) { + return ""; + } + + public static String getTemplateDefaultValue(ASObjectModel doTemp) { + Vector columns = doTemp.Columns; + JSONObject jsonObject = new JSONObject(); + for (ASColumn column : columns) { + String name = column.getItemName(); + String value = column.getAttribute("COLDEFAULTVALUE"); + if (StringUtils.isNotEmpty(value)) { + jsonObject.put(name, value); + } + } + return jsonObject.toJSONString(); + } + + public static String getBusinessTypeTree() throws Exception { + List> datas = query("select case when attribute10 = 'Catalog' then 'folder' else 'item' end type_, typeno, typename, sortno, attribute9 as parentno from business_type where isinuse = 1 and TYPENAME not in('历史数据迁移产品','对公','回租','直租') order by sortno"); + JSONArray jsonArray = new JSONArray(); + for (int i = 0; i < datas.size(); i++) { + Map data = datas.get(i); + String type = data.get("TYPE_"); + String typeNo = data.get("TYPENO"); + String parentNo = data.get("PARENTNO"); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("id", typeNo); + jsonObject.put("label", data.get("TYPENAME")); + if ("folder".equals(type)) { + jsonArray.add(jsonObject); + } else { + for (int j = 0; j < jsonArray.size(); j++) { + JSONObject obj = jsonArray.getJSONObject(j); + if (obj.get("id").toString().replaceAll("Cata", "").equals(parentNo)) { + JSONArray array; + if (obj.get("children") != null) { + array = obj.getJSONArray("children"); + } else { + array = new JSONArray(); + } + array.add(jsonObject); + obj.put("children", array); + } + } + } + } + return jsonArray.toJSONString(); + } + + + //app零售计算器产品选择 + public static String getBusinessTypeTreeApp(String str) throws Exception { + List> datas = query("select case when attribute10 = 'Catalog' then 'folder' else 'item' end type_, typeno, typename, sortno, attribute9 as parentno from business_type where isinuse = 1 and TYPENAME not in('历史数据迁移产品','对公','回租','直租') order by sortno"); + JSONArray jsonArray = new JSONArray(); + for (int i = 0; i < datas.size(); i++) { + Map data = datas.get(i); + String type = data.get("TYPE_"); + String typeNo = data.get("TYPENO"); + String parentNo = data.get("PARENTNO"); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("id", typeNo); + jsonObject.put("label", data.get("TYPENAME")); + if ("folder".equals(type)) { + jsonArray.add(jsonObject); + } else { + for (int j = 0; j < jsonArray.size(); j++) { + JSONObject obj = jsonArray.getJSONObject(j); + if (obj.get("id").toString().replaceAll("Cata", "").equals(parentNo)) { + JSONArray array; + if (obj.get("children") != null) { + array = obj.getJSONArray("children"); + } else { + array = new JSONArray(); + } + if (str.length() != 0 && !data.get("TYPENAME").contains(str)) { + obj.put("children", array);//app零售计算器产品选择增加搜索框 + continue; + } + array.add(jsonObject); + obj.put("children", array); + } + } + } + } + return jsonArray.toJSONString(); + } + + + public static String getBusinessTypeTreePublic() throws Exception { + List> datas = query("select case when attribute10 = 'Catalog' then 'folder' else 'item' end type_, typeno, typename, sortno, attribute9 as parentno from business_type where isinuse = 1 and TYPENAME in('对公','回租','直租') order by sortno"); + JSONArray jsonArray = new JSONArray(); + for (int i = 0; i < datas.size(); i++) { + Map data = datas.get(i); + String type = data.get("TYPE_"); + String typeNo = data.get("TYPENO"); + String parentNo = data.get("PARENTNO"); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("id", typeNo); + jsonObject.put("label", data.get("TYPENAME")); + if ("folder".equals(type)) { + jsonArray.add(jsonObject); + } else { + for (int j = 0; j < jsonArray.size(); j++) { + JSONObject obj = jsonArray.getJSONObject(j); + if (obj.get("id").toString().replaceAll("Cata", "").equals(parentNo)) { + JSONArray array; + if (obj.get("children") != null) { + array = obj.getJSONArray("children"); + } else { + array = new JSONArray(); + } + array.add(jsonObject); + obj.put("children", array); + } + } + } + } + return jsonArray.toJSONString(); + } + + /** + * 立项业务线下对应产品 + * + * @param businessLine + * @return + * @throws Exception + */ + public static String getBusinessTypeTree(String businessLine) throws Exception { + List> datas = null; + /* + * if( businessLine.equals("lines01") ){//商用车 // 查询商用车向下的所有产品 + * List btList = + * JBOFactory.getBizObjectManager("jbo.prd.BUSINESS_TYPE"). + * createQuery("typename LIKE '%商用车%' AND attribute10 = 'Catalog'"). + * getResultList(false); String sortno = ""; for (int i=0; i btList = + * JBOFactory.getBizObjectManager("jbo.prd.BUSINESS_TYPE"). + * createQuery("typename LIKE '%工程机械%' AND attribute10 = 'Catalog'"). + * getResultList(false); String sortno = ""; for (int i=0; i data = datas.get(i); + String type = data.get("TYPE_"); + String typeNo = data.get("TYPENO"); + String parentNo = data.get("PARENTNO"); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("id", typeNo); + jsonObject.put("label", data.get("TYPENAME")); + if ("folder".equals(type)) { + jsonArray.add(jsonObject); + } else { + for (int j = 0; j < jsonArray.size(); j++) { + JSONObject obj = jsonArray.getJSONObject(j); + if (obj.get("id").toString().replaceAll("Cata", "").equals(parentNo)) { + JSONArray array; + if (obj.get("children") != null) { + array = obj.getJSONArray("children"); + } else { + array = new JSONArray(); + } + array.add(jsonObject); + obj.put("children", array); + } + } + } + } + return jsonArray.toJSONString(); + } + + public static String getRiskManagementCatalog() throws Exception { + List> datas = query("select attribute2 type_, itemno, itemname || case when attribute3 = '01' then '(企业目录)' else case when attribute3 = '03' then '(个人目录)' else '' end end itemname, pid, attribute2 from lb_risk_management_catalog where isinuse = '1' order by sortno"); + JSONArray jsonArray = new JSONArray(); + for (int i = 0; i < datas.size(); i++) { + Map data = datas.get(i); + String type = data.get("TYPE_"); + String itemNo = data.get("ITEMNO"); + String parentNo = data.get("PID"); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("id", itemNo); + jsonObject.put("label", data.get("ITEMNAME")); + jsonObject.put("type", type); + jsonObject.put("leaf", data.get("ATTRIBUTE2")); + getTree(jsonObject, jsonArray, type, parentNo); + } + return jsonArray.toJSONString(); + } + + public static String getRiskManagementCatalog(String businessLine) throws Exception { + List> datas = query("select a.attribute2 type_, a.itemno, a.itemname || case when a.attribute3 = '01' then '(企业目录)' else case when a.attribute3 = '03' then '(个人目录)' else '' end end itemname, a.pid, a.attribute2 from lb_risk_management_catalog a left join lb_risk_management_library b on a.itemno = b.itemno where a.isinuse = '1' and ( b.business_line = ? or a.itemno like '0001%' and b.id is null ) order by to_number( a.sortno )", businessLine); + JSONArray jsonArray = new JSONArray(); + for (int i = 0; i < datas.size(); i++) { + Map data = datas.get(i); + String type = data.get("TYPE_"); + String itemNo = data.get("ITEMNO"); + String parentNo = data.get("PID"); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("id", itemNo); + jsonObject.put("label", data.get("ITEMNAME")); + jsonObject.put("type", type); + jsonObject.put("leaf", data.get("ATTRIBUTE2")); + getTree(jsonObject, jsonArray, type, parentNo); + } + return jsonArray.toJSONString(); + } + + public static void getTree(JSONObject jsonObject, JSONArray jsonArray, String type, String parentNo) { + if ("0".equals(type)) { + jsonArray.add(jsonObject); + } else { + JSONObject obj = getTarget(jsonArray, parentNo); + JSONArray array = obj.getJSONArray("children"); + if (array == null) { + array = new JSONArray(); + } + array.add(jsonObject); + obj.put("children", array); + } + } + + /** + * 根据ID搜索对象 + * + * @param jsonArray + * @param id + * @return + */ + public static JSONObject getTarget(JSONArray jsonArray, String id) { + if (jsonArray == null) { + return null; + } + Iterator iterator = jsonArray.iterator(); + while (iterator.hasNext()) { + JSONObject target = null; + JSONObject obj = (JSONObject) iterator.next(); + if (!obj.get("id").equals(id)) { + target = getTarget((JSONArray) obj.get("children"), id); + } else { + return obj; + } + if (target == null) { + continue; + } else { + return target; + } + } + return null; + } + + public static String getFlowCondition(String flowNo, String phaseNo) throws Exception { + try { + String condition = getValueBySql("select attribute11 from flow_model where flowno = ? and phaseno = ?", flowNo, phaseNo); + if (StringUtils.isNotEmpty(condition)) { + return condition; + } else { + return ""; + } + } catch (Exception e) { + return ""; + } + } + + public static String getFlowLog(String flowunid) throws Exception { + List> datas = query("select * from ( select a.serialno, a.phaseno, a.phasename, a.begintime, a.endtime, nvl(getUserName(b.INPUTUSER),a.username) as username, nvl(GETORGNAME(b.INPUTORG),a.orgname) as orgname, ( case when b.updatetime is null then b.inputtime else b.updatetime end ) opiniontime, b.phaseopinion, a.phaseopinion1, phaseaction from flow_task a left join flow_opinion b on a.serialno = b.serialno where a.objectno = ? " + + //"union all " + + //"select '' serialno, a.phaseno, b.phasename, '' begintime, '' endtime, '' username, '' orgname, '' opiniontime, to_clob('') phaseopinion, '' phaseopinion1, '' phaseaction from flow_task a left join flow_task b on a.assignedtaskno = b.serialno where a.objectno = ? and a.assignedtaskno = b.serialno " + + //"union all " + + //"select '' serialno, a.phaseno, a.phasename, '' begintime, '' endtime, '' username, '' orgname, '' opiniontime, to_clob('') phaseopinion, '' phaseopinion1, '' phaseaction from flow_model a left join ( select b.phaseno from flow_task a left join flow_task b on a.assignedtaskno = b.serialno where a.objectno = ? and a.assignedtaskno = b.serialno ) c on 1 = 1 " + + //"left join ( select max( flowno ) flowno, max( phaseno ) phaseno from flow_task where objectno = ? ) d on 1 = 1 " + + //"where ( case when c.phaseno is not null then ( case when a.phaseno > c.phaseno then 1 else 2 end ) else ( case when a.phaseno > d.phaseno then 1 else 2 end ) end ) = 1 and a.flowno = d.flowno and ( case when d.phaseno = 1000 then ( case when a.phaseno <> 8000 then 1 else 2 end ) else 1 end ) = 1 ) t " + + ") t " + + "order by to_date( t.begintime, 'yyyy/mm/dd hh24:mi:ss' ), t.phaseno", flowunid); + return convertMapToArrayString(datas); + } + + public static String getFlowLogBack(String flowunid, String userId) throws Exception { + List> datas = query("select * from ( select a.serialno, a.phaseno, a.phasename, a.begintime, a.endtime, a.orgname, ( case when b.updatetime is null then b.inputtime else b.updatetime end ) opiniontime, b.phaseopinion, a.phaseopinion1 from flow_task a left join flow_opinion b on a.serialno = b.serialno where a.objectno = ? and a.phaseaction=? and a.phaseopinion1 like '%退回%') t " + + "order by to_date( t.begintime, 'yyyy/mm/dd hh24:mi:ss' ), t.phaseno", flowunid, userId); + return convertMapToArrayString(datas); + } + + public static String getFlowReader(String flowunid) throws Exception { + List> datas = query("select a.taskno, b.username, a.inputtime, a.updatetime, a.isread from flow_reader a left join user_info b on a.reader = b.userid where flowunid = ?", flowunid); + JSONObject readerData = new JSONObject(); + for (Map data : datas) { + String taskId = data.get("TASKNO"); + JSONArray readers = readerData.getJSONArray(taskId); + JSONObject reader = new JSONObject(); + reader.put("USERNAME", data.get("USERNAME")); + reader.put("ISREAD", data.get("ISREAD")); + reader.put("INPUTTIME", data.get("INPUTTIME")); + reader.put("UPDATETIME", data.get("UPDATETIME")); + if (readers == null) { + readers = new JSONArray(); + } + readers.add(reader); + readerData.put(taskId, readers); + } + return readerData.toJSONString(); + } + + public static void saveFlowCondition(Map params, String flowCondition, JBOTransaction tx) throws Exception { + String flowNo = params.get("flowNo").toString(); + String phaseNo = params.get("phaseNo").toString(); + String keyName = getValueBySql("select attribute12 from flow_model where flowno = ? and phaseno = ?", flowNo, phaseNo); + String keyValue = getString(params.get(keyName)); + executeUpdate("update flow_condition set status = '1' where flowno = ? and phaseno = ?", tx, flowNo, phaseNo); + BizObject bo = BizObject.getBizObject("FLOW_CONDITION"); + bo.setAttributeValue("ID", UUIDUtil.getUUID()); + bo.setAttributeValue("KEY1", keyValue); + bo.setAttributeValue("FLOW_UNID", params.get("ObjectNo")); + bo.setAttributeValue("TASK_ID", params.get("TaskNo")); + bo.setAttributeValue("FLOWNO", flowNo); + bo.setAttributeValue("PHASENO", phaseNo); + bo.setAttributeValue("CONDITION", flowCondition); + bo.setAttributeValue("STATUS", "0"); + bo.setAttributeValue("INPUTUSERID", params.get("userId")); + bo.setAttributeValue("INPUTORGID", params.get("orgId")); + bo.setAttributeValue("INPUTTIME", StringFunction.getTodayNow()); + insert(bo, tx); + } + + public static void setPatameter(Page curPage, String kv) { + if (StringUtils.isEmpty(kv)) { + return; + } + Vector parameters = curPage.getCurComp().getParameterList(); + Parameter parameter = new Parameter(); + parameter.setName(kv.split("->")[0]); + parameter.setValue(kv.split("->")[1]); + parameters.add(parameter); + curPage.getCurComp().setParameterList(parameters); + } + + public static void setAttributes(com.amarsoft.are.jbo.BizObject bo, List> datas) throws JBOException { + if (bo == null && (datas == null || datas.isEmpty())) { + return; + } + Map data = datas.get(0); + for (DataElement dataElement : bo.getAttributes()) { + String columnName = dataElement.getName(); + for (Map.Entry entry : data.entrySet()) { + if (entry.getKey().equalsIgnoreCase(columnName)) { + bo.setAttributeValue(columnName, entry.getValue()); + break; + } + } + } + } + + public static void save(List> classs, Vector columns, com.amarsoft.are.jbo.BizObject bo, boolean createKey, boolean flag, JBOTransaction tx) throws Exception { + if (classs == null || classs.isEmpty() || columns == null || columns.isEmpty()) { + return; + } + for (Map cls : classs) { + String alias = cls.get("alias"); + String className = cls.get("className"); + BizObjectClass boc = JBOFactory.getBizObjectClass(className); + String[] dataElements = boc.getKeyAttributes(); + if (dataElements == null || dataElements.length == 0) { + continue; + } + BizObject newBo = BizObject.getBizObject(className); + String key = ""; + boolean keyFlag = false; + for (ASColumn column : columns) { + String tableName = column.getAttribute("COLTABLENAME"); + if (!alias.equalsIgnoreCase(tableName)) { + continue; + } + String colName = column.getAttribute("COLNAME"); + boolean isKey = false; + for (String keyName : dataElements) { + if (keyName.equalsIgnoreCase(colName)) { + isKey = true; + if (!"".equals(key)) { + key += ","; + } + key += colName.toUpperCase(); + keyFlag = false; + String keyValue = bo.getAttribute(colName).getString(); + if (StringUtils.isNotEmpty(keyValue)) { + keyFlag = true; + } + } + } + if (isKey && createKey) { + newBo.setAttributeValue(colName.toUpperCase(), UUIDUtil.getUUID()); + continue; + } + newBo.setAttributeValue(colName.toUpperCase(), bo.getAttribute(colName).getString()); + } + if (flag) { + keyFlag = false; + } + if ("".equals(key)) { + continue; + } else if (!keyFlag) { + insert(newBo, tx); + } else { + update(newBo, tx, key); + } + } + + return; + } + + public static boolean isJSON(Page page, String dono) throws Exception { + String templateNo = page.getParameter("FlowTemplateNo"); + boolean flag = false; + Vector parameterList = page.getCurComp().getParameterList(); + for (Parameter parameter : parameterList) { + if (parameter.getName().equals(dono) || parameter.getName().equals("InfoData")) { + flag = true; + break; + } + } + return flag; + } + + public static boolean isReadOnly(Page page) throws Exception { + String rightType = page.getParameter("RightType"); + String isHistory = page.getParameter("IsHistory"); + return isReadOnly(rightType, isHistory); + } + + public static boolean isReadOnly(String rightType, String isHistory) { + if ((null != rightType && rightType.equals("ReadOnly")) || (null != isHistory && isHistory.equals("true"))) { + return true; + } else { + return false; + } + } + + public static JSONObject getTemplateAllValue(Page page, String templateNo) throws Exception { + JSONObject dataJSON = null; + String data = page.getParameter(templateNo); + String infoData = page.getParameter("InfoData"); + if ("true".equals(page.getParameter("loadDataBase"))) { + String flowunid = page.getParameter("ObjectNo"); + String taskId = page.getParameter("TaskNo"); + Map d = DataUtil.flowVariables("FLOW_VARINST", null, flowunid, taskId, templateNo); + if (d.size() > 0 && d.get(templateNo) != null) { + data = JSON.toJSONString(d.get(templateNo)); + } + } + if (infoData != null && !"".equals(infoData) && !"null".equals(infoData)) { + dataJSON = JSON.parseObject(infoData.replaceAll("@_@", ">>").replaceAll("%", "@-@").replaceAll("@\\^@", "<").replaceAll("@v@", ">").replaceAll("@\\*@", "+")); + } else if (data != null && !"".equals(data) && !"null".equals(data)) { + dataJSON = JSON.parseObject(URLDecoder.decode(data.replaceAll("%", "@-@"), "UTF-8").replaceAll("@_@", ">>").replaceAll("@\\^@", "<").replaceAll("@v@", ">").replaceAll("@\\*@", "+")); + } + + if (dataJSON != null) { + dataJSON = convertJSONObjectSymbols(dataJSON); + } + + return dataJSON; + } + + public static void convertJSONArraySymbols(JSONArray jsonArray) { + for (int i = 0; i < jsonArray.size(); i++) { + convertJSONObjectSymbols(jsonArray.getJSONObject(i)); + } + } + + public static JSONObject convertJSONObjectSymbols(JSONObject jsonObject) { + for (Map.Entry entry : jsonObject.entrySet()) { + jsonObject.put(entry.getKey(), convertSymbols(entry.getValue())); + } + return jsonObject; + } + + public static Object convertSymbols(Object obj) { + if (obj != null) { + return obj.toString().replaceAll("@-@", "%"); + } + return obj; + } + + public static JSONArray getTemplateAllList(Page page, String templateNo) throws Exception { + JSONArray arrayJSON = null; + String arrayData = page.getParameter(templateNo); + if (arrayData != null && !"".equals(arrayData)) { + arrayJSON = JSON.parseArray(URLDecoder.decode(arrayData, "UTF-8").replaceAll("@_@", ">>")); + } + + return arrayJSON; + } + + public static String getPageParameters(Page page, String... paramterNames) { + return getPageParameters(null, page, paramterNames); + } + + public static String getPageParameters(String symbol, Page page, String... paramterNames) { + Vector params = page.getCurComp().getParameterList(); + StringBuffer stringBuffer = new StringBuffer(); + if (StringUtils.isEmpty(symbol)) { + symbol = "&"; + } + for (Parameter parameter : params) { + if (paramterNames != null && paramterNames.length > 0) { + for (String p : paramterNames) { + if (p.equals(parameter.getName())) { + if (stringBuffer.length() > 0) { + stringBuffer = stringBuffer.append(symbol); + } + stringBuffer = stringBuffer.append(parameter.getName()).append("=").append(parameter.getValue()); + break; + } + } + } else { + if (stringBuffer.length() > 0) { + stringBuffer = stringBuffer.append(symbol); + } + stringBuffer = stringBuffer.append(parameter.getName()).append("=").append(parameter.getValue()); + } + } + return stringBuffer.toString(); + } + + public static Object getTemplateValue(Page page, String templateNo, String key) throws Exception { + JSONObject dataJSON = getTemplateAllValue(page, templateNo); + if (dataJSON == null) { + return null; + } + return dataJSON.get(key); + } + + public static void setTemplateValue(Page page, String templateNo, String key, String value) throws Exception { + JSONObject dataJSON = getTemplateAllValue(page, templateNo); + if (dataJSON == null) { + dataJSON = new JSONObject(); + } + dataJSON.put(key, value); + page.setAttribute(templateNo, JSON.toJSONString(dataJSON).replaceAll(">>", "@_@")); + } + + public static void saveTemplate(Bizlet bizlet, String templateNo, JBOTransaction tx) throws Exception { + saveTemplate(bizlet, templateNo, true, null, true, tx); + } + + public static void saveTemplate(Bizlet bizlet, String templateNo, String otherProp, JBOTransaction tx) throws Exception { + saveTemplate(bizlet, templateNo, true, otherProp, true, tx); + } + + public static void saveTemplate(Bizlet bizlet, String templateNo, boolean createKey, String otherProp, JBOTransaction tx) throws Exception { + saveTemplate(bizlet, templateNo, createKey, otherProp, true, tx); + } + + /** + * flag = true 的时候,无论如何都会insert + * + * @param bizlet + * @param templateNo + * @param insertOrUpdate + * @param tx + * @throws Exception + */ + public static void saveTemplate(Bizlet bizlet, String templateNo, boolean insertOrUpdate, JBOTransaction tx) throws Exception { + saveTemplate(bizlet, templateNo, true, null, insertOrUpdate, tx); + } + + public static void saveTemplate(Bizlet bizlet, String templateNo, boolean createKey, String otherProp, boolean flag, JBOTransaction tx) throws Exception { + if (bizlet != null) { + if ("".equals(bizlet.getAttribute(templateNo))) { + return; + } + com.amarsoft.are.jbo.BizObject bo = (com.amarsoft.are.jbo.BizObject) bizlet.getAttribute(templateNo); + if (bo != null) { + if (StringUtils.isNotEmpty(otherProp)) { + String[] props = otherProp.split(","); + for (String prop : props) { + bo.setAttributeValue(prop.split("=")[0], prop.split("=")[1]); + } + } + saveTemplate(templateNo, bo, createKey, flag, tx); + } else { + throw new JBOException("NO TEMPLATE DATA"); + } + } + } + + public static void saveTemplate(String templateNo, com.amarsoft.are.jbo.BizObject bo, boolean createKey, boolean flag, JBOTransaction tx) throws Exception { + ASObjectModel asObjectModel = new ASObjectModel(templateNo); + List> classs = getTemplateClass(asObjectModel); + Vector columns = asObjectModel.Columns; + save(classs, columns, bo, createKey, flag, tx); + } + + public static List> getTemplateClass(ASObjectModel asObjectModel) { + String jboFrom = asObjectModel.getJboFrom(); + Pattern p = Pattern.compile("jbo\\.(\\w+\\.)*[A-Z_0-9]+[\\s]+(as|AS|As)?[\\s]?[\\w]+[\\s]{1}"); + Matcher m = p.matcher(jboFrom); + List> classs = getArrayList(); + while (m.find()) { + Map cls = new ConcurrentHashMap<>(); + String jboClassName = m.group().trim(); + cls.put("className", jboClassName.split(" ")[0]); + cls.put("alias", jboClassName.split(" ")[1]); + classs.add(cls); + } + String mainJboClass = asObjectModel.getJboClass(); + Map cls = new ConcurrentHashMap<>(); + cls.put("className", mainJboClass); + cls.put("alias", "O"); + classs.add(cls); + + return classs; + } + + public static String getJBOClass(com.amarsoft.are.jbo.BizObject bizObject) { + if (bizObject == null) { + return ""; + } + String className = bizObject.getBizObjectClass().getPackageName() + "." + bizObject.getBizObjectClass().getName(); + String pattern = "\\d"; + if (Pattern.matches(pattern, className.substring(className.length() - 1))) { + className = className.substring(0, className.lastIndexOf("X")); + } + return className; + } + + public static String getIgnoreCaseParams(String key, Page page) { + for (Parameter parameter : page.getCurComp().getParameterList()) { + if (parameter.getName().equalsIgnoreCase(key)) { + return parameter.getValue(); + } + } + return null; + } + + public static List getUpdateFields(String templateNo, com.amarsoft.are.jbo.BizObject bo) throws Exception { + List updateFields = getArrayList(); + if (bo instanceof StateBizObject) { + com.amarsoft.are.jbo.BizObject oBo = getTemplateJBO(templateNo); + StateBizObject so = (StateBizObject) bo; + DataElement[] dataElements = bo.getAttributes(); + for (int i = 0; i < dataElements.length; i++) { + oBo.setAttributeValue(i, so.getOriginalValue(i)); + if (!bo.getAttribute(i).equals(oBo.getAttribute(i))) { + updateFields.add(dataElements[i].getName()); + } + } + } + return updateFields; + } + + public static void saveListTemplate(Bizlet bizlet, String templateNo, JBOTransaction tx) throws Exception { + saveListTemplate(bizlet, null, templateNo, true, null, null, tx); + } + + public static void saveListTemplate(Bizlet bizlet, String templateNo, boolean createKey, JBOTransaction tx) throws Exception { + saveListTemplate(bizlet, null, templateNo, createKey, null, null, tx); + } + + public static void saveListTemplate(Bizlet bizlet, String templateNo, String otherProp, JBOTransaction tx) throws Exception { + saveListTemplate(bizlet, null, templateNo, true, otherProp, null, tx); + } + + public static void saveListTemplate(Bizlet bizlet, String templateNo, boolean createKey, String otherProp, JBOTransaction tx) throws Exception { + saveListTemplate(bizlet, null, templateNo, true, otherProp, null, tx); + } + + public static void saveListTemplate(Bizlet bizlet, String templateNoTemp, String templateNo, boolean createKey, String otherProp, String insertOrUpdate, JBOTransaction tx) throws Exception { + saveListTemplate(bizlet, templateNoTemp, templateNo, createKey ? "true" : "false", otherProp, insertOrUpdate, tx); + } + + public static void saveListTemplate(Bizlet bizlet, String templateNoTemp, String templateNo, String createKey, String otherProp, String insertOrUpdate, JBOTransaction tx) throws Exception { + if (bizlet != null) { + List bos; + if (StringUtils.isNotEmpty(templateNoTemp)) { + bos = (List) bizlet.getAttribute(templateNoTemp); + } else { + bos = (List) bizlet.getAttribute(templateNo); + } + if (bos != null) { + if (StringUtils.isNotEmpty(otherProp)) { + String[] props = otherProp.split(","); + for (com.amarsoft.are.jbo.BizObject bo : bos) { + for (String prop : props) { + bo.setAttributeValue(prop.split("=")[0], prop.split("=")[1]); + } + } + } + saveListTemplate(bos, createKey, insertOrUpdate, tx); + } else { + // throw new JBOException( "NO TEMPLATE DATA" ); + } + } + } + + public static void saveListTemplate(List bos, JBOTransaction tx) throws Exception { + saveListTemplate(bos, "false", null, tx); + } + + public static void saveListTemplate(List bos, String createKey, String insertOrUpdate, JBOTransaction tx) throws Exception { + if (bos == null) { + return; + } + List insert = getArrayList(); + List update = getArrayList(); + String key = ""; + boolean flag = false; + for (com.amarsoft.are.jbo.BizObject bizObject : bos) { + String[] keys = bizObject.getBizObjectClass().getKeyAttributes(); + String className = bizObject.getBizObjectClass().getPackageName() + "." + bizObject.getBizObjectClass().getName(); + String pattern = "\\d"; + if (Pattern.matches(pattern, className.substring(className.length() - 1))) { + className = className.substring(0, className.lastIndexOf("X")); + } + BizObjectManager bom = JBOFactory.getBizObjectManager(className); + com.amarsoft.are.jbo.BizObject bo = bom.newObject(); + for (DataElement dataElement1 : bo.getAttributes()) { + for (DataElement dataElement2 : bizObject.getAttributes()) { + if (dataElement1.getName().equalsIgnoreCase(dataElement2.getName())) { + bo.setAttributeValue(dataElement1.getName().toUpperCase(), bizObject.getAttribute(dataElement2.getName())); + break; + } + } + } + boolean keyFlag = false; + for (String k : keys) { + keyFlag = false; + String keyValue = bizObject.getAttribute(k).getString(); + if (StringUtils.isNotEmpty(keyValue)) { + if (!flag) { + flag = true; + if (!"".equals(key)) { + key += ","; + } + key += k.toUpperCase(); + } + keyFlag = true; + } + if (!keyFlag && ("true".equals(createKey) || "auto".equals(createKey))) { + bo.setAttributeValue(k.toUpperCase(), UUIDUtil.getUUID()); + } + } + if ("insert".equals(insertOrUpdate) && !"auto".equals(createKey)) { + keyFlag = false; + } + if (keyFlag) { + update.add(bo); + } else { + insert.add(bo); + } + } + if (insert.size() > 0) { + insert(insert, tx); + } + if (update.size() > 0) { + update(update, tx, key); + } + } + + + /** + * ***********************************************测算API开始********************************************************** + */ + + // 二分法IRR + public static BigDecimal getIRR(List cashFlows, BigDecimal incomeNumberYear) { + List cashFlow = getArrayList(); + for (int o = 0; o < cashFlows.size(); o++) { + Object obj = cashFlows.get(o); + if (obj instanceof BigDecimal) { + cashFlow.add((BigDecimal) obj); + } else { + cashFlow.add(new BigDecimal(obj.toString())); + } + } + BigDecimal up = BigDecimal.ONE; + BigDecimal down = BigDecimal.ZERO; + BigDecimal two = new BigDecimal("2"); + BigDecimal irr = new BigDecimal("0.01"); + BigDecimal accuracy = new BigDecimal("0.0000001"); + BigDecimal out; + + int i = 0; + while (irr.abs().compareTo(accuracy) > 0 && i < 200) { + out = cashFlow.get(0); + for (int j = 1; j < cashFlow.size(); j++) { + out = out.add(cashFlow.get(j).divide(new BigDecimal(Math.pow(BigDecimal.ONE.add(irr).doubleValue(), j)), 20, 4)); + } + + if (out.compareTo(BigDecimal.ZERO) > 0) { + down = irr; + irr = irr.add(up).divide(two, 20, 4); + } else if (out.compareTo(BigDecimal.ZERO) < 0) { + up = irr; + irr = irr.add(down).divide(two, 20, 4); + } + i++; + } + irr = irr.multiply(incomeNumberYear).multiply(new BigDecimal(100)); + + return irr; + } + + /** + * NPV + * + * @param rate 折现率 + * @param cashFlow 现金流 + * @return + */ + public static BigDecimal getNPV(BigDecimal rate, BigDecimal incomeNumberYear, List cashFlow) { + BigDecimal npv = BigDecimal.ZERO; + rate = BigDecimal.ONE.add(rate.divide(incomeNumberYear, 20, 4)); + // 因为是摊到月的,所以用12月来代替 + // rate = BigDecimal.ONE.add( rate.divide( new BigDecimal( 12 ), 20, 4 ) ); + int i = 1; + for (String cash : cashFlow) { + npv = npv.add(new BigDecimal(cash).divide(new BigDecimal(Math.pow(rate.doubleValue(), Double.parseDouble((i++) + ""))), 20, 4)); + } + return npv.setScale(2, 4); + } + + /** + * XNPV + * + * @param rate 折现率 + * @param dateList 日期列表 + * @param cashFlow 现金流 + * @return + */ + public static BigDecimal getXNPV(BigDecimal rate, String startDate, List dateList, List cashFlow) { + BigDecimal xnpv = BigDecimal.ZERO; + rate = rate.divide(new BigDecimal(360), 20, 4); + BigDecimal prev = BigDecimal.ONE; + for (int i = 0; i < cashFlow.size(); i++) { + BigDecimal days; + if (i == 0) { + days = getDayDiff(startDate, dateList.get(i)); + } else { + days = getDayDiff(dateList.get(i - 1), dateList.get(i)); + } + prev = BigDecimal.ONE.add(rate.multiply(days)).multiply(prev); + xnpv = xnpv.add(new BigDecimal(cashFlow.get(i)).divide(prev, 20, 4)); + } + return xnpv.setScale(2, 4); + } + + + /** + * PMT + * + * @param rate 期利率 + * @param nper 期次 + * @param pv 现值 + * @param fv 未来值 + * @param type 期初/期末 + * @return + */ + public static BigDecimal getPMT(BigDecimal rate, BigDecimal nper, BigDecimal pv, BigDecimal fv, BigDecimal type) { + if (rate == null || nper == null || pv == null) { + return BigDecimal.ZERO; + } + if (fv == null) { + fv = BigDecimal.ZERO; + } + if (type == null || type.compareTo(BigDecimal.ONE) > 0 || type.compareTo(BigDecimal.ZERO) < 0) { + type = BigDecimal.ZERO; + } + if (rate.compareTo(BigDecimal.ZERO) == 0) { + return pv.negate().subtract(fv.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : fv.divide(new BigDecimal(Math.pow(BigDecimal.ONE.add(rate).doubleValue(), nper.doubleValue())), 20, 4)) + .divide(nper, 2, 4); + } else { + return pv.negate().subtract(fv.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : fv.divide(new BigDecimal(Math.pow(BigDecimal.ONE.add(rate).doubleValue(), nper.doubleValue())), 20, 4)) + .multiply(rate).multiply(new BigDecimal(Math.pow(BigDecimal.ONE.add(rate).doubleValue(), nper.subtract(type).doubleValue()))).divide(new BigDecimal(Math.pow(BigDecimal.ONE.add(rate).doubleValue(), nper.doubleValue())).subtract(BigDecimal.ONE), 2, 4); + } + } + + /** + * PV + * + * @param rate 期利率 + * @param nper 期次 + * @param pmt + * @param fv 未来值 + * @param type 期初/期末 + * @return pv 现值 + */ + + public static BigDecimal getPV(BigDecimal rate, BigDecimal nper, BigDecimal pmt, BigDecimal fv, BigDecimal type) { + if (rate == null || nper == null) { + return BigDecimal.ZERO; + } + if (fv == null) { + fv = BigDecimal.ZERO; + } + if (type == null || type.compareTo(BigDecimal.ONE) > 0 || type.compareTo(BigDecimal.ZERO) < 0) { + type = BigDecimal.ZERO; + } + if (pmt == null) { + pmt = BigDecimal.ZERO; + } + if (rate.compareTo(BigDecimal.ZERO) == 0) { + return BigDecimal.ONE.negate().multiply(pmt.multiply(rate).add(fv.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : fv.divide(new BigDecimal(Math.pow(BigDecimal.ONE.add(rate).doubleValue(), nper.doubleValue())), 20, 4))).setScale(2, 4); + } else { + return BigDecimal.ONE.negate().multiply(pmt.multiply(BigDecimal.ONE.subtract(new BigDecimal(Math.pow(BigDecimal.ONE.add(rate).doubleValue(), nper.negate().add(type).doubleValue()))).divide(rate, 20, 4).add(type)).add(fv.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : fv.divide(new BigDecimal(Math.pow(BigDecimal.ONE.add(rate).doubleValue(), nper.doubleValue())), 20, 4))).setScale(2, 4); + } + } + + public static String getDiscount(JBOTransaction tx, String flowunid, boolean flag) throws Exception { + List> discount; + if (flag) { + discount = query("select wm_concat( nvl( c.interests, 0 ) || '@' || a.id ) discount from lb_equipment_car_temp a" + + " left join lb_commercial_interests c on a.car_date_id = c.id and trunc( sysdate ) between" + + " to_date( c.interestsbegin, 'yyyy/mm/dd' ) and to_date( c.interestsover, 'yyyy/mm/dd' ) where c.id is not null and a.flowunid = ? order by a.id", tx, flowunid); + } else { + discount = query("select wm_concat( nvl( c.interests, 0 ) || '@' || a.id ) discount from lb_equipment_car_temp a" + + " left join lb_cardata_model_interests c on a.car_date_id = c.id and trunc( sysdate ) between" + + " to_date( c.interestsbegin, 'yyyy/mm/dd' ) and to_date( c.interestsover, 'yyyy/mm/dd' ) where c.id is not null and a.flowunid = ? order by a.id", tx, flowunid); + } + if (discount.size() == 0 || discount.get(0).get("DISCOUNT") == null) { + return "0"; + } else { + return discount.get(0).get("DISCOUNT"); + } + } + + public static String getDiscountByCarId(String carId, JBOTransaction tx) throws Exception { + List> discount = query("select nvl( interests, -1 ) interest from lb_commercial_interests where id = ? and trunc( sysdate ) between" + + " to_date( interestsbegin, 'yyyy/mm/dd' ) and to_date( interestsover, 'yyyy/mm/dd' )", tx, carId); + if (discount.size() == 0 || discount.get(0).get("INTEREST") == null) { + return "-1"; + } else { + return discount.get(0).get("INTEREST"); + } + } + + public static String getActualDiscount(JBOTransaction tx, String flowunid) throws Exception { + List> discount = query("select sum( nvl( actual_discount, 0 ) ) discount from lb_equipment_car_temp where flowunid = ?", tx, flowunid); + if (discount.size() == 0 || discount.get(0).get("DISCOUNT") == null) { + return "0"; + } else { + return discount.get(0).get("DISCOUNT"); + } + } + + public static String getPrice(JBOTransaction tx, String flowunid, boolean flag) throws Exception { + List> price; + if (flag) { + price = query("select wm_concat( id || '@' || ( transactionprice + nvl( equip_purchase_tax, 0 ) + nvl( equip_insurance, 0 ) + nvl( accessory_money, 0 ) + nvl( upper_equipment, 0 ) ) || '@' || nvl( price, 0 ) ) price from lb_equipment_car_temp where flowunid = ? order by id", tx, flowunid); + } else { + price = query("select wm_concat( id || '@' || transactionprice || '@' || nvl( price, 0 ) ) price from lb_equipment_car_temp where flowunid = ? order by id", tx, flowunid); + } + + if (price.size() == 0 || price.get(0).get("PRICE") == null) { + return "0"; + } else { + return price.get(0).get("PRICE"); + } + } + + public static String getPrice1(JBOTransaction tx, String flowunid) throws Exception { + String sql = "select nvl(SUM(TOTALPRICE),0) as TOTALPRICE from LB_EQUIPMENT_CAR_TEMP o where o.flowunid=? "; + List> map = DataUtil.query(sql, tx, flowunid); + String price = map.get(0).get("TOTALPRICE"); + return price; + } + + //获取增融比例 + public static String getFinancingPro(JBOTransaction tx, String flowunid) throws Exception { + List> price = query("select nvl(round(sum(INCREASE_FINANCING)/sum(EQUIP_PRICE),2)*100,0) as proportion from LB_EQUIPMENT_CAR_TEMP where FLOWUNID=?", tx, flowunid); + String financingPro = price.get(0).get("PROPORTION"); + return financingPro; + } + + + public static BizObject getDiscountAndYearRate(Map equipment, List> discountRate) throws Exception { + // 交易价格 + BigDecimal transactionPrice = new BigDecimal(equipment.get("TRANSACTIONPRICE")); + // 购置税 + BigDecimal equipPurchaseTax = new BigDecimal(equipment.get("EQUIP_PURCHASE_TAX")); + equipPurchaseTax = BigDecimal.ZERO; + // 保险费 + BigDecimal equipInsurance = new BigDecimal(equipment.get("EQUIP_INSURANCE")); + equipInsurance = BigDecimal.ZERO; + // 配件费 + BigDecimal accessoryMoney = new BigDecimal(equipment.get("ACCESSORY_MONEY")); + accessoryMoney = BigDecimal.ZERO; + // 上装费 + BigDecimal upperEquipment = new BigDecimal(equipment.get("UPPER_EQUIPMENT")); + upperEquipment = BigDecimal.ZERO; + // IRR + BigDecimal irr = new BigDecimal(equipment.get("IRR")); + // 贴息收取延迟月数 + BigDecimal discoutDelayMonth = new BigDecimal(equipment.get("DISCOUTDELAYMONTH")); + // 年还款次数 + BigDecimal incomeNumberYear = new BigDecimal(equipment.get("INCOMENUMBERYEAR")); + // 还款次数 + int incomeNumber = Integer.parseInt(equipment.get("INCOMENUMBER")); + // 期初/期末 + BigDecimal periodType = new BigDecimal(equipment.get("PERIODTYPE")); + // 资金成本折现率 + BigDecimal capitalCostRate = new BigDecimal(equipment.get("CAPITALCOSTRATE")); + // 首付比例 + BigDecimal firstPaymentRatio = new BigDecimal(equipment.get("FIRSTPAYMENTRATIO")); + firstPaymentRatio = firstPaymentRatio.multiply(new BigDecimal("0.01")); + // 保证金比例 + BigDecimal cautionMoneyRatio = new BigDecimal(equipment.get("CAUTIONMONEYRATIO")); + cautionMoneyRatio = cautionMoneyRatio.multiply(new BigDecimal("0.01")); + // 首付款 + transactionPrice = transactionPrice.add(equipInsurance).add(equipPurchaseTax).add(accessoryMoney).add(upperEquipment); + BigDecimal firstPayment = transactionPrice.multiply(firstPaymentRatio); + // 融资额 + BigDecimal cleanLeaseMoney = transactionPrice.subtract(firstPayment).negate(); + // 保证金抵扣 + BigDecimal cautionMoney = cleanLeaseMoney.multiply(cautionMoneyRatio).negate(); + // 贴息 + BigDecimal discount = new BigDecimal(equipment.get("DISCOUNT")); + // 加入贴息计算( 交易价格 + 购置税 + 保险费 - ( 交易价格 + 购置税 + 保险费 ) * 首付比例 ) * 贴息比例 + BigDecimal t = new BigDecimal("0.01"); + BigDecimal dt = BigDecimal.ZERO; + for (Map d : discountRate) { + BigDecimal up = new BigDecimal(d.get("EquipUplimpits")); + BigDecimal down = new BigDecimal(d.get("MoneyLowLimits")); + if (cleanLeaseMoney.negate().compareTo(down) >= 0 && cleanLeaseMoney.negate().compareTo(up) <= 0) { + BigDecimal r; + BigDecimal v; + if ("".equals(d.get("DiscountRate"))) { + r = BigDecimal.ZERO; + } else { + r = new BigDecimal(d.get("DiscountRate")); + } + if ("".equals(d.get("DiscountValue"))) { + v = BigDecimal.ZERO; + } else { + v = new BigDecimal(d.get("DiscountValue")); + } + if (r.compareTo(BigDecimal.ZERO) > 0) { + BigDecimal m; + if ("CLEAN_LEASE_MONEY".equals(d.get("DiscountReferenceFee"))) { + m = cleanLeaseMoney.negate(); + } else { + m = transactionPrice; + } + dt = m.multiply(r).multiply(t); + } else { + dt = v; + } + break; + } + } + dt = dt.setScale(2, 4); + if (dt.compareTo(discount) > 0) { + dt = discount; + } + discount = dt; + if (discoutDelayMonth.compareTo(BigDecimal.ZERO) > 0) { + discount = getPV(capitalCostRate, discoutDelayMonth, BigDecimal.ZERO, discount.negate(), BigDecimal.ZERO); + } + + // 贴息脱税 + BigDecimal tax = new BigDecimal(equipment.get("TAX")).multiply(t); + BigDecimal other = new BigDecimal(equipment.get("OTHER")).multiply(t).add(BigDecimal.ONE); + BigDecimal calDiscount = DataUtil.discountTaxDeduction(discount, tax, other); + + cleanLeaseMoney = cleanLeaseMoney.add(calDiscount).add(cautionMoney); + + BizObject bo = BizObject.getBizObject("LB_EQUIPMENT_CAR_TEMP"); + bo.setAttributeValue("ID", equipment.get("ID")); + bo.setAttributeValue("EQUIP_DISCOUNT", discount); + bo.setAttributeValue("EQUIP_YEAR_RATE", getYearRate(cleanLeaseMoney, irr, incomeNumber, incomeNumberYear, periodType, cautionMoney, calDiscount, tax, other).setScale(6, 4).toString()); + + return bo; + } + + public static BigDecimal getYearRate(BigDecimal cleanLeaseMoney, BigDecimal irr, int incomeNumber, BigDecimal incomeNumberYear, BigDecimal periodType, BigDecimal cautionMoney, BigDecimal calDiscount, BigDecimal tax, BigDecimal other) { + // 构造测算参数 + BigDecimal up = BigDecimal.ONE; + BigDecimal down = BigDecimal.ZERO; + BigDecimal two = new BigDecimal("2"); + BigDecimal rate = new BigDecimal("0.001"); + BigDecimal accuracy = new BigDecimal("0.0000001"); + BigDecimal calcIrr; + BigDecimal cautionMoneyTemp; + BigDecimal cleanLeaseMoneyTemp; + + int i = 0; + do { + cleanLeaseMoneyTemp = cleanLeaseMoney.subtract(cautionMoney).subtract(calDiscount).negate(); + BigDecimal pRete = rate.divide(incomeNumberYear, 20, 4); + BigDecimal rent = getPMT(pRete, new BigDecimal(incomeNumber), cleanLeaseMoneyTemp.negate(), BigDecimal.ZERO, periodType); + List cashList = Arrays.asList(new BigDecimal[incomeNumber + 1]); + List taxList = Arrays.asList(new BigDecimal[incomeNumber + 1]); + cautionMoneyTemp = cautionMoney; + cashList.set(0, cleanLeaseMoney); + taxList.set(0, BigDecimal.ZERO); + for (int j = 1; j < incomeNumber + 1; j++) { + BigDecimal interest = cleanLeaseMoneyTemp.multiply(pRete).setScale(2, 4); + BigDecimal t = interest.multiply(other).multiply(tax).divide(BigDecimal.ONE.add(tax), 2, 4); + taxList.set(j, t); + cashList.set(j, rent.subtract(t)); + cleanLeaseMoneyTemp = cleanLeaseMoneyTemp.subtract(rent.subtract(interest)); + } + if (cautionMoneyTemp.compareTo(BigDecimal.ZERO) > 0) { + double count = cautionMoneyTemp.divide(rent, 2, 4).doubleValue(); + int d = 0; + for (; d < (int) count; d++) { + cashList.set(cashList.size() - 1 - d, BigDecimal.ZERO.subtract(taxList.get(cashList.size() - 1 - d))); + } + cautionMoneyTemp = cautionMoneyTemp.subtract(rent.multiply(new BigDecimal((int) count))); + if (cautionMoneyTemp.compareTo(BigDecimal.ZERO) > 0) { + cashList.set(cashList.size() - 1 - d, rent.subtract(cautionMoneyTemp).subtract(taxList.get(cashList.size() - 1 - d))); + } + } + calcIrr = getIRR(cashList, incomeNumberYear); + if (calcIrr.compareTo(irr) > 0) { + up = rate; + rate = rate.add(down).divide(two, 20, BigDecimal.ROUND_HALF_UP); + } else if (calcIrr.compareTo(irr) < 0) { + down = rate; + rate = rate.add(up).divide(two, 20, BigDecimal.ROUND_HALF_UP); + } else { + break; + } + i++; + } while (calcIrr.abs().compareTo(accuracy) > 0 && i < 100); + return rate.multiply(new BigDecimal(100)); + } + + public static String getUnIncomePlanList(String paymentNumber) throws Exception { + List> planList = query("select case when max(zero_rent_max_plan_list)>=max(min_plan_list) and max(zero_rent_max_plan_list)< max(max_plan_list) then max(zero_rent_max_plan_list)+1||'@'||max(max_plan_list)" + + " when max(nvl(zero_rent_max_plan_list,0))=0 then max(min_plan_list)|| '@' || max(max_plan_list) WHEN max( zero_rent_max_plan_list ) < max( min_plan_list ) then" + + " max( min_plan_list ) || '@' || max( max_plan_list ) else '0' end as planList from (select min(plan_list) as min_plan_list,max(plan_list) as max_plan_list,0 as zero_rent_max_plan_list from vi_lc_rent_plan vlrp where payment_number = ?" + + " and fact_rent = 0 and vlrp.RENT > 0 union all select 0 as min_plan_list,0 as max_plan_list,max(plan_list) as zero_rent_max_plan_list from vi_lc_rent_plan vlrp where payment_number = ? and vlrp.RENT = 0) vlrp", paymentNumber, paymentNumber); + if (planList.size() > 0 && !"0".equals(planList.get(0).get("PLANLIST"))) { + String pList = planList.get(0).get("PLANLIST"); + int s = Integer.parseInt(pList.split("@")[0]); + int m = Integer.parseInt(pList.split("@")[1]); + String interest = getValueBySql("select interest from vi_lc_rent_plan where payment_number = ? and plan_list = ?", paymentNumber, s); + String r = ""; + if (s == m) { + r = s + "," + m; + } else { + for (int i = s; i <= m; i++) { + if (r.length() > 0) { + r += ","; + } + r += i + "," + i; + } + } + return r + "@" + interest; + } else { + return "0@0"; + } + } + + public static BigDecimal discountTaxDeduction(BigDecimal discount, TabCalBean tcb) { + BigDecimal t = new BigDecimal("0.01"); + BigDecimal tax = new BigDecimal("0"); + BigDecimal other = new BigDecimal("0"); + return discountTaxDeduction(discount, tax, other); + } + + public static BigDecimal discountTaxDeduction(BigDecimal discount, BigDecimal tax, BigDecimal other) { + return discount.subtract(discount.multiply(tax).divide(BigDecimal.ONE.add(tax), 2, 4).multiply(other).setScale(2, 4)); + } + + public static String getFeeName(String feeType, Item[] items) { + for (Item item : items) { + if (feeType.equals(item.getItemNo())) { + return item.getRelativeCode(); + } + } + return feeType; + } + + + public static void updatePACashFlow(Map params, JBOTransaction tx) throws Exception { + String productId = params.get("productId"); + String paymentNumber = params.get("paymentNumber"); + String userId = params.get("userId"); + String orgId = params.get("orgId"); + Map> productCashInIRRList = ProductParamUtil.getProductComponentType(productId, "PRD0315"); + List outFeeType = getArrayList(); + for (Map.Entry> entry : productCashInIRRList.entrySet()) { + String feeName = entry.getKey(); + Map items = entry.getValue(); + if ("N".equals(items.get("CostType10"))) { + outFeeType.add(feeName); + } + } + executeUpdate("DELETE FROM PA_CASH_FLOW WHERE PAYMENT_NUMBER = ?", tx, paymentNumber); + String cashFlowSql = "INSERT INTO PA_CASH_FLOW\n" + + "( ID, PROJECT_ID, PROJECT_PLAN_NUMBER, CONTRACT_ID, CONTRACT_PLAN_NUMBER, PAYMENT_NUMBER,\n" + + " PLAN_DATE, FUND_IN, FUND_IN_DETAILS, FUND_OUT, FUND_OUT_DETAILS, NET_FLOW, INPUTUSERID, INPUTORGID, INPUTTIME\n" + + ")\n" + + "SELECT SYS_GUID(), MAX( C.PROJECT_ID ), MAX( C.PROJECT_PLAN_NUMBER ), MAX( C.CONTRACT_ID ), MAX( C.CONTRACT_PLAN_NUMBER ), MAX( C.PAYMENT_NUMBER ), C.PLAN_DATE,\n" + + "SUM( C.FUND_IN ), NVL( WM_CONCAT( CASE WHEN C.FUND_IN_DETAILS = '' THEN NULL ELSE C.FUND_IN_DETAILS END ), '-' ),\n" + + "SUM( C.FUND_OUT ), NVL( WM_CONCAT( CASE WHEN C.FUND_OUT_DETAILS = '' THEN NULL ELSE C.FUND_OUT_DETAILS END ), '-' ),\n" + + "SUM( C.NET_FLOW ), ?, ?, ?\n" + + "FROM ( SELECT PROJECT_ID, PROJECT_PLAN_NUMBER, CONTRACT_ID, CONTRACT_PLAN_NUMBER, PAYMENT_NUMBER,\n" + + "PLAN_DATE, RENT FUND_IN, '第' || PLAN_LIST || '期本息:' || TO_CHAR( RENT, 'FM9,999,999,999,999,999,999,999,990.00' ) FUND_IN_DETAILS,\n" + + "0 FUND_OUT, '' FUND_OUT_DETAILS, RENT NET_FLOW\n" + + "FROM PA_RENT_PLAN WHERE PAYMENT_NUMBER = ?\n" + + "UNION ALL\n" + + "SELECT PROJECT_ID, PROJECT_PLAN_NUMBER, CONTRACT_ID, CONTRACT_PLAN_NUMBER, PAYMENT_NUMBER,\n" + + "PLAN_DATE,\n" + + "CASE WHEN PAY_TYPE = 'pay_type_in' THEN PLAN_MONEY ELSE 0 END FUND_IN,\n" + + "CASE WHEN PAY_TYPE = 'pay_type_in' THEN CASE WHEN B.ITEMNAME = '设备款' THEN '当金' ELSE B.ITEMNAME END || ':' || TO_CHAR( PLAN_MONEY, 'FM9,999,999,999,999,999,999,999,990.00' ) ELSE '' END FUND_IN_DETAILS,\n" + + "CASE WHEN PAY_TYPE = 'pay_type_in' THEN 0 ELSE PLAN_MONEY END FUND_OUT,\n" + + "CASE WHEN PAY_TYPE = 'pay_type_in' THEN '' ELSE CASE WHEN B.ITEMNAME = '设备款' THEN '当金' ELSE B.ITEMNAME END || ':' || TO_CHAR( PLAN_MONEY, 'FM9,999,999,999,999,999,999,999,990.00' ) END FUND_OUT_DETAILS,\n" + + "CASE WHEN PAY_TYPE = 'pay_type_in' THEN PLAN_MONEY ELSE -PLAN_MONEY END NET_FLOW\n" + + "FROM PA_FUND_PLAN A\n" + + "LEFT JOIN CODE_LIBRARY B ON A.FEE_TYPE = B.ITEMNO AND B.CODENO = 'FeeType'\n" + + "WHERE A.PAYMENT_NUMBER = ?"; + if (outFeeType.size() > 0) { + cashFlowSql += "AND B.RELATIVECODE NOT IN ( " + getSqlInCondition(outFeeType.toArray(new String[outFeeType.size()])) + " )"; + } + cashFlowSql += " ) C GROUP BY C.PLAN_DATE"; + executeUpdate(cashFlowSql, tx, userId, orgId, StringFunction.getTodayNow(), paymentNumber, paymentNumber); + } + + + /** + * ***********************************************测算API结束********************************************************** + */ + + public static String getItemsToString(String codeNo) throws Exception { + return getItemsToString(CodeManager.getItems(codeNo)); + } + + public static String getItemsToString(Item[] items) { + JSONArray jsonArray = new JSONArray(); + for (Item item : items) { + JSONObject obj = new JSONObject(); + obj.put("value", item.getItemNo()); + obj.put("name", item.getItemName()); + jsonArray.add(obj); + } + return jsonArray.toJSONString(); + } + + public static List> getItemsToList(Item[] items) { + List> datas = getArrayList(); + for (Item item : items) { + Map data = new ConcurrentHashMap<>(); + data.put("value", item.getItemNo()); + data.put("name", item.getItemName()); + datas.add(data); + } + return datas; + } + + public static List> toLowerCase(List> datas) { + for (int i = 0; i < datas.size(); i++) { + Map newData = new ConcurrentHashMap<>(); + for (Map.Entry entry : datas.get(i).entrySet()) { + newData.put(entry.getKey().toLowerCase(), entry.getValue()); + } + datas.set(i, newData); + } + return datas; + } + + public static String getSqlInCondition(String[] conditions) { + String condition = ""; + for (String c : conditions) { + if (condition.length() > 0) { + condition += ", "; + } + condition += "'" + c + "'"; + } + return condition; + } + + public static Map convertUserListToMap(List> userList) { + Map users = new ConcurrentHashMap<>(); + if (userList == null) { + return users; + } + for (Map user : userList) { + users.put(user.get("USERID"), user.get("USERNAME")); + } + + return users; + } + + public static String getSelectRole(String config) { + String[] c = config.split(","); + String roles = ""; + for (int i = 0; i < c.length; i++) { + if (i % 2 == 0) { + if (roles.length() > 0) { + roles += ","; + } + roles += "'" + c[i] + "'"; + } + } + return roles; + } + + public static LinkedHashMap getkeyList(String keyList) { + LinkedHashMap params = new LinkedHashMap(1, 0.75f, true); + String[] kvs = keyList.split("@"); + for (String kv : kvs) { + params.put(kv.split("--")[0], kv.split("--")[1]); + } + return params; + } + + public static Map getParams(String p) { + Map np = new ConcurrentHashMap<>(); + if (StringUtils.isEmpty(p)) { + return np; + } + String[] ps = p.split("△"); + for (String s : ps) { + np.put(s.split("->")[0], s.split("->")[1]); + } + return np; + } + + public static Map getPageParams(Page page) { + if (page == null) { + return null; + } + Map params = new ConcurrentHashMap<>(); + for (Parameter parameter : page.getCurComp().getParameterList()) { + params.put(parameter.getName(), parameter.getValue()); + } + + return params; + } + + public static List> getParamList(String p) { + List> np = getArrayList(); + if (StringUtils.isEmpty(p)) { + return np; + } + String[] ps = p.split("@~"); + for (String s : ps) { + Map m = new ConcurrentHashMap<>(); + for (String t : s.split("@")) { + m.put(t.split("->")[0], t.split("->")[1]); + } + np.add(m); + } + return np; + } + + public static BigDecimal getDayDiff(String date1, String date2) { + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd"); + LocalDate e = LocalDate.parse(date1, dateTimeFormatter); + LocalDate s = LocalDate.parse(date2, dateTimeFormatter); + return new BigDecimal(e.until(s, ChronoUnit.DAYS)); + } + + public static int compareTo(String date1, String date2) { + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd"); + LocalDate e = LocalDate.parse(date1, dateTimeFormatter); + LocalDate s = LocalDate.parse(date2, dateTimeFormatter); + return e.compareTo(s); + } + + public static String getEquipAmt(String businessLine, String flowunid, boolean flag) throws Exception { + List> datas; + String table = "lb_equipment_temp"; + if (flag) { + table = "lb_equipment_car_temp"; + } + if ("lines01".equals(businessLine) || "lines04".equals(businessLine)) { + datas = query("select sum( nvl( transactionprice, 0 ) ) + sum( nvl( equip_purchase_tax, 0 ) ) + sum( nvl( equip_insurance, 0 ) ) + sum( nvl( accessory_money, 0 ) ) + sum( nvl( upper_equipment, 0 ) ) equipAmt from lb_equipment_car_temp where flowunid = ?", flowunid); + } else if ("lines02".equals(businessLine)) { + datas = query("select sum( nvl( transactionprice, 0 ) ) equipAmt from lb_equipment_car_temp where flowunid = ?", flowunid); + } else if ("lines".equals(businessLine)) { + datas = query("select sum( nvl( equip_price, 0 ) ) equipAmt from lb_indent_equipment_temp where flowunid = ?", flowunid); + } else { + datas = query("select sum( nvl( equip_price, 0 ) ) equipAmt from " + table + " where flowunid = ?", flowunid); + } + // 项目立项工程机械业务线查询lb_equipment_temp表 + if (!flag && "lines04".equals(businessLine) && datas.size() == 0) { + datas = query("select sum( nvl( equip_price, 0 ) ) equipAmt from " + table + " where flowunid = ?", flowunid); + } + if (datas.size() > 0 && datas.get(0).get("EQUIPAMT") != null) { + return datas.get(0).get("EQUIPAMT"); + } else { + return "0"; + } + } + + public static void copyRiskManagement(String flowunid, String kv, JBOTransaction tx, String otherField) throws Exception { + List> d = DataUtil.query("select id from lb_risk_management_relative where flow_unid = ?", tx, flowunid); + if (d.size() == 0) { + String[] keyValue = kv.split("="); + List> nd = DataUtil.query("select id from lb_risk_management_relative where " + keyValue[0] + " = ? order by to_date( inputtime, 'yyyy/mm/dd hh24:mi:ss' ) desc", tx, keyValue[1]); + if (nd.size() > 0) { + String relativeId = nd.get(0).get("ID"); + String o = "FLOW_UNID->" + flowunid; + if (StringUtils.isNotEmpty(otherField)) { + o += "@" + otherField; + } + DataUtil.copy("jbo.sys.LB_RISK_MANAGEMENT_RELATIVE", "jbo.sys.LB_RISK_MANAGEMENT_RELATIVE", "ID->" + relativeId, "", o, null, null, true, tx); + String newRelativeId = DataUtil.getValueBySql("select id from lb_risk_management_relative where flow_unid = ?", tx, flowunid); + DataUtil.copy("jbo.sys.LB_RISK_MANAGEMENT_DATA", "jbo.sys.LB_RISK_MANAGEMENT_DATA", "RELATIVE_ID->" + relativeId, "", "RELATIVE_ID->" + newRelativeId, null, null, true, tx); + } + } + } + + public static String getNewNodeId(String nodeId) { + String zero = ""; + for (int i = 0; i < nodeId.length(); i++) { + if (nodeId.charAt(i) == '0') { + zero += "0"; + } else { + break; + } + } + int id = Integer.parseInt(nodeId); + id += 1; + return zero + id; + } + + public static String getItemNo(String codeNo, String relativeCode) throws Exception { + Item[] items = CodeManager.getItems(codeNo); + for (Item item : items) { + if (relativeCode.equals(item.getRelativeCode())) { + return item.getItemNo(); + } + } + return ""; + } + + public static String getItemName(String codeNo, String relativeCode) throws Exception { + Item[] items = CodeManager.getItems(codeNo); + for (Item item : items) { + if (relativeCode.equals(item.getRelativeCode())) { + return item.getItemName(); + } + } + return ""; + } + + public static String getItemNames(String codeNo, String itemNos) throws Exception { + String result = ""; + for (String itemNo : itemNos.split(",")) { + if (result.length() > 0) { + result += ","; + } + result += itemNo + "," + CodeCache.getItemName(codeNo, itemNo); + } + return result; + } + + public static String getAttribute1(String codeNo, String relativeCode) throws Exception { + Item[] items = CodeManager.getItems(codeNo); + for (Item item : items) { + if (relativeCode.equals(item.getRelativeCode())) { + return item.getAttribute1(); + } + } + return ""; + } + + /** + * ************************************************页面渲染API开始********************************************************** + */ + + public static void setTreeView(BaseInitTreeView treeView) throws Exception { + List treeItems = treeView.getTreeItem(); + String productId = treeView.getFlowFixedParam().get("ProductId"); + if (StringUtils.isNotEmpty(productId)) { + removeTreeView(treeItems, productId, null); + } + } + + public static void removeTreeView(List treeItems, String productId, List itemNos) throws Exception { + if (itemNos == null) itemNos = getArrayList(); + for (TreeItemData treeItem : treeItems) { + String itemNo = treeItem.getItemNo(); + if (itemNos.contains(itemNo)) { + continue; + } + if (Pattern.matches("(50004)?(50005)?", itemNo)) { + // 处理典当物页面 + String pawnType = ProductParamUtil.getProductParameterValue(productId, "PRD0355", "PawnType"); + if ("real_estate_pawn".equals(pawnType)) { + removeTreeView(treeItems, "50004"); + } else { + removeTreeView(treeItems, "50005"); + } + itemNos.add("50004"); + itemNos.add("50005"); + removeTreeView(treeItems, productId, itemNos); + break; + } + } + } + + public static void removeTreeView(List treeItems, String removeItemNo) { + for (TreeItemData treeItem : treeItems) { + String itemNo = treeItem.getItemNo(); + if (removeItemNo.equals(itemNo)) { + treeItems.remove(treeItem); + break; + } + } + } + + /** + * ************************************************页面渲染API结束********************************************************** + */ + + public static List getSqlParams(String sql, Map params) { + Pattern pattern = Pattern.compile("(\\{(.*?)\\})"); + Matcher matcher = pattern.matcher(sql); + List param = getArrayList(); + while (matcher.find()) { + String key = matcher.group(); + key = key.replaceAll("[{]", ""); + key = key.replaceAll("[}]", ""); + param.add(params.getOrDefault(key, "")); + } + return param; + } + + /** + * 例( { rect1: XXXX, rect2: XXXX } ), 排序类此结构JSON + * + * @param jsonObject + * @return + */ + public static List sortJSONObject(JSONObject jsonObject) { + List newJsonObject = getArrayList(); + for (Map.Entry obj : jsonObject.entrySet()) { + int key = Integer.parseInt(obj.getKey().replaceAll("\\D", "")); + JSONObject newObj = new JSONObject(); + newObj.put(obj.getKey(), obj.getValue()); + if (newJsonObject.size() < key) { + for (int i = 0; i <= key; i++) { + newJsonObject.add(null); + } + } + newJsonObject.set(key, newObj); + } + newJsonObject.removeAll(Collections.singleton(null)); + return newJsonObject; + } + + /** + * 根据ProjectId判断当前项目是否融租上回 + * + * @param projectId + * @return 是否融租上会 + */ + public static boolean projectIsMeeting(String projectId) throws Exception { + boolean _flag = false; + String flowNo = "PAProjectReviewFlow"; + List> data = query("select flow_unid from pa_project_info where id = ? ", projectId); + String flowUnid = ""; + if (data.size() > 0 && data != null) { + flowUnid = data.get(0).get("FLOW_UNID"); + } + List> flowData = query("select flowno from flow_task where objectno= ? ", flowUnid); + //判断sql查出来的归属于项目审核还是变更流程 + if (!flowNo.equals(flowData.get(0).get("FLOWNO"))) { + flowNo = "PaProjectReviewChange"; + } + + //判断当前流程是否上会 + data = query("select serialno from flow_task where objectno = ? and phaseno = '0100' and flowno = ? ", flowUnid, flowNo); + if (data.size() > 0 && data != null) { + _flag = !_flag; + return _flag; + } + return _flag; + } + + /** + * 解析UNICODE + */ + public static String unicodeToString(String unicodes) { + String[] unicodeArray = unicodes.split("\\\\u"); + String sResult = ""; + for (String unicode : unicodeArray) { + sResult += (char) Integer.valueOf(unicode, 16).intValue(); + } + return sResult; + } + + public static String getContractTemplateList() throws Exception { + Item[] paContractTwoClasses = CodeManager.getItems("pa_contract_two_class"); + String params = ""; + for (Item item : paContractTwoClasses) { + if (params.length() > 0) { + params += ","; + } + params += "'" + item.getItemNo() + "'"; + } + List> datas = DataUtil.query("select a.doc_class_itemno codeno, a.id itemno, a.doc_name itemname, b.id template_id from lb_docconfig a left join bf_template b on a.id = b.config_id where a.doc_class_itemno in ( " + params + " ) order by doc_class_itemno, to_number( a.serial_num )"); + return getCodeTree(datas).toJSONString(); + } + + public static JSONObject getCodeTree(List> datas) { + JSONObject sResult = new JSONObject(); + for (Map data : datas) { + String codeNo = data.get("CODENO"); + String itemNo = data.get("ITEMNO"); + String itemName = data.get("ITEMNAME"); + String templateId = data.get("TEMPLATE_ID"); + JSONObject object = new JSONObject(); + object.put("itemno", itemNo); + object.put("itemname", itemName); + object.put("template_id", templateId); + JSONArray array = null; + for (Map.Entry entry : sResult.entrySet()) { + String c = entry.getKey(); + JSONArray a = (JSONArray) entry.getValue(); + if (codeNo.equals(c)) { + array = a; + break; + } + } + if (array == null) { + array = new JSONArray(); + array.add(object); + sResult.put(codeNo, array); + } else { + array.add(object); + } + } + return sResult; + } + + public static void convertBeanToBean(Class cls, Object instanceo, Object instancen) throws Exception { + convertBeanToBean(cls, instanceo, instancen, null); + } + + public static void convertBeanToBean(Class cls, Object instanceo, Object instancen, String excludeMethod) throws Exception { + Method[] declaredMethods = cls.getDeclaredMethods(); + for (Method method : declaredMethods) { + String name = method.getName(); + if (method.getParameterTypes().length > 0) { + continue; + } + if (StringUtils.isNotEmpty(excludeMethod)) { + List em = Arrays.asList(excludeMethod.split(",")); + if (em.contains(name)) { + continue; + } + } + if (name.startsWith("get") || name.startsWith("is")) { + try { + if (name.equals("getSpacingAfterLines") || name.equals("getSpacingBeforeLines")) { + continue; + } + if (name.startsWith("is")) { + name = "get" + name.substring(2); + } + if (name.equals("getWordWrapped") || name.equals("getTextScale") || name.equals("getWordWrap") || name.equals("getWidthType")) { + continue; + } + Method setMethod = cls.getDeclaredMethod(name.replaceAll("get", "set"), method.getReturnType()); + setMethod.invoke(instancen, method.invoke(instanceo)); + } catch (NoSuchMethodException e) { + } + } + } + } +}