jfow-代码分析
- 目录
- 概述
- 需求:
- 设计思路
- 实现思路分析
- 1.代码:
- 2.代码2:
- 3.CashFrmTemplate
- 4.chartType
- 5.DataColumn
- Data:
- 参考资料和推荐阅读
Survive by day and develop by night.
talk for import biz , show your perfect code,full busy,skip hardness,make a better result,wait for change,challenge Survive.
happy for hardess to solve denpendies.
目录
概述
需求:
设计思路
实现思路分析
1.代码:
package bp.da;
import bp.difference.ContextHolderUtils;
import bp.difference.SystemConfig;
import bp.en.Entities;
import bp.en.Row;
import bp.tools.StringUtils;
import java.util.Hashtable;
/**
* hashtable
* -- entity
* -- row
*/
/**
实体缓存
*/
public class Cash2019
{
public static String redisKey = SystemConfig.getRedisCacheKey("Case2019");
/**
清除所有的实体缓存.
*/
/* public static void ClearCash()
{
// _hts = null;
ContextHolderUtils.getRedisUtils().del(false,redisKey);
}*/
//缓存ht
// en-pk
// private static Hashtable _hts;
// public static Hashtable getHts()
// {
//
// _hts =ContextHolderUtils.getRedisUtils().hget(false,redisKey);
// if (_hts == null)
// {
// _hts = new Hashtable<>();
// }
//
// return _hts;
// }
///对实体的操作.
/**
把实体放入缓存里面
param enName
param pkVal
param row
*/
public static void PutRow(String enName, String pkVal, Row row) {
// synchronized (lockObj)
// {
// Object tempVar = getHts().get(enName);
// Hashtable<String,Object> ht = tempVar instanceof Hashtable ? (Hashtable<String,Object>)tempVar : null;
// if (ht == null)
// {
// ht = new Hashtable<>();
// getHts().put(enName, ht);
// }
// ht.put(pkVal, row);
// ContextHolderUtils.getRedisUtils().hset(false,redisKey,enName,ht, 300);
if(StringUtils.isBlank(pkVal)) return;
ContextHolderUtils.getRedisUtils().set(false, SystemConfig.getRedisCacheKey(enName + "_"+pkVal), row);
// }
}
public static void UpdateRow(String enName, String pkVal, Row row) {
// synchronized (lockObj)
// {
// Object tempVar = getHts().get(enName);
// Hashtable<String,Object> ht = tempVar instanceof Hashtable ? (Hashtable)tempVar : null;
// if (ht == null)
// {
// ht = new Hashtable<>();
// getHts().put(enName, ht);
//
// }
// ht.put(pkVal, row);
// ContextHolderUtils.getRedisUtils().hset(false,redisKey,enName,ht, 300);
if(StringUtils.isBlank(pkVal)) return;
ContextHolderUtils.getRedisUtils().set(false, SystemConfig.getRedisCacheKey(enName + "_"+pkVal), row);
// }
}
public static void DeleteRow(String enName, String pkVal) {
// synchronized (lockObj)
// {
// Object tempVar = getHts().get(enName);
// Hashtable<String,Object> ht = tempVar instanceof Hashtable ? (Hashtable)tempVar : null;
// if (ht == null)
// {
// ht = new Hashtable<>();
// getHts().put(enName, ht);
// }
// ht.remove(pkVal.toString());
// ContextHolderUtils.getRedisUtils().hset(false,redisKey,enName,ht,300);
ContextHolderUtils.getRedisUtils().del(false, SystemConfig.getRedisCacheKey(enName + "_"+pkVal));
// }
}
// private static final Object lockObj = new Object();
/**
获得实体类
param enName 实体名字
param pkVal 键
@return row
*/
public static Row GetRow(String enName, String pkVal) {
// synchronized (lockObj)
// {
Object obj = ContextHolderUtils.getRedisUtils().get(false,SystemConfig.getRedisCacheKey(enName + "_"+pkVal));
return obj==null ? null : (Row) obj;
// Object tempVar = getHts().get(enName);
// Hashtable ht = tempVar instanceof Hashtable ? (Hashtable)tempVar : null;
// if (ht == null)
// return null;
// if(DataType.IsNullOrEmpty(pkVal)==true)
// return null;
// if (ht.containsKey(pkVal) == true)
// {
// return ht.get(pkVal) instanceof Row ? (Row)ht.get(pkVal) : null;
// }
// return null;
// }
}
/// 对实体的操作.
///对实体的集合操作.
/**
把集合放入缓存.
param ensName 集合实体类名
param ens 实体集合
*/
// public static void PutEns(String ensName, Entities ens)
// {
//
// }
/**
获取实体集合类
param ensName 集合类名
param pkVal 主键
@return 实体集合
*/
// public static Entities GetEns(String ensName, Object pkVal)
// {
// return null;
// }
}
2.代码2:
package bp.da;
import bp.difference.ContextHolderUtils;
import bp.difference.SystemConfig;
import bp.en.*;
import java.util.*;
public class CashEntity
{
///Hashtable 属性
private static Hashtable<String, Object> _Cash = new Hashtable<>();
private static String dCashKey = SystemConfig.getRedisCacheKey("DCash");
public static Hashtable<String, Object> getDCash()throws Exception
{
_Cash = ContextHolderUtils.getRedisUtils().hget(false,dCashKey);
return _Cash;
}
/**
把实体放入缓存里面
param enName
param ens
param enPK
* @throws Exception
*/
public static void PubEns(String enName, Entities ens, String enPK) throws Exception
{
Object tempVar = CashEntity.getDCash().get(enName);
Hashtable ht = tempVar instanceof Hashtable ? (Hashtable)tempVar : null;
if (ht == null)
{
ht = new Hashtable();
}
ht.clear();
for (Entity en : ens)
{
ht.put(en.GetValStrByKey(enPK), en);
}
// 把实体集合放入.
CashEntity.getDCash().put(enName + "Ens", ens);
ContextHolderUtils.getRedisUtils().hset(false,dCashKey,enName + "Ens",ens);
}
public static Entities GetEns(String enName) throws Exception {
Object tempVar = CashEntity.getDCash().get(enName + "Ens");
Entities ens = tempVar instanceof Entities ? (Entities)tempVar : null;
return ens;
}
/**
更新对象
param enName
param key
param en
*/
public static void Update(String enName, String key, Entity en) throws Exception {
Object tempVar = CashEntity.getDCash().get(enName);
Hashtable ht = tempVar instanceof Hashtable ? (Hashtable)tempVar : null;
if (ht == null)
{
ht = new Hashtable();
CashEntity.getDCash().put(enName, ht);
}
ht.put(key, en);
//清除集合.
CashEntity.getDCash().remove(enName + "Ens");
//ContextHolderUtils.getRedisUtils().hset(false,enName,ht);
ContextHolderUtils.getRedisUtils().hdel(false,dCashKey,enName + "Ens");
}
/**
获取一个实体
param enName 实体Name
param pkVal 主键值
@return 返回这个实体
*/
public static Entity Select(String enName, String pkVal) throws Exception {
Object tempVar = CashEntity.getDCash().get(enName);
Hashtable ht = tempVar instanceof Hashtable ? (Hashtable)tempVar : null;
if (ht == null)
{
return null;
}
return ht.get(pkVal) instanceof Entity ? (Entity)ht.get(pkVal) : null;
}
/**
删除
param enName
param pkVal
*/
public static void Delete(String enName, String pkVal) throws Exception {
Object tempVar = CashEntity.getDCash().get(enName);
Hashtable ht = tempVar instanceof Hashtable ? (Hashtable)tempVar : null;
if (ht == null)
{
return;
}
ht.remove(pkVal);
//清除集合.
CashEntity.getDCash().remove(enName + "Ens");
ContextHolderUtils.getRedisUtils().hset(false,dCashKey,enName,ht);
ContextHolderUtils.getRedisUtils().hdel(false,dCashKey,enName + "Ens");
}
/**
插入
param enName
param en
param pkVal
*/
public static void Insert(String enName, String pkVal, Entity en) throws Exception {
Object tempVar = CashEntity.getDCash().get(enName);
Hashtable ht = tempVar instanceof Hashtable ? (Hashtable)tempVar : null;
if (ht == null)
{
return;
}
if (ht.containsKey(pkVal))
{
ht.put(pkVal, en);
}
else
{
ht.put(pkVal, en);
}
//清除集合.
CashEntity.getDCash().remove(enName + "Ens");
ContextHolderUtils.getRedisUtils().hset(false,dCashKey,enName,ht);
ContextHolderUtils.getRedisUtils().hdel(false,dCashKey,enName + "Ens");
}
}
3.CashFrmTemplate
package bp.da;
import bp.difference.ContextHolderUtils;
import bp.difference.SystemConfig;
public class CashFrmTemplate {
///对实体的操作.
/**
* 放入表单
* <p>
* param frmID 表单ID
* param ds 表单模版
*
* @throws Exception
*/
public static void Put(String frmID, DataSet ds) throws Exception {
if (ds == null) return;
String json = bp.tools.Json.ToJson(ds);
ContextHolderUtils.getRedisUtils().set(false, SystemConfig.getRedisCacheKey(frmID), json);
}
/**
* 移除
* <p>
* param frmID 表单ID
*/
public static void Remove(String frmID) {
ContextHolderUtils.getRedisUtils().del(false, SystemConfig.getRedisCacheKey(frmID));
}
/**
* 获得表单DataSet模式的模版数据
* <p>
* param frmID 表单ID
*
* @return 表单模版
*/
public static DataSet GetFrmDataSetModel(String frmID) throws Exception {
Object result = ContextHolderUtils.getRedisUtils().get(false, SystemConfig.getRedisCacheKey(frmID));
if (result != null) {
DataSet ds = bp.tools.Json.ToDataSet(result.toString());
return ds;
}
return null;
}
/**
* 获得表单json模式的模版数据
* <p>
* param frmID 表单ID
*
* @return json
*/
/// 对实体的操作.
}
4.chartType
package bp.da;
/**
图表类型
*/
public enum ChartType
{
/**
柱状图
*/
Histogram,
/**
丙状图
*/
Pie,
/**
折线图
*/
Line;
public static final int SIZE = java.lang.Integer.SIZE;
public int getValue()
{
return this.ordinal();
}
public static ChartType forValue(int value)
{
return values()[value];
}
}
5.DataColumn
package bp.da;
import java.util.HashMap;
import java.util.Map;
public class DataColumn
{
/**
* DataColumn所屬的DataTable
*/
private DataTable table;
/**
* DataColumn的欄位名稱
*/
public String ColumnName; // 欄名,當做DataRow的key
public String oldColumnName; // 欄名,當做DataRow的key
public void setColumnName(String val)
{
if (oldColumnName==null)
oldColumnName= ColumnName;
ColumnName=val;
}
public Object DataType;
public Object getDataType()throws Exception
{
return DataType;
}
public void setDataType(Object dataType)
{
DataType = dataType;
}
/**
* DataColumn被建立時,一定要指定欄名
*
* param columnName
* 欄名
*/
public DataColumn(String columnName)
{
this.ColumnName = columnName;
this.oldColumnName = columnName;
}
public DataColumn()throws Exception
{
}
public DataColumn(String columnName, Object DataType)
{
this.ColumnName = columnName;
this.oldColumnName = columnName;
this.DataType = DataType;
}
//区分大小写
public DataColumn(String columnName, Object DataType, boolean cases)
{
this.ColumnName = columnName;
this.oldColumnName = columnName;
this.DataType = DataType;
}
public DataColumn(String columnName, Object DataType, String str)
{
this.ColumnName = columnName;
this.oldColumnName = columnName;
this.DataType = DataType;
}
/**
* 給DataColumnCollection加入DataColumn時設定所屬的DataTable的方法,同一個package才用到
*
* param table
*/
void setTable(DataTable table)
{
this.table = table;
}
/**
* 取得DataColumn所屬的DataTable,唯讀
*
* @return DataTable
*/
public DataTable getTable()throws Exception
{
return this.table;
}
/**
* DataColumn物件的toString(),會回傳自己的欄名
*
* @return
*/
@Override
public String toString() {
return this.ColumnName;
}
private int ordinal;
public void setOrdinal(int ordinal) {
this.ordinal = ordinal;
}
public int getOrdinal() {
return ordinal;
}
public final Properties ExtendedProperties = new Properties();
public static class Properties {
private Map<Object, Object> properties = new HashMap<Object, Object>();
public void Add(Object key, Object value) {
this.properties.put(key, value);
}
public boolean ContainsKey(Object key) {
return this.properties.containsKey(key);
}
public Object get(Object key) {
return this.properties.get(key);
}
}
}
package bp.da;
import java.util.LinkedHashMap;
import bp.tools.StringUtils;
public class DataRow extends LinkedHashMap<String, Object>
{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* 此資料列所屬的DataTable,唯讀
*/
public transient DataTable table;
/**
* 在getValue()和setValue()時候,程式碼須透過此成員的欄位名稱來找出Map字典裡的物件
*/
public transient DataColumnCollection columns;
public transient Object ItemArray;
public Object getItemArray() {
return ItemArray;
}
public void setItemArray(Object itemArray) {
ItemArray = itemArray;
}
/**
* DataRow被建立時,必須指定所屬的DataTable
*
* param table
*/
public DataRow(DataTable table)
{
this.table = table;
this.columns = table.Columns;
}
/**
* 取得DataRow所屬的DataTable
*
* @return DataTable
*/
public DataTable getTable()throws Exception
{
return this.table;
}
/**
* 設定該列該行的值
*
* param columnIndex
* 行索引(從0算起)
* param value
* 要設定的值
*/
public void setValue(int columnIndex, Object value)
{setValue(this.columns.get(columnIndex), value);
}
public void setDataType(int columnIndex, Object dataType)
{
this.columns.get(columnIndex).setDataType(dataType);
}
/**
* 設定該列該行的值
*
* param columnName
* 行名稱
* param value
* 要設定的值
*/
public void setValue(String columnName, Object value)
{this.put(columnName, value);
// this.put(columnName, value);
}
public void setValue(String columnName, Boolean value)
{if (value==true)
this.put(columnName, 1);
else
this.put(columnName, 0);
// this.put(columnName, value);
}
public void setValueStr(String columnName, String value)
{this.put(columnName, "\""+value+"\"");
// this.put(columnName, value);
}
/**
* 設定該列該行的值 区分大小写
*
* param columnName
* 行名稱
* param value
* 要設定的值
*/
public void setValue2017(String columnName, Object value)
{this.put(columnName, value);
}
/**
* 設定該列該行的值
*
* param column
* DataColumn物件
* param value
* 要設定的值
*/
public void setValue(DataColumn column, Object value)
{if (column != null)
{
String lowerColumnName = column.ColumnName;
if (this.containsKey(lowerColumnName))
this.remove(lowerColumnName);
this.put(lowerColumnName, value);
}
}
/**
* 区分大小写
*
* param column
* param value
*/
public void setValue_UL(DataColumn column, Object value)throws Exception
{if (column != null)
{
String lowerColumnName = column.ColumnName;
// String lowerColumnName = column.ColumnName;
if (this.containsKey(lowerColumnName))
this.remove(lowerColumnName);
this.put(lowerColumnName, value);
}
}
/**
* 取得該列該行的值
*
* param columnIndex
* 行索引(從0算起)
* @return Object
*/
public Object getValue(int columnIndex)
{
Object obj = this.get(this.columns.get(columnIndex).ColumnName);
if (obj == null)
{
obj = "";
}
return obj;
// return
// this.get(this.columns.get(columnIndex).ColumnName.toLowerCase());
}
/**
* 取得該列該行的值
*
* param columnName
* 行名稱
* @return Object
*/
public Object getValue(String columnName)
{
Object obj = this.get(columnName);
if (obj == null)
{
if(!DataType.IsNullOrEmpty(this.get(columnName.toLowerCase())))
return this.get(columnName.toLowerCase());
if(!DataType.IsNullOrEmpty(this.get(columnName.toUpperCase())))
return this.get(columnName.toUpperCase());
return "";
}
return obj;
}
/**
* 取得該列該行的值
*
* param column
* DataColumn物件
* @return Object
*/
public Object getValue(DataColumn column)
{
Object obj = this.get(column.ColumnName);
if (obj == null)
{
obj = "";
}
return obj;
}
public void set(String string, Object object) {
if (object==null)
object="";
this.set(string, object.toString());
}
}
package bp.da;
import java.util.ArrayList;
import java.util.Map;
import bp.difference.SystemConfig;
public class DataRowCollection extends ArrayList<DataRow>
{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* DataRowCollection所屬的DataTable,唯讀
*/
private transient DataTable Table;
/**
* DataRowCollection被建立時,一定要指定所屬的DataTable
*
* param table
*/
public DataRowCollection(DataTable table)
{
this.Table = table;
}
/**
* 取得所屬的DataTable
*
* @return DataTable
*/
public DataTable getTable()throws Exception
{
return this.Table;
}
public DataRow AddRow(DataRow vals)
{
return AddRow(vals,-1);
}
public DataRow AddRow(DataRow vals, int idx){
if (vals==null)
return null;
DataRow row = new DataRow(Table);
Map ap= ((Map<String, Object>) vals);
for(DataColumn dc : Table.Columns)
{
String key= dc.ColumnName;
String valStr=String.valueOf( ap.get(key));
if((DataType.IsNullOrEmpty(valStr) ||"null".equals(valStr))
&& SystemConfig.AppCenterDBFieldCaseModel() == FieldCaseModel.Lowercase){
valStr=String.valueOf( ap.get(key.toLowerCase()));
}
if (valStr==null)
valStr="";
row.setValue(key, valStr);
}
if (idx==-1)
this.add(row);
else
this.add(row);
return row;
}
public DataRow AddDatas(Object... vals){
if (vals==null)
return null;
DataRow row = new DataRow(Table);
int i=0;
for (Object val : vals) {
String key = Table.Columns.get(i++).ColumnName;
Object value;
if (val instanceof Map) {
value = ((Map<String, Object>) val).get(key);
} else {
value = val;
}
if (value==null)
value="";
row.put(key, value);
}
this.add(row);
return row;
}
}
Data:
package bp.da;
import java.io.*;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import bp.difference.SystemConfig;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.core.io.ClassPathResource;
public class DataSet {
private String name;
public List<DataTable> Tables;
public Hashtable<String, DataTable> hashTables;
public DataSet() {
if (Tables == null) {
Tables = new ArrayList<DataTable>();
hashTables = new Hashtable<String, DataTable>();
}
}
public boolean removeTableByName(String tableName)
{
for (DataTable dtb : this.Tables)
{
if( tableName.equals(dtb.getTableName()))
{
this.Tables.remove(dtb);
return true;
}
}
return false;
}
public DataTable GetTableByName(String tableName)
{
for (DataTable dtb : this.Tables)
{
if( tableName.equals(dtb.getTableName()))
{
return dtb;
}
}
return null;
}
/**
* 判断DataSet中是否包含指定的名称的DataTable数据
* @param tableName
* @return
*/
public boolean contains(String tableName){
boolean isHave=false;
for (DataTable dtb : this.Tables)
{
if( tableName.equals(dtb.getTableName()))
{
isHave = true;
break;
}
}
return isHave;
}
public DataSet(String name) {
if (Tables == null) {
Tables = new ArrayList<DataTable>();
hashTables = new Hashtable<String, DataTable>();
}
}
/**
* DataSet 以xml形式写入文件
*
* param file
* @throws Exception
*/
public void WriteXml(String file) {
WriteXml(file, XmlWriteMode.IgnoreSchema, new DataSet("NewDataSet"));
}
/**
* DataSet 以xml形式写入文件
*
* param path
* param mode
* 暂不支持DiffGram格式
* @throws Exception
*/
public void WriteXml(String path, XmlWriteMode mode, DataSet ds) {
StringBuilder str = new StringBuilder("<?xml version=\"1.0\" standalone=\"yes\"?>");
str.append("<NewDataSet>");
// 输出表架构
for (int i = 0; i < ds.Tables.size(); i++) {
DataTable dt = ds.Tables.get(i);
for (int k = 0; k < dt.Rows.size(); k++) {
str.append("<");
str.append(dt.getTableName());
str.append(">");
for (int j = 0; j < dt.Columns.size(); j++) {
DataColumn dc = dt.Columns.get(j);
str.append("<");
str.append(dc.ColumnName);
str.append(">");
try {
Object value = dt.Rows.get(k).getValue(dc);
if (value.toString().contains(">") || value.toString().contains("<") || value.toString().contains("&")
|| value.toString().contains("'") || value.toString().contains("\"")) {
value = value.toString().replace(">", ">");
value = value.toString().replace("<", "<");
value = value.toString().replace("&", "&");
value = value.toString().replace("'", "'");
value = value.toString().replace("\"", """);
}
str.append(value);
} catch (Exception e) {
}
str.append("</");
str.append(dc.ColumnName);
str.append(">");
}
str.append("</");
str.append(dt.getTableName());
str.append(">");
}
}
// }
str.append("</NewDataSet>");
String temp = str.toString();
int pathType=0;
if(path.startsWith("resources")==true)
pathType = 1;
if(SystemConfig.getIsJarRun() && pathType==1){
}
// 写入文件
File file = new File(path);
try {
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");
BufferedWriter br = new BufferedWriter(osw);
br.write(temp.toString());
fos.flush();
br.close();
fos.close();
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public String formatXml(String str) throws Exception {
Document document = null;
document = DocumentHelper.parseText(str);
// 格式化输出格式
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("gbk");
StringWriter writer = new StringWriter();
// 格式化输出流
XMLWriter xmlWriter = new XMLWriter(writer, format);
// 将document写入到输出流
xmlWriter.write(document);
xmlWriter.close();
return writer.toString();
}
public void readXmls(String xmlPath) throws Exception {
if (DataType.IsNullOrEmpty(xmlPath)) {
return;
}
SAXReader reader = new SAXReader();
File file = new File(xmlPath);
// DataSet ds=new DataSet();
if (file.exists()) {
Document document = reader.read(file);// 读取XML文件
Element root = document.getRootElement();// 得到根节点
for (Iterator i = root.elementIterator(); i.hasNext();) {
Element e = (Element) i.next();
boolean type = false;
for (int k = 0; k < this.Tables.size(); k++) {
if (this.Tables.get(k).TableName.equals(e.getName())) {
DataTable dt = this.Tables.get(k);
DataRow dr = dt.NewRow();
DataColumn dc = null;
for (Iterator j = e.elementIterator(); j.hasNext();) {
Element cn = (Element) j.next();
dc = new DataColumn(cn.getName());
dr.setValue(dc, cn.getText());
}
dt.Columns.Add(dc);
dt.Rows.add(dr);
type = true;
break;
}
}
if (type) {
continue;
}
DataTable dt = new DataTable(e.getName());
DataRow dr = dt.NewRow();
DataColumn dc = null;
for (Iterator j = e.elementIterator(); j.hasNext();) {
Element cn = (Element) j.next();
dc = new DataColumn(cn.getName());
dt.Columns.Add(dc);
dr.setValue(dc, cn.getText());
}
dt.Rows.add(dr);
this.Tables.add(dt);
this.hashTables.put(e.getName(), dt);
}
}
}
public void readXmlm(String xml) {
if (DataType.IsNullOrEmpty(xml))
return;
try {
xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n <NewDataSets>" + xml + "</NewDataSets>";
// 创建xml解析对象
SAXReader reader = new SAXReader();
// 定义一个文档
Document document = null;
// 将字符串转换为
document = reader.read(new ByteArrayInputStream(xml.getBytes("UTF-8")));
@SuppressWarnings("unchecked")
List<Element> elements = document.selectNodes("//NewDataSets/NewDataSet");
int i = 0;
DataTable oratb = new DataTable();
for (Element element : elements) {
DataRow dr = oratb.NewRow();
@SuppressWarnings("unchecked")
Iterator<Element> iter = element.elementIterator();
int j = 0;
while (iter.hasNext()) {
Element itemEle = (Element) iter.next();
if (i == 0) {
oratb.Columns.Add(itemEle.getName());
}
dr.setValue(j, itemEle.getTextTrim());
j++;
}
oratb.Rows.add(dr);
i++;
}
this.Tables.add(oratb);
} catch (Exception e) {
e.printStackTrace();
}
}
public String getName() {
return name;
}
public void setName(String name) throws Exception {
this.setName( name);
}
public List<DataTable> getTables() {
return Tables;
}
public void setTables(List<DataTable> tables) {
Tables = tables;
}
public Hashtable<String, DataTable> getHashTabless() {
return hashTables;
}
public void setHashTables(Hashtable<String, DataTable> hashTables) {
this.hashTables = hashTables;
}
/**
* 获取文件的XML文件内容。
* param path xml文件路径
* @return xml文件内容
*/
public String xmlToString(String path) throws Exception {
String line = null;
StringBuffer strBuffer = new StringBuffer();
int pathType =0;
if((path.indexOf("DataUser/")!=-1 &&path.indexOf("DataUser/Siganture/")==-1 && path.indexOf("DataUser/UploadFile/")==-1 &&
path.indexOf("DataUser/FlowDesc/")==-1 && path.indexOf("DataUser/Temp/")==-1 )|| path.indexOf("WF/")!=-1)
pathType =1;
try {
String encoding = "UTF-8"; // 字符编码
if(SystemConfig.getIsJarRun() && pathType==1){
ClassPathResource classPathResource = new ClassPathResource(path);
InputStream inputStream = classPathResource.getInputStream();
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, encoding));
StringBuffer buffer = new StringBuffer();
while ((line = bufferedReader.readLine()) != null){
buffer.append(line + "\n");
}
bufferedReader.close();
return buffer.toString();
}else{
File file = new File(path);
if (file.isFile() && file.exists()) {
InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
BufferedReader bufferedReader = new BufferedReader(read);
while ((line = bufferedReader.readLine()) != null) {
strBuffer.append(line + "\n");
}
read.close();
} else {
throw new Exception("找不到指定的文件"+path+",请联系管理员查看环境配置是否正确,jflow.properties中的配置是否正确");
}
}
} catch (Exception e) {
throw new Exception("读取文件内容操作出错!" + e.getMessage());
}
return strBuffer.toString();
}
/**
* 读取XML文件
* param xmlpath xml文件路径
* @author ThinkGem
*/
@SuppressWarnings("rawtypes")
public void readXml(String xmlpath) {
if (DataType.IsNullOrEmpty(xmlpath)){
return;
}
try {
String xml = xmlToString(xmlpath);
Document document = new SAXReader().read(new ByteArrayInputStream(xml.getBytes("UTF-8")));
Element element = document.getRootElement();
// 遍历 DataTable
for (Iterator iterator = element.elementIterator(); iterator.hasNext();) {
Element el = (Element) iterator.next();
// System.out.println(" ===================== " + el.getName());
// 如果没有获取到DataTable则新建一个
DataTable dt = hashTables.get(el.getName());
if (dt == null){
dt = new DataTable(el.getName());
hashTables.put(el.getName(), dt);
Tables.add(dt);
}
// 新增一行数据
DataRow dr = dt.NewRow();
dt.Rows.add(dr);
// 遍历该DataTable的属性
for (Iterator it = el.attributeIterator(); it.hasNext();) {
Attribute at = (Attribute)it.next();
// System.out.println(" ======= " + at.getName());
//sunxd 修改
//由于"at.getName().toLowerCase()"语句导至 isContains 方法判断永远不成立,会给TABLE插入很多重复列
//将at.getName().toLowerCase() 修改为 at.getName()
if (!iscontains(dt.Columns.subList(0, dt.Columns.size()), at.getName())) {
dt.Columns.Add(at.getName());
}
dr.setValue(at.getName(), at.getValue());
}
// 遍历该DataTable的子元素
for (Iterator it = el.elementIterator(); it.hasNext();) {
Element at = (Element) it.next();
if (!iscontains(dt.Columns.subList(0, dt.Columns.size()), at.getName())) {
dt.Columns.Add(at.getName());
}
String value = at.getText();
try {
//导出模板进行了转义,现在进行反转 dgq 2018-7-5
if (value.toString().contains(">") || value.toString().contains("<")
|| value.toString().contains("&") || value.toString().contains("'")
|| value.toString().contains(""")) {
value = value.toString().replace("&", "&");
value = value.toString().replace(">",">");
value = value.toString().replace("<","<");
value = value.toString().replace("'","'");
value = value.toString().replace(""","\"");
}
} catch (Exception e) {
}
dr.setValue(at.getName(), value);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean iscontains(List<DataColumn> dcList, String column) {
for (DataColumn dc : dcList) {
if (dc.ColumnName.equals(column)) {
return true;
}
}
return false;
}
public static String ConvertDataSetToXml(DataSet dataSet) {
if (dataSet != null) {
String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
str += "<xs:schema id=\"NewDataSet\" xmlns=\"\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">";
str += "<xs:element name=\"NewDataSet\" msdata:IsDataSet=\"true\" msdata:UseCurrentLocale=\"true\">";
str += "<xs:complexType><xs:choice minOccurs=\"0\" maxOccurs=\"unbounded\">";
// 循环每一个表的列
for (int n = 0; n < dataSet.getTables().size(); n++) {
str += "<xs:element name=\"" + dataSet.getTables().get(n).TableName + "\">";
str += "<xs:complexType><xs:sequence>";
DataTable table = dataSet.getTables().get(n);
for (DataColumn col : table.Columns) {
str += "<xs:element name=\"" + col.ColumnName;
str += "\" type=\"";
try {
col.DataType.toString();
str += IsType(col.DataType.toString());
} catch (Exception e) {
str += "xs:string";
}
str += "\" minOccurs=\"0\" />";
}
str += "</xs:sequence></xs:complexType></xs:element>";
}
str += "</xs:choice></xs:complexType></xs:element><_NewDataSet>";
for (int i = 0; i < dataSet.getTables().size(); i++) {
DataTable dt = dataSet.getTables().get(i);
DataTable table = dataSet.getTables().get(i);
for (int j = 0; j < table.Rows.size(); j++) {
str += "<_" + i + ">";
DataRow row = table.Rows.get(j);
for (int a = 0; a < row.columns.size(); a++) {
DataColumn col = table.Columns.get(a);
str += "<_" + a + ">";
if (row.getValue(col) == null) {
str += "";
} else {
if (col.ColumnName.equals("icon")) {
if (row.getValue(col).equals("")) {
str += "审核";
} else if (row.getValue(col).equals("Default")) {
str += "审核";
} else {
str += row.getValue(col);
}
} else {
str += row.getValue(col);
}
}
str += "</_" + a + ">";
}
str += "</_" + i + ">";
}
}
str += "</_NewDataSet>";
str += "</xs:schema>";
return str;
}
return null;
}
public static String IsType(String name) throws Exception {
if (name.equals("class java.lang.Integer")) {
name = "xs:int";
}
if (name.equals("class java.lang.Long")) {
name = "xs:long";
}
if (name.equals("class java.lang.Float")) {
name = "xs:float";
}
if (name.equals("class java.lang.Double")) {
name = "xs:double";
}
if (name.equals("class java.lang.String")) {
name = "xs:string";
}
if (name.equals("class java.math.BigDecimal")) {
name = "xs:int";
}
return name;
}
}
package bp.da;
import bp.difference.SystemConfig;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.core.io.ClassPathResource;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class DataTable implements Cloneable
{
/**
* 保存DataRow的集合,在DataTable初始化時,便會建立
*/
public DataRowCollection Rows;
/**
* 保存DataColumn的集合,在DataTable初始化時,便會建立
*/
public DataColumnCollection Columns;
/**
* DataTable的名稱,沒什麼用到
*/
public String TableName;
private DataRow[] dataRows;
/**
* @return 复制DataTable的结构
*/
public DataTable clone(){
try
{
DataTable v = new DataTable();
for(DataColumn Column: this.Columns){
v.Columns.Add(Column.ColumnName,Column.DataType);
}
return v;
} catch (Exception e)
{
throw new InternalError();
}
}
/**
* @return 复制DataTable的结构与数据。
* @throws CloneNotSupportedException
*/
public DataTable copy()
{
try
{
DataTable v = (DataTable) super.clone();
v.Rows = (DataRowCollection) this.Rows.clone();
v.Columns = (DataColumnCollection) this.Columns.clone();
return v;
} catch (CloneNotSupportedException e)
{
throw new InternalError();
}
}
/**
* 初始化DataTable,並建立DataColumnCollection,DataRowCollection
*/
public DataTable() {
this.Columns = new DataColumnCollection(this);
this.Rows = new DataRowCollection(this);
}
/**
* 除了初始化DataTable, 可以指定DataTable的名字(沒什麼意義)
*
* param tableName DataTable的名字
*/
public DataTable(String tableName) {
this();
this.TableName = tableName;
}
/**
* 由此DataTable物件來建立一個DataRow物件
*
* @return DataRow
*/
public DataRow NewRow()
{
DataRow row = new DataRow(this);// DataRow為呼叫此方法DataTable的成員
return row;
}
/**
* 把DataTable當做二維陣列,給列索引和行索引,設定值的方法 <br/>
* (發佈者自行寫的方法)
*
* param rowIndex
* 列索引(從0算起)
* param columnIndex
* 行索引(從0算起)
* param value
* 要給的值
*/
public void setValue(int rowIndex, int columnIndex, Object value)throws Exception
{this.Rows.get(rowIndex).setValue(columnIndex, value);
}
/**
* 把DataTable當做二維陣列,給列索引和行名稱,設定值的方法 <br/>
* (發佈者自行寫的方法)
*
* param rowIndex 列索引(從0算起)
* param columnName 行名稱
* param value 要給的值
*/
public void setValue(int rowIndex, String columnName, Object value)throws Exception
{this.Rows.get(rowIndex).setValue(columnName.toLowerCase(), value);
}
/**
* 把DataTable當做二維陣列,給列索引和行索引,取得值的方法 <br/>
* (發佈者自行寫的方法)
*
* param rowIndex
* 列索引(從0算起)
* param columnIndex
* 行索引(從0算起)
* @return 回傳該位置的值
*/
public Object getValue(int rowIndex, int columnIndex)
{
return this.Rows.get(rowIndex).getValue(columnIndex);
}
public void Clear()
{
Rows.clear();
Columns.clear();
}
public void ClearRow()throws Exception
{
Rows.clear();
}
public List<DataRow> Select(Map<String, Object> filterMap) throws Exception {
List<DataRow> dataRowList = new ArrayList<DataRow>();
outer: for (int i = 0; i < Rows.size(); i++)
{
DataRow row = Rows.get(i);
for (Object key : filterMap.keySet().toArray())
{
Object lefteql = filterMap.get(key);
Object righteql = row.getValue(key.toString());
if (lefteql == null || "".equals(lefteql))
{
if (righteql == null || "".equals(righteql))
{
continue;
} else
{
continue outer;
}
} else if (!filterMap.get(key).toString().toUpperCase().equals(
row.getValue(key.toString()).toString().toUpperCase()))
{
continue outer;
}
}
dataRowList.add(row);
}
return dataRowList;
}
/**
* 返回符合过滤条件的数据行集合,并返回
* param filterString 过滤字符串,例如 a>1 and a>=2 or a<3 and a<=4 or a!=5 and a=6 or a!='b' and a='c'
* @return 过滤后的 List<DataRow>
*/
public List<DataRow> select(String filterString) {
List<DataRow> rows = new ArrayList<DataRow>();
if (DataType.IsNullOrEmpty(filterString) == true)
return this.Rows;
boolean bl;
for (Object row : this.Rows) {
DataRow currentRow = (DataRow) row;
try {
bl = dataRowCompute(filterString, currentRow);
} catch (Exception e) {
System.err.println("语法错误");
e.printStackTrace();
continue;
}
if (bl) {
rows.add(currentRow);
}
}
return rows;
}
/**
* 返回符合过滤条件的数据行集合,并返回
* param filterString 过滤字符串,例如 a>1 and a>=2 or a<3 and a<=4 or a!=5 and a=6 or a!='b' and a='c'
* @return 过滤后的 List<DataRow>
*/
public List<DataRow> selectx(String filterString) {
List<DataRow> rows = new ArrayList<DataRow>();
if (DataType.IsNullOrEmpty(filterString) == true)
return rows;
boolean bl = false;
for (Object row : Rows) {
DataRow currentRow = (DataRow) row;
try {
//bl = dataRowCompute(filterString, currentRow);
if(filterString.split("=").length>1)
bl = currentRow.getValue(filterString.split("=")[0].trim()).equals(filterString.split("=")[1].trim());
} catch (Exception e) {
System.err.println("语法错误");
e.printStackTrace();
continue;
}
if (bl) {
rows.add(currentRow);
}
}
return rows;
}
/**
* 数据行计算,是否符合filterString过滤条件
* param filterString 过滤条件,支持 and or > >= < <= != = 操作符,暂不支持括号
* param row 数据行
* @return true 符合
*/
private boolean dataRowCompute(String filterString, DataRow row){
if (filterString == null || row == null){
return false;
}
boolean orResult = false;
try {
String[] or = filterString.split(" (?i)or "); // 忽略大小写
for (String o : or){
boolean andResult = true;
String[] and = o.split(" (?i)and "); // 忽略大小写
for (String a : and){
String[] kv = null;
if (a.contains(">=")){
kv = a.split(">=");
}else if (a.contains(">")){
kv = a.split(">");
}else if (a.contains("<=")){
kv = a.split("<=");
}else if (a.contains("<")){
kv = a.split("<");
}else if (a.contains("!=")){
kv = a.split("!=");
}else if (a.contains("=")){
kv = a.split("=");
}
if (kv != null && kv.length == 2){
String key = kv[0].trim(), value = kv[1].trim();
if (key != null && value != null){
Object val = row.getValue(key);
// is null
if (value.equalsIgnoreCase("is null")){
if (!(val == null)){
andResult = false;
break;
}
}
// is not null
else if (value.equalsIgnoreCase("is not null")){
if (!(val != null)){
andResult = false;
break;
}
}
// is string
else if (value.startsWith("'") && value.endsWith("'")){
String v = value.replaceAll("'", "");
if (a.contains("!=")){
if (!(!val.toString().equalsIgnoreCase(v))){
andResult = false;
break;
}
}else if (a.contains("=")){
if (!(val.toString().equalsIgnoreCase(v))){
andResult = false;
break;
}
}
}
// is number
else{
int v = Integer.parseInt(value.toString());
int dbVal = Integer.parseInt(val.toString());
if (a.contains(">=")){
if (!(dbVal >= v)){
andResult = false;
break;
}
}else if (a.contains(">")){
if (!(dbVal > v)){
andResult = false;
break;
}
}else if (a.contains("<=")){
if (!(dbVal <= v)){
andResult = false;
break;
}
}else if (a.contains("<")){
if (!(dbVal < v)){
andResult = false;
break;
}
}else if (a.contains("!=")){
if (!(dbVal != v)){
andResult = false;
break;
}
}else if (a.contains("=")){
if (!(dbVal == v)){
andResult = false;
break;
}
}
}
}
}
}
// 如果有一个and成立,则成立。
if (andResult){
orResult = true;
break;
}
}
} catch (Exception e) {
System.err.println("语法错误");
e.printStackTrace();
}
return orResult;
}
public String getTableName() {
return TableName;
}
public void setTableName(String tableName) {
TableName = tableName;
}
/**
* 把DataTable當做二維陣列,給列索引和行名稱,取得值的方法 <br/>
* (發佈者自行寫的方法)
*
* param rowIndex 列索引(從0算起)
* param columnName 行名稱
* @return 回傳該位置的值
*/
public Object getValue(int rowIndex, String columnName)
{
return this.Rows.get(rowIndex).getValue(columnName);
}
public DataRow[] Select(String string) {
DataRow[] dataRowsx = null;
List<DataRow> dataRowList = new ArrayList<DataRow>();
if (DataType.IsNullOrEmpty(string)==false) {
boolean bl;
for (Object row : Rows) {
DataRow currentRow = (DataRow) row;
try {
bl = dataRowCompute(string, currentRow);
} catch (Exception e) {
System.err.println("语法错误");
e.printStackTrace();
continue;
}
if (bl) {
dataRowList.add(currentRow);
}
}
dataRowsx = new DataRow[dataRowList.size()];
for(int i=0;i<dataRowList.size();i++){
dataRowsx[i] = dataRowList.get(i);
}
return dataRowsx;
} else {
return dataRowsx;
}
}
public void WriteXml(String path, DataTable dt) {
StringBuilder str = new StringBuilder("<?xml version=\"1.0\" standalone=\"yes\"?>");
str.append("<DataTable>");
for (int k = 0; k < dt.Rows.size(); k++) {
str.append("<");
str.append(dt.getTableName());
str.append(">");
for (int j = 0; j < dt.Columns.size(); j++) {
DataColumn dc = dt.Columns.get(j);
str.append("<");
str.append(dc.ColumnName);
str.append(">");
try {
Object value = dt.Rows.get(k).getValue(dc);
if (value.toString().contains(">") || value.toString().contains("<") || value.toString().contains("&")
|| value.toString().contains("'") || value.toString().contains("\"")) {
value = value.toString().replace(">", ">");
value = value.toString().replace("<", "<");
value = value.toString().replace("&", "&");
value = value.toString().replace("'", "'");
value = value.toString().replace("\"", """);
}
str.append(value);
} catch (Exception e) {
}
str.append("</");
str.append(dc.ColumnName);
str.append(">");
}
str.append("</");
str.append(dt.getTableName());
str.append(">");
}
str.append("</DataTable>");
// }
String temp = str.toString();
// String temp = formatXml(str.toString());
// 写入文件
File file = new File(path);
try {
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");
BufferedWriter br = new BufferedWriter(osw);
br.write(temp.toString());
fos.flush();
br.close();
fos.close();
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取文件的XML文件内容。
* param path xml文件路径
* @return xml文件内容
*/
public String xmlToString(String path) throws Exception {
String line = null;
StringBuffer strBuffer = new StringBuffer();
int pathType =0;
if(path.indexOf("DataUser/")!=-1 || path.indexOf("WF/")!=-1)
pathType =1;
try {
String encoding = "UTF-8"; // 字符编码
if(SystemConfig.getIsJarRun() && pathType==1){
ClassPathResource classPathResource = new ClassPathResource(path);
InputStream inputStream = classPathResource.getInputStream();
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, encoding));
StringBuffer buffer = new StringBuffer();
while ((line = bufferedReader.readLine()) != null){
buffer.append(line + "\n");
}
bufferedReader.close();
return buffer.toString();
}else{
File file = new File(path);
if (file.isFile() && file.exists()) {
InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
BufferedReader bufferedReader = new BufferedReader(read);
while ((line = bufferedReader.readLine()) != null) {
strBuffer.append(line + "\n");
}
read.close();
} else {
throw new Exception("找不到指定的文件"+path+",请联系管理员查看环境配置是否正确,jflow.properties中的配置是否正确");
}
}
} catch (Exception e) {
throw new Exception("读取文件内容操作出错!" + e.getMessage());
}
return strBuffer.toString();
}
public boolean iscontains(List<DataColumn> dcList, String column) {
for (DataColumn dc : dcList) {
if (dc.ColumnName.equals(column)) {
return true;
}
}
return false;
}
/**
* 读取XML文件
* param xmlpath xml文件路径
* @author ThinkGem
*/
@SuppressWarnings("rawtypes")
public DataTable readXml(String xmlpath) {
if (DataType.IsNullOrEmpty(xmlpath)){
return null;
}
try {
String xml = xmlToString(xmlpath);
Document document = new SAXReader().read(new ByteArrayInputStream(xml.getBytes("UTF-8")));
Element root = document.getRootElement();
DataTable dt = new DataTable(root.getName());
DataRow dr = null;
for (Iterator i = root.elementIterator(); i.hasNext();){
Element element = (Element) i.next();
dr = dt.NewRow();
// 遍历该DataTable的属性
for (Iterator it = element.attributeIterator(); it.hasNext();) {
Attribute at = (Attribute)it.next();
// System.out.println(" ======= " + at.getName());
//sunxd 修改
//由于"at.getName().toLowerCase()"语句导至 isContains 方法判断永远不成立,会给TABLE插入很多重复列
//将at.getName().toLowerCase() 修改为 at.getName()
if (!iscontains(dt.Columns.subList(0, dt.Columns.size()), at.getName())) {
dt.Columns.Add(at.getName());
}
dr.setValue(at.getName(), at.getValue());
}
// 遍历该DataTable的子元素
for (Iterator it = element.elementIterator(); it.hasNext();) {
Element at = (Element) it.next();
if (!iscontains(dt.Columns.subList(0, dt.Columns.size()), at.getName())) {
dt.Columns.Add(at.getName());
}
String value = at.getText();
try {
//导出模板进行了转义,现在进行反转 dgq 2018-7-5
if (value.toString().contains(">") || value.toString().contains("<")
|| value.toString().contains("&") || value.toString().contains("'")
|| value.toString().contains(""")) {
value = value.toString().replace("&", "&");
value = value.toString().replace(">",">");
value = value.toString().replace("<","<");
value = value.toString().replace("'","'");
value = value.toString().replace(""","\"");
}
} catch (Exception e) {
}
dr.setValue(at.getName(), value);
}
dt.Rows.add(dr);
}
return dt;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
参考资料和推荐阅读
- 暂无
欢迎阅读,各位老铁,如果对你有帮助,点个赞加个关注呗!~
如有侵权,请联系删除之