rabbitmq + historymanager + redismanager
com.dx.mes.common.bean.entity.HisXml
package com.dx.mes.common.bean.entity;
import java.io.Serializable;
public class HisXml implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private TableHistoryConfig tableHistoryConfig;
private String xml;
public TableHistoryConfig getTableHistoryConfig() {
return tableHistoryConfig;
}
public void setTableHistoryConfig(TableHistoryConfig tableHistoryConfig) {
this.tableHistoryConfig = tableHistoryConfig;
}
public String getXml() {
return xml;
}
public void setXml(String xml) {
this.xml = xml;
}
public HisXml() {
}
public HisXml(TableHistoryConfig tableHistoryConfig, String xml) {
super();
this.tableHistoryConfig = tableHistoryConfig;
this.xml = xml;
}
@Override
public String toString() {
return "HisXml [tableHistoryConfig=" + tableHistoryConfig + ", xml=" + xml + "]";
}
}
com.dx.mes.common.bean.entity.TableHistoryConfig
package com.dx.mes.common.bean.entity;
import java.io.Serializable;
public class TableHistoryConfig implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String opeTableName;
private boolean hasToSendHis;
private String queueName;
private String errorQueueName;
private String pptTableName;
private String hisTableName;
public String getOpeTableName() {
return opeTableName;
}
public void setOpeTableName(String opeTableName) {
this.opeTableName = opeTableName;
}
public boolean isHasToSendHis() {
return hasToSendHis;
}
public void setHasToSendHis(boolean hasToSendHis) {
this.hasToSendHis = hasToSendHis;
}
public String getQueueName() {
return queueName;
}
public void setQueueName(String queueName) {
this.queueName = queueName;
}
public String getErrorQueueName() {
return errorQueueName;
}
public void setErrorQueueName(String errorQueueName) {
this.errorQueueName = errorQueueName;
}
public String getPptTableName() {
return pptTableName;
}
public void setPptTableName(String pptTableName) {
this.pptTableName = pptTableName;
}
public String getHisTableName() {
return hisTableName;
}
public void setHisTableName(String hisTableName) {
this.hisTableName = hisTableName;
}
}
com.dx.mes.common.bean.entity.UUIDObject
package com.dx.mes.common.bean.entity;
public class UUIDObject {
protected String pv_unq_seq_id;
protected String sequence;
protected String unq_seq_id;
protected String operation;
protected String ope_tbl_name;
protected Double sta_time_d;
protected String ope_evt_name;
protected String ope_evt_node;
protected String ope_evt_usr;
protected String ope_evt_no;
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
public String getOpe_tbl_name() {
return ope_tbl_name;
}
public void setOpe_tbl_name(String ope_tbl_name) {
this.ope_tbl_name = ope_tbl_name;
}
public Double getSta_time_d() {
return sta_time_d;
}
public void setSta_time_d(Double sta_time_d) {
this.sta_time_d = sta_time_d;
}
public String getOpe_evt_name() {
return ope_evt_name;
}
public void setOpe_evt_name(String ope_evt_name) {
this.ope_evt_name = ope_evt_name;
}
public String getOpe_evt_node() {
return ope_evt_node;
}
public void setOpe_evt_node(String ope_evt_node) {
this.ope_evt_node = ope_evt_node;
}
public String getOpe_evt_usr() {
return ope_evt_usr;
}
public void setOpe_evt_usr(String ope_evt_usr) {
this.ope_evt_usr = ope_evt_usr;
}
public String getOpe_evt_no() {
return ope_evt_no;
}
public void setOpe_evt_no(String ope_evt_no) {
this.ope_evt_no = ope_evt_no;
}
public String getPv_unq_seq_id() {
return pv_unq_seq_id;
}
public void setPv_unq_seq_id(String pv_unq_seq_id) {
this.pv_unq_seq_id = pv_unq_seq_id;
}
public String getSequence() {
return sequence;
}
public void setSequence(String sequence) {
this.sequence = sequence;
}
public String getUnq_seq_id() {
return unq_seq_id;
}
public void setUnq_seq_id(String unq_seq_id) {
this.unq_seq_id = unq_seq_id;
}
}
com.dx.mes.common.transcoder.util.AppContext
package com.dx.mes.common.transcoder.util;
public class AppContext {
private static ThreadLocal<String> currServiceName = new ThreadLocal<String>();
private static ThreadLocal<String> currEventNumber = new ThreadLocal<String>();
public static String getCurrServiceName() {
return (String) currServiceName.get();
}
public static void setCurrServiceName(String serviceName) {
currServiceName.set(serviceName);
}
public static String getCurrEventNumber() {
return (String) currEventNumber.get();
}
public static void setCurrEventNumber(String eventNo) {
currEventNumber.set(eventNo);
}
public static void clear() {
currServiceName.set(null);
currEventNumber.set(null);
}
}
com.dx.mes.common.transcoder.util.GUIDGenerator
package com.dx.mes.common.transcoder.util;
import java.util.UUID;
import java.math.BigInteger;
public class GUIDGenerator {
/**
* This is 1 followed by 25 0. This is used to make sure the string generated
* is always 26 chars long.
*/
private static final String PADDING_STRING = "0000000000000000000000000";
public static final String DEFAULT_PADDING_PREFIX = "X";
private static int TOTAL_GUID_LENGTH = 26;
/**
* @return Generate fix lenght 26 char GUID.
* Currently the using the java GUID Generator based on pseudo random number.
* The GUID generated by java can be from 22-25 char long, prepending the value with
* prefix followed by any number of 0s to make the the GUID 26 char long.
* if the prefix is a white space (trimmable char), then the default prefix X is used.
*/
public static String generateGUID(char prefix) {
String prefixStr = (""+ prefix).trim();
if (prefixStr.equals("")) {
prefixStr = DEFAULT_PADDING_PREFIX;
}
StringBuffer retStr = new StringBuffer(prefixStr + PADDING_STRING);
String guid = javaGUID();
int length = guid.length();
int replaceIdx = TOTAL_GUID_LENGTH - length;
retStr.replace(replaceIdx, TOTAL_GUID_LENGTH, guid);
return retStr.toString();
}
/**
* @return Webex String representation of the GUID generated by java.
* The UUID is represented in Java as 2 long.
* 2 long are combine to from a 16 byte array, which is then converted into a string by using base36 of the number.
* The long is considered Big-Endian and the byte array Little-Endian, to do this
* MSB (most significant bytes) are copied to the begining of the array
* LSB (least significant bytes) are copied to the end of the array
* So
* byte 7 of the MSB is copied as Byte 0 in the array
* byte 6 of the MSB is copied as Byte 1 in the array
* ...
* byte 0 of the MSB is copied as Byte 7 in the array
* byte 7 of the LSB is copied as Byte 8 in the array
* byte 6 of the LSB is copied as Byte 9 in the array
* ...
* byte 0 of the LSB is copied as Byte 15 in the array
*/
public static String javaGUID() {
UUID uuid = UUID.randomUUID();
long lsb = uuid.getLeastSignificantBits();
byte bytes[] = new byte[16];
populateBytes(bytes, 15, lsb);
long msb = uuid.getMostSignificantBits();
populateBytes(bytes, 7, msb);
BigInteger bi = new BigInteger(1, bytes);
return bi.toString(36).toUpperCase();
}
public static int javaIntGUID() {
UUID uuid = UUID.randomUUID();
long lsb = uuid.getLeastSignificantBits();
byte bytes[] = new byte[16];
populateBytes(bytes, 15, lsb);
long msb = uuid.getMostSignificantBits();
populateBytes(bytes, 7, msb);
BigInteger bi = new BigInteger(1, bytes);
return bi.intValue();
}
/**
* Private method to copy bytes in the reverse endian way.
*/
private static void populateBytes(byte [] bytes, int startIdx, long lbytes){
int endIdx = startIdx - 8;
for (int i = startIdx; i > endIdx; i--) {
bytes[i] = (byte) (lbytes & 0xFF);
lbytes = lbytes >> 8;
}
}
public static void main(String [] args){
System.out.println(GUIDGenerator.javaGUID());
System.out.println(GUIDGenerator.javaGUID().length());
}
}
com.dx.mes.common.transcoder.util.JacksonUtil
package com.dx.mes.common.transcoder.util;
import java.util.List;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
public class JacksonUtil {
/**
* 将json字符串转换成对象
*
* @param jsonString
* @param clazz
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T fromJson(String jsonString, @SuppressWarnings("rawtypes") Class clazz) {
return (T) JSON.parseObject(jsonString, clazz);
}
/**
* 将一个 Object 或者List对象转化为JSOObject或者JSONArray
*
* @param ObjOrList
* Object 或者List对象 或者hashmap 但是如果是set 就会有问题
* @return
*/
public static String toJSONStr(Object ObjOrList) {
// return JSON.toJSONString(ObjOrList);
// JSON.toJSONStringWithDateFormat(date, "yyyy-MM-dd HH:mm:ss.SSS");
return JSON.toJSONString(ObjOrList, SerializerFeature.WriteDateUseDateFormat);
}
/**
* 字符串转list
*
* @param jsonstr
* @param clazz
* @return
*/
public static List<?> parseToList(String jsonstr, Class<?> clazz) {
List<?> parseObj = JSON.parseArray(jsonstr, clazz);
return parseObj;
}
public static JSONObject getObjectValue(String key, JSONObject oj) {
return oj.getJSONObject(key);
}
public static boolean getBooleanValue(String key, JSONObject oj) {
return oj.getBoolean(key);
}
public static int getIntValue(String key, JSONObject oj) {
return oj.getIntValue(key);
}
public static String getStringValue(String key, JSONObject oj) {
return oj.getString(key);
}
public static JSONArray getListValue(String key, JSONObject oj) {
JSONArray str = oj.getJSONArray(key);
return str;
}
public static String json2xml(String jsonStr)throws Exception{
String xmlHead = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>";
StringBuffer sb = new StringBuffer(xmlHead);
ObjectMapper objectMapper = new ObjectMapper();
XmlMapper xmlMapper = new XmlMapper();
JsonNode root = objectMapper.readTree(jsonStr);
String xml = xmlMapper.writeValueAsString(root);
sb.append(xml.replaceAll("ObjectNode", "transaction"));
return sb.toString();
}
public static String json2Boexml(String jsonStr)throws Exception{
String xmlHead = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>";
StringBuffer sb = new StringBuffer(xmlHead);
ObjectMapper objectMapper = new ObjectMapper();
XmlMapper xmlMapper = new XmlMapper();
JsonNode root = objectMapper.readTree(jsonStr.toUpperCase());
String xml = xmlMapper.writeValueAsString(root);
sb.append(xml.replaceAll("ObjectNode", "BODY"));
return sb.toString();
}
}
com.dx.mes.common.transcoder.util.LocalUtil
package com.dx.mes.common.transcoder.util;
import java.net.InetAddress;
import java.net.UnknownHostException;
import com.dx.mes.common.bean.entity.LocalInfoBean;
/**
* @Title: LocalUtil.java
* @Package com.util
* @Description: TODO(添加描述)
* @date 2015-2-13 上午8:25:41
* @version V1.0
*/
public class LocalUtil {
private static LocalInfoBean localInfo;
static {
localInfo = new LocalInfoBean();
try {
InetAddress inetAddr = InetAddress.getLocalHost();
byte[] addr = inetAddr.getAddress();
// Convert to dot representation
String ipAddr = "";
for (int i = 0; i < addr.length; i++) {
if (i > 0) {
ipAddr += ".";
}
ipAddr += addr[i] & 0xFF;
}
String hostname = inetAddr.getHostName();
if (hostname.length() > 20) {
localInfo.setHostName(hostname.substring(0, 20));
} else {
localInfo.setHostName(hostname);
}
localInfo.setIp(ipAddr);
// System.out.println("IP Address: " + ipAddr);
// System.out.println("Hostname: " +hostname );
} catch (UnknownHostException e) {
System.out.println("Host not found: " + e.getMessage());
}
}
/*****
* 获取主机名和ip
* ******/
public static LocalInfoBean getLocalInfo() {
return localInfo;
}
}
com.dx.mes.common.transcoder.util.ObjectTranscoder
package com.dx.mes.common.transcoder.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ObjectTranscoder {
public static byte[] serialize(Object value) throws IOException{
byte[] rv=null;
ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
try {
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(value);
rv = bos.toByteArray();
} catch (IOException e) {
throw new IllegalArgumentException("Non-serializable object", e);
} finally {
oos.close();
bos.close();
}
return rv;
}
public static Object deserialize(byte[] in) throws IOException {
Object rv = null;
ByteArrayInputStream bis = null;
ObjectInputStream is = null;
try {
bis = new ByteArrayInputStream(in);
is = new ObjectInputStream(bis);
rv = is.readObject();
} catch (IOException e) {
throw new IllegalArgumentException("Caught IOException decoding "
+ (in == null ? 0 : in.length)
+ " bytes of data" + e.toString());
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Caught CNFE decoding "
+ (in == null ? 0 : in.length)
+ " bytes of data" + e.toString());
} finally {
is.close();
bis.close();
}
return rv;
}
}
com.dx.mes.common.transcoder.util.Util
package com.dx.mes.common.transcoder.util;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import org.apache.log4j.Logger;
public class Util {
private static Logger logger = Logger.getLogger(Util.class);
private static String strMySQLTimeFormat = "yyyy-MM-dd HH:mm:ss";
private static char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
public static String stackTraceToString(Exception excp) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, true);
excp.printStackTrace(pw);
pw.flush();
sw.flush();
return sw.toString();
}
public static String getEvtTime() {
Calendar now = Calendar.getInstance();
SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String evt_timestamp = tempDate.format(now.getTime());
return evt_timestamp;
}
public static Timestamp getCurrentTimestamp() {
Calendar now = Calendar.getInstance();
SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String evt_timestamp = tempDate.format(now.getTime());
Timestamp timestatmp = null;
try {
timestatmp = Timestamp.valueOf(evt_timestamp);
} catch (Exception ex) {
logger.error(Util.stackTraceToString(ex));
}
return timestatmp;
}
public static String getEvtTimeforVer() {
Calendar now = Calendar.getInstance();
SimpleDateFormat tempDate = new SimpleDateFormat("yyyyMMdd");
String evt_timestamp = tempDate.format(now.getTime());
return evt_timestamp;
}
public static String getEvtTimeforVer1() {
Calendar now = Calendar.getInstance();
SimpleDateFormat tempDate = new SimpleDateFormat("yyyyMMddHHmmss");
String evt_timestamp = tempDate.format(now.getTime());
return evt_timestamp;
}
public static String getRvTime() {
Calendar now = Calendar.getInstance();
SimpleDateFormat tempDate = new SimpleDateFormat("yyyyMMddHHmmss");
String evt_timestamp = tempDate.format(now.getTime());
return evt_timestamp;
}
public static String getMillisecondTime() {
Calendar now = Calendar.getInstance();
SimpleDateFormat tempDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String evt_timestamp = tempDate.format(now.getTime());
return evt_timestamp;
}
public static String getMillTimeStr() {
Calendar now = Calendar.getInstance();
// SimpleDateFormat tempDate = new
// SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
SimpleDateFormat tempDate = new SimpleDateFormat(strMySQLTimeFormat);
String evt_timestamp = tempDate.format(now.getTime());
return evt_timestamp;
}
public static Date getMillTime() {// TODO Need format
return String2Date(getMillTimeStr());
}
public static String formatEvtTime(Calendar calendar) {
SimpleDateFormat tempDate = new SimpleDateFormat(strMySQLTimeFormat);
String evt_timestamp = tempDate.format(calendar.getTime());
return evt_timestamp;
}
public static String formatRvTime(Calendar calendar) {
SimpleDateFormat tempDate = new SimpleDateFormat("yyyyMMddHHmmss");
String evt_timestamp = tempDate.format(calendar.getTime());
return evt_timestamp;
}
public static Date String2Date(String dateString) {
Date date = new Date();
try {
SimpleDateFormat sdf = new SimpleDateFormat(strMySQLTimeFormat);
date = sdf.parse(dateString);
} catch (ParseException e) {
System.out.println(e.getMessage());
}
return date;
}
public static Date String2Time(String timeString) {
Date date = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat("HH.mm.ss");
date = sdf.parse(timeString);
} catch (ParseException e) {
System.out.println(e.getMessage());
}
return date;
}
public static Timestamp String2Timestamp(String timeString) {
Timestamp timestatmp = null;
try {
timestatmp = Timestamp.valueOf(timeString);
} catch (Exception ex) {
logger.error(Util.stackTraceToString(ex));
}
return timestatmp;
}
/**
* Get time diff value (By min)
*
* @param startTime
* @param endTime
* @return
*/
public static long getDiffMin(String startTime, String endTime) {
long diff;
long diffMin = 0;
long nm = 1000 * 60;// 一分钟的毫秒数
SimpleDateFormat sd = new SimpleDateFormat(strMySQLTimeFormat);
try {
// 获得两个时间的毫秒时间差异
diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
diffMin = diff / nm;// 计算差多少分钟
} catch (ParseException ex) {
logger.error(Util.stackTraceToString(ex));
}
return diffMin;
}
/**
* Get time diff value (By min)
*
* @param startTime
* @param endTime
* @return
*/
public static long getDiffMin(Timestamp startTime, Timestamp endTime) {
long diffMin = 0;
long nm = 1000 * 60;// 一分钟的毫秒数
long diff = endTime.getTime() - startTime.getTime();
diffMin = diff / nm;// 计算差多少分钟 //TODO Double
return diffMin;
}
public static boolean isSpaceCheck(String str) {
if (null == str || str.length() <= 0 || ("").equals(str)) {
return true;
}
return false;
}
/*****
* 获取 double类型时间 逻辑混乱,不建议深入研究
* ******/
public static Double getDoubleTime() {
long now = System.currentTimeMillis(); // 微秒级当前时间
Calendar c = Calendar.getInstance();
c.setTimeInMillis(now);
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH) + 1;
int day = c.get(Calendar.DATE);
// int year = 2013;
// int month = 10;
// int day = 27;
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
int second = c.get(Calendar.SECOND);
int millisecond = c.get(Calendar.MILLISECOND);
// System.out.println("当前微秒级时间:"+System.currentTimeMillis());
// System.out.println("当前时间: " + c.get(Calendar.YEAR) + "年 "
// + (c.get(Calendar.MONTH) + 1) + "月 " + c.get(Calendar.DATE)
// + "日 周" + (c.get(Calendar.DAY_OF_WEEK) - 1) + " "
// + c.get(Calendar.HOUR) + "时 " + c.get(Calendar.MINUTE) + "分 "
// + c.get(Calendar.SECOND) + "秒 " + c.get(Calendar.MILLISECOND)
// + " 微秒");
Double days = Double.valueOf("0");// 统计天数
for (int i = 1900; i < year; i++) {
days += getDaysByYear(i);
}
// System.out.println("passDays :" + days + "\n");
int[] days_each_month = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30,
31, 30, 31 };
if (isLeepYear(year)) {
days_each_month[1] = 29;
}
for (int i = 0; i < month - 1; i++) {
days += days_each_month[i];
}
days = days + day + 1;
// 获取微秒
// long nanoTime = System.nanoTime();
// String snonoTime = nanoTime+"";
// String sMicroSecond = snonoTime.substring(snonoTime.length()-6,
// snonoTime.length()-3);
double seconds = hour * 3600 + minute * 60 + second;
double millSeconds = millisecond + seconds * 1000;// 000
// +Double.valueOf(sMicroSecond);
Double d = Double.valueOf(millSeconds / (3600 * 24 * 1000) + "");
return Double.valueOf(days + d);
}
// 获得某年的天数
private static int getDaysByYear(int year) {
if (isLeepYear(year)) {
return 366;
} else {
return 365;
}
}
// 判断是否是闰年
private static boolean isLeepYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}
public static String comInt2String(int value, int length) {
// System.out.println("value:" + value);
// System.out.println("length:" + length);
String s = String.valueOf(value);
if (s.length() > length) {
throw new RuntimeException("length is too short.");
} else if (s.length() == length) {
return s;
} else {
char[] cc = new char[length];
int i = 0;
for (; i < length - s.length(); i++) {
cc[i] = '0';
}
for (int j=0; j < s.length();i++,j++) {
// System.out.println(i);
cc[i] = s.charAt(j);
}
return new String(cc);
}
}
public static String comString2String(String s, int length) {
if (s.length() > length) {
throw new RuntimeException("length is too short.");
} else if (s.length() == length) {
return s;
} else {
char[] cc = new char[length];
int i = 0;
for (; i < length - s.length(); i++) {
cc[i] = '0';
}
for (int j=0; j < s.length();i++,j++) {
// System.out.println(i);
cc[i] = s.charAt(j);
}
return new String(cc);
}
}
/***
* 功能描述:将double类型的时间转换为 正常的时间格式如: 2013-08-16 13:04:12 。精确度:精确到秒。
* 此函数逻辑混乱,最好不要深入研究
* ***/
public static String getTimestampByDblTime(double dTime) {
int alldays = (int) dTime, year = 0, mon = 0, day = 0, hour, minute, second;
double allFloatPartDay = dTime - alldays;// double时间的小数部分
int remainDays = alldays-1;
StringBuffer timeStamp = new StringBuffer();
timeStamp.setLength(0);
// get year & mon
Calendar c = Calendar.getInstance();
for (int i = 1900; i < c.get(Calendar.YEAR)+1; i++) {
if(remainDays <= getDaysByYear(i)){//remainDays<=当年的天数,那么year=i
year = i;
break;
}
remainDays -= getDaysByYear(i);
}
int[] days_each_month = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (isLeepYear(year)) {
days_each_month[1] = 29;
}
//get day
int days = 0;
for (int i = 0; i < 12; i++) {
if ((days + days_each_month[i]) >= remainDays) {
mon = i + 1;
day = remainDays - days;
break;
}
days += days_each_month[i];
}
// get hour,minute,second
hour = (int) (24 * allFloatPartDay);
minute = (int) (24 * 60 * allFloatPartDay - 60 * (hour));
second = (int) (24 * 60 * 60 * (allFloatPartDay) - 60 * minute - 60 * 60 * hour);
timeStamp.append(year).append("-").append(comInt2String(checkTimeMaxVal(mon, "MON"), 2))
.append("-").append(comInt2String(checkTimeMaxVal(day, "DAY"), 2)).append(" ")
.append(comInt2String(checkTimeMaxVal(hour, "HOUR"), 2)).append(":")
.append(comInt2String(checkTimeMaxVal(minute, "MINUTE"), 2)).append(":")
.append(comInt2String(checkTimeMaxVal(second, "SECOND"), 2));
return timeStamp.toString();
}
public static int checkTimeMaxVal(int time, String type) {
if (("MON").equals(type) && time > 12) {
return 0;
}
if (("DAY").equals(type) && time > 31) {
return 0;
}
if (("HOUR").equals(type) || ("MINUTE").equals(type)
|| ("SECOND").equals(type)) {
if (time >= 60) {
return 0;
}
}
return time;
}
/**
* Get Date diff value (By day)
*
* @param startTime
* @param endTime
* @return
*/
public static long getDiffDay(String startTime, String endTime) {
long diffDays = 0;
Calendar c1 = Calendar.getInstance();
c1.clear();
Calendar c2 = Calendar.getInstance();
c2.clear();
Date start_Time = String2Date(startTime);
Date end_Time = String2Date(endTime);
// Set the date for both of the calendar instance
c1.setTime(start_Time);
c2.setTime(end_Time);
// Get the represented date in milliseconds
long time1 = c1.getTimeInMillis();
long time2 = c2.getTimeInMillis();
// Calculate difference in milliseconds
long diff = time2 - time1;
// Difference in days
diffDays = diff / (24 * 60 * 60 * 1000);
return diffDays;
}
/**
* Get getDateTime yyyy-MM-dd
*
* @return
*/
public static String getDateTime(String DateTime) {
Date dateTime = String2Date(DateTime);
SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd");
String evt_timestamp = tempDate.format(dateTime);
return evt_timestamp;
}
public static String getYesterData() {//获取当前日期的前一天日期
Calendar calendar = Calendar.getInstance(); //得到日历
calendar.add(Calendar.DAY_OF_MONTH, -1); //设置为前一天
Date dBefore = calendar.getTime(); //得到前一天的时间
SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd");
String evt_timestamp = tempDate.format(dBefore);
return evt_timestamp;
}
public static String getYesterData(String DateTime) {//获取指定日期的前一天日期
Calendar calendar = Calendar.getInstance(); //得到日历
SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = tempDate.parse(DateTime);
} catch (ParseException ex) {
// TODO Auto-generated catch block
logger.error(Util.stackTraceToString(ex));
}
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, -1); //设置为前一天
String strDate = tempDate.format(calendar.getTime());
return strDate;
}
// public static String getDataAfter(String DateTime ,Integer x) {//获取当前日期的后6个月日期
// Calendar calendar = Calendar.getInstance(); //得到日历
// calendar.add(Calendar.MONTH, +x); //设置为后几个月日期
// Date dBefore = calendar.getTime(); //得到后几个月的时间
// SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd");
// String evt_timestamp = tempDate.format(dBefore);
// return evt_timestamp;
// }
public static String getDateAfter(String DateTime,Integer x) {//获取指定日期的后x个月
Calendar calendar = Calendar.getInstance(); //得到日历
SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = tempDate.parse(DateTime);
} catch (ParseException ex) {
logger.error(Util.stackTraceToString(ex));
}
calendar.setTime(date);
calendar.add(Calendar.MONTH, +x);
String strDate = tempDate.format(calendar.getTime());
return strDate;
}
public static String getCurTime() {//获取当前日期的08整时间
Calendar dateTime = Calendar.getInstance();
SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd 08:00:00");
String evt_timestamp = tempDate.format(dateTime.getTime());
return evt_timestamp;
}
public static String getYesterTime() {//获取当前日期的前一天的08整时间
// Date dNow = new Date(); //当前时间
// Date dBefore = new Date();
Calendar calendar = Calendar.getInstance(); //得到日历
// calendar.setTime(dNow);//把当前时间赋给日历
calendar.add(Calendar.DAY_OF_MONTH, -1); //设置为前一天
Date dBefore = calendar.getTime(); //得到前一天的时间
SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd 08:00:00");
String evt_timestamp = tempDate.format(dBefore);
return evt_timestamp;
}
public static String getBefore4Time(String timestamp) {//获取当前时间往前推4小时的时间点
Date dNow = String2Date(timestamp);
Calendar calendar = Calendar.getInstance(); //得到日历
calendar.setTime(dNow);//把当前时间赋给日历
calendar.add(Calendar.HOUR_OF_DAY, -4); //设置为当前时间前推4小时
Date dBefore = calendar.getTime(); //得到前推4小时的时间
SimpleDateFormat tempDate = new SimpleDateFormat(strMySQLTimeFormat);
String evt_timestamp = tempDate.format(dBefore);
return evt_timestamp;
}
public static String getThickFormat(Double thickness){//将小数0.6转换为0060的格式
String S = thickness + "";
String[] s1 = S.split("\\.");//以小数点分隔
if(s1[0].length() == 1){
s1[0] = "0" + s1[0];
}
if(s1[1].length() == 1){
s1[1] = s1[1] + "0";
}else{
s1[1] = s1[1].substring(0,2);
}
return s1[0] + s1[1];
}
public static String getShiftType(){//根据系统时间,判断白夜班
Calendar dateTime = Calendar.getInstance();
SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String cur_timestamp = tempDate.format(dateTime.getTime());
SimpleDateFormat temp_8 = new SimpleDateFormat("yyyy-MM-dd 08:00:00");
String timestamp_8 = temp_8.format(dateTime.getTime());
SimpleDateFormat temp_20 = new SimpleDateFormat("yyyy-MM-dd 20:00:00");
String timestamp_20 = temp_20.format(dateTime.getTime());
try {
Date curTime = String2Date(cur_timestamp);
Date cur_8_time = String2Date(timestamp_8);
Date cur_20_time = String2Date(timestamp_20);
if (curTime.getTime() >= cur_8_time.getTime() &&
curTime.getTime() < cur_20_time.getTime()) {
return "F";
} else if (curTime.getTime() < cur_8_time.getTime() ||
curTime.getTime() >= cur_20_time.getTime()) {
return "R";
}
} catch (Exception ex) {
logger.error(Util.stackTraceToString(ex));
}
return "F";
}
public static String getLotData() {
Calendar dateTime = Calendar.getInstance();
SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String cur_timestamp = tempDate.format(dateTime.getTime());
SimpleDateFormat temp_0 = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
String timestamp_0 = temp_0.format(dateTime.getTime());
SimpleDateFormat temp_8 = new SimpleDateFormat("yyyy-MM-dd 08:00:00");
String timestamp_8 = temp_8.format(dateTime.getTime());
try {
Date evtTime = String2Date(cur_timestamp);
Date evt_0_time = String2Date(timestamp_0);
Date evt_8_time = String2Date(timestamp_8);
if (evtTime.getTime() >= evt_0_time.getTime() &&
evtTime.getTime() < evt_8_time.getTime()) {
dateTime.add(Calendar.DAY_OF_MONTH, -1); //设置为前一天
}
} catch (Exception ex) {
logger.error(Util.stackTraceToString(ex));
}
Date dBefore = dateTime.getTime(); //得到日期
SimpleDateFormat evtDate = new SimpleDateFormat("yyyyMMdd");
String evt_data = evtDate.format(dBefore);
return evt_data;
}
public static Timestamp getCurrentTimestampToMilli() {
Calendar now = Calendar.getInstance();
SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String evt_timestamp = tempDate.format(now.getTime());
Timestamp timestatmp = null;
try {
timestatmp = Timestamp.valueOf(evt_timestamp);
} catch (Exception ex) {
logger.error(Util.stackTraceToString(ex));
}
return timestatmp;
}
/**
* Get time diff value (By millisecond)毫秒
*
* @param startTime
* @param endTime
* @return
*/
public static long getDiffMillisec(Timestamp startTime, Timestamp endTime) {
long diffMillisec = 0;
diffMillisec = endTime.getTime() - startTime.getTime();
return diffMillisec;
}
/**
* 大于9的数字转换为字母
*/
public static String I2S(Integer numb){
String str = "0";
switch(numb){
case 1:
str = "1";
break;
case 2:
str = "2";
break;
case 3:
str = "3";
break;
case 4:
str = "4";
break;
case 5:
str = "5";
break;
case 6:
str = "6";
break;
case 7:
str = "7";
break;
case 8:
str = "8";
break;
case 9:
str = "9";
break;
case 10:
str = "A";
break;
case 11:
str = "B";
break;
case 12:
str = "C";
break;
case 13:
str = "D";
break;
case 14:
str = "E";
break;
case 15:
str = "F";
break;
case 16:
str = "G";
break;
case 17:
str = "H";
break;
case 18:
str = "I";
break;
case 19:
str = "J";
break;
case 20:
str = "K";
break;
case 21:
str = "L";
break;
case 22:
str = "M";
break;
case 23:
str = "N";
break;
case 24:
str = "O";
break;
case 25:
str = "P";
break;
case 26:
str = "Q";
break;
case 27:
str = "R";
break;
case 28:
str = "S";
break;
case 29:
str = "T";
break;
case 30:
str = "U";
break;
case 31:
str = "V";
break;
case 32:
str = "W";
break;
case 33:
str = "X";
break;
case 34:
str = "Y";
break;
case 35:
str = "Z";
break;
}
return str;
}
public static Integer S2I(String str){
Integer numb = 0;
switch(str.charAt(0)){
case '1':
numb = 1;
break;
case '2':
numb = 2;
break;
case '3':
numb = 3;
break;
case '4':
numb = 4;
break;
case '5':
numb = 5;
break;
case '6':
numb = 6;
break;
case '7':
numb = 7;
break;
case '8':
numb = 8;
break;
case '9':
numb = 9;
break;
case 'A':
numb = 10;
break;
case 'B':
numb = 11;
break;
case 'C':
numb = 12;
break;
case 'D':
numb = 13;
break;
case 'E':
numb = 14;
break;
case 'F':
numb = 15;
break;
case 'G':
numb = 16;
break;
case 'H':
numb = 17;
break;
case 'I':
numb = 18;
break;
case 'J':
numb = 19;
break;
case 'K':
numb = 20;
break;
case 'L':
numb = 21;
break;
case 'M':
numb = 22;
break;
case 'N':
numb = 23;
break;
case 'O':
numb = 24;
break;
case 'P':
numb = 25;
break;
case 'Q':
numb = 26;
break;
case 'R':
numb = 27;
break;
case 'S':
numb = 28;
break;
case 'T':
numb = 29;
break;
case 'U':
numb = 30;
break;
case 'V':
numb = 31;
break;
case 'W':
numb = 32;
break;
case 'X':
numb = 33;
break;
case 'Y':
numb = 34;
break;
case 'Z':
numb = 35;
break;
}
return numb;
}
//随即生成16位字符串 by wfq
public static String getRandomString(int length) { //length表示生成字符串的长度
String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
/**
* 获取当前时间(格式yyyy-MM-dd HH:mm:ss)
* @return String currentDateTime
*/
public static String getCurrentDateTime() {
Calendar now = Calendar.getInstance();
SimpleDateFormat tempDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateTime = tempDateTime.format(now.getTime());
return currentDateTime;
}
/**
* 获取当前日期(格式yyyy-MM-dd)
* @return String currentDate
*/
public static String getCurrentDate(String DateTime) {
Date dateTime = String2Date(DateTime);
SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd");
String currentDate = tempDate.format(dateTime);
return currentDate;
}
//+1s by wfq
public static Timestamp sec(Timestamp firstTime){
Calendar calendar = Calendar.getInstance();
SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date begdate = new Date(firstTime.getTime());
calendar.setTime(begdate);
calendar.add(Calendar.SECOND, +1);
String finalTime = tempDate.format(calendar.getTime());
return Timestamp.valueOf(finalTime);
}
/**
*
* @param i 年份截取末位个数
* @param flg Y for 日期转换,N for 日期不转换,其他 for 不输出日期
* @return
*/
public static String getYearMonthDayEight(Integer i, String flg){
String yearMonthDay = "***";
String tempYearMonthDay = getLotData();
yearMonthDay = tempYearMonthDay.substring(4-i, 4);
//月份需要转换(1~9艺术字体现,10~12以字母A~C体现)
yearMonthDay = yearMonthDay + Digit[Integer.valueOf(tempYearMonthDay.substring(4,6))];
if("Y".equals(flg)){//日期需要转换(1~9用数字,10~31用字母,排除I和O)
yearMonthDay = yearMonthDay + Digit[Integer.valueOf(tempYearMonthDay.substring(6,8))];
}else if("N".equals(flg)){
yearMonthDay = yearMonthDay + tempYearMonthDay.substring(6,8);
}
return yearMonthDay;
}
public static String getYearMonthDayZero(Integer i, String flg){
String yearMonthDay = "***";
Calendar dateTime = Calendar.getInstance();
SimpleDateFormat tempDate = new SimpleDateFormat("yyyyMMdd");
String tempYearMonthDay = tempDate.format(dateTime.getTime());
yearMonthDay = tempYearMonthDay.substring(4-i, 4);
//月份需要转换(1~9艺术字体现,10~12以字母A~C体现)
yearMonthDay = yearMonthDay + Digit[Integer.valueOf(tempYearMonthDay.substring(4,6))];
if("Y".equals(flg)){//日期需要转换(1~9用数字,10~31用字母,排除I和O)
yearMonthDay = yearMonthDay + Digit[Integer.valueOf(tempYearMonthDay.substring(6,8))];
}else if("N".equals(flg)){
yearMonthDay = yearMonthDay + tempYearMonthDay.substring(6,8);
}
return yearMonthDay;
}
/**
* 0~1,A~Z(I和O除外)
* 将10进制数转换为数字和字母组合的字符串
* @return
*/
public static String getSerialNo(Integer iSerial, Integer i){
String sSerial = "*";
if(i == 1 && iSerial<= 33){
sSerial = String.valueOf(Digit[iSerial]);
}else if(i == 2 && iSerial<= 1155){//33*34+33
sSerial = String.valueOf(Digit[iSerial/34])
+ String.valueOf(Digit[iSerial%34]);
}else if(i == 3 && iSerial<= 39303){//33*34*34+33*34+33
sSerial = String.valueOf(Digit[iSerial/34/34])
+ String.valueOf(Digit[iSerial/34%34])
+ String.valueOf(Digit[iSerial%34%34]);
}
return sSerial;
}
/**
* 获取thickness type
*/
public static String getThicknessTyp(String thickness){
String thicknessTyp = "*";
Map<String,String> thick = new HashMap<String,String>();
thick.put("0.4", "A");
thick.put("0.5", "B");
thick.put("0.6", "C");
thick.put("0.63", "D");
thick.put("0.7", "E");
thick.put("1.1", "F");
thick.put("0.2", "G");
thick.put("0.3", "H");
thick.put("0.25", "J");
thick.put("0.225", "K");
thick.put("0.63+0.7", "L");
thick.put("0.215", "M");
thick.put("0.265", "N");
thick.put("0.1", "P");
thick.put("0.15", "Q");
thick.put("0.2+0.1", "S");
thick.put("0.18", "T");
thick.put("0.5+0.4", "R");
thick.put("0.2+0.4", "U");
if(thick.get(thickness) != null){
thicknessTyp = thick.get(thickness);
}
return thicknessTyp;
}
/**
* 获取月份代码
* 区分公元单双数
*/
public static String getMonthTyp(Calendar rightNow){
String strMonth = "*";
char[] Digit_E = { '*', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C'}; //双数公元年
char[] Digit_O = { '*', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q'}; //单数公元年
if(rightNow.get(Calendar.YEAR)%2 == 0){//双数公元年
strMonth = String.valueOf(Digit_E[rightNow.get(Calendar.MONTH) + 1]);
}else{//单数公元年
strMonth = String.valueOf(Digit_O[rightNow.get(Calendar.MONTH) + 1]);
}
return strMonth;
}
/****
* 测试main函数,获取double类型时间,后再转换成String 时间
* ***/
public static void main(String[] args) {
double dTime = getDoubleTime();
System.out.println("" + getDoubleTime() + "\n");
// getTimestampByDblTime(41574.10797572048);
getTimestampByDblTime(dTime);
System.out.println("" + getTimestampByDblTime(42369.65204627315) + "\n");
}
//判断保养是否过期
public static boolean isDealy(String dataString){
boolean is_delay = false;
Date data = String2Date(dataString);
Calendar calendar = Calendar.getInstance(); //得到日历
Date d2 = calendar.getTime();
if(d2.getTime() > data.getTime()){
is_delay = true;
}
return is_delay;
}
//sap date to timestamp
public static Timestamp sapStr2Timestap(String timeStr) throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat formatter2 = new SimpleDateFormat("yyyyMMdd");
Date date = formatter2.parse(timeStr);
String plnDteStr = formatter.format(date);
return Timestamp.valueOf(plnDteStr+" 00:00:00");
}
public static String now2sapData(){
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
String cx_date = dateFormat.format(now);
return cx_date;
}
public static String timestamp2Sapdate(Timestamp timestamp){
String dateStr = timestamp.toString().substring(0,9);
String removeStr ="-";
dateStr.replace(removeStr,"");
return dateStr;
}
public static String sapDateToWebDate(String date){
if(date.length()!=8){
return "";
}
return date.substring(0,4) + "-" + date.substring(4,6) + "-" + date.substring(6,8);
}
}
com.dx.mes.common.core.base.service.ICIMBaseInterface
package com.dx.mes.common.core.base.service;
public interface ICIMBaseInterface {
String subMainProc(String var1, String var2);
}
com.dx.mes.common.core.dao.GenericHisDao
package com.dx.mes.common.core.dao;
import java.io.Serializable;
import java.util.List;
import org.hibernate.LockMode;
import org.hibernate.Session;
public interface GenericHisDao<T extends Serializable, PK extends Serializable> {
T get(PK var1);
T getWithLock(PK var1, LockMode var2);
List<T> list(String var1, Object... var2);
T uniqueResult(String var1, Object... var2);
List<T> listWithLock(String var1, Object... var2);
T uniqueResultWithLock(String var1, Object... var2);
Session getCrSession();
void flushCurSession();
void flush();
List find(String var1);
List findBySQL(String var1);
List findBySQL(String var1, Class var2);
List findBySQL(String var1, Class var2, Object... var3);
T comTblRead(String var1);
T comTblReadLock(String var1, String var2);
List<T> comTblRead2nd(String var1);
T load(PK var1);
T loadWithLock(PK var1, LockMode var2);
List<T> loadAll();
List<T> find(String var1, Object[] var2);
List<T> listBySQL(String var1);
void lock(T var1, LockMode var2);
List<String> findDistStringList(String var1);
T findBySQLOnly(String var1);
long getCountBySql(String var1);
}
com.dx.mes.common.core.dao.GenericDao
package com.dx.mes.common.core.dao;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import org.hibernate.LockMode;
import org.hibernate.Session;
public interface GenericDao<T extends Serializable, PK extends Serializable> {
T get(PK var1);
T getWithLock(PK var1, LockMode var2);
List<T> list(String var1, Object... var2);
T uniqueResult(String var1, Object... var2);
List<T> listWithLock(String var1, Object... var2);
T uniqueResultWithLock(String var1, Object... var2);
void update(T var1);
void updateWh(T var1);
void update2(T var1);
void save(T var1);
void saveOrUpdate(T var1);
void saveOrUpdate2(T var1);
void saveOrUpdateAll(Collection<T> var1);
void saveOrUpdateAllWh(Collection<T> var1);
void delete(T var1);
void deleteByKey(PK var1);
Session getCrSession();
void flushCurSession();
void flush();
List find(String var1);
List findBySQL(String var1);
List findBySQL(String var1, Class var2);
List findBySQL(String var1, Class var2, Object... var3);
T comTblRead(String var1);
T comTblReadLock(String var1, String var2);
List<T> comTblRead2nd(String var1);
T load(PK var1);
T loadWithLock(PK var1, LockMode var2);
List<T> loadAll();
void deleteAll(Collection<T> var1);
List<T> find(String var1, Object var2);
List<T> find(String var1, Object[] var2);
List<T> listBySQL(String var1);
void lock(T var1, LockMode var2);
List<String> findDistStringList(String var1);
T findBySQLOnly(String var1);
long getCountBySql(String var1);
}
com.dx.mes.common.core.dao.impl.GenericHibernateHisDao
package com.dx.mes.common.core.dao.impl;
import com.dx.mes.common.bean.entity.UUIDObject;
import com.dx.mes.common.core.dao.GenericHisDao;
import com.dx.mes.common.core.redis.RedisManager;
import com.dx.mes.common.transcoder.util.AppContext;
import com.dx.mes.common.transcoder.util.GUIDGenerator;
import com.dx.mes.common.transcoder.util.LocalUtil;
import com.dx.mes.common.transcoder.util.Util;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
@Repository
public class GenericHibernateHisDao<T extends Serializable, PK extends Serializable> extends HibernateDaoSupport implements GenericHisDao<T, PK> {
private static final Logger logger = Logger.getLogger(RedisManager.class);
private Class<T> entityClass = null;
@Resource
private RedisManager redisManager;
@Resource
public void setSessionFactoryOverride(SessionFactory sessionFactoryHis) {
super.setSessionFactory(sessionFactoryHis);
}
public GenericHibernateHisDao() {
Class c = this.getClass();
Type t = c.getGenericSuperclass();
if(t instanceof ParameterizedType) {
Type[] p = ((ParameterizedType)t).getActualTypeArguments();
this.entityClass = (Class)p[0];
}
}
public T get(PK id) {
return id == null?null:(Serializable)this.getHibernateTemplate().get(this.entityClass, id);
}
public T getWithLock(PK id, LockMode lock) {
if(id == null) {
return null;
} else {
T t = (Serializable)this.getHibernateTemplate().get(this.entityClass, id, lock);
if(t != null) {
this.flush();
}
return t;
}
}
public T load(PK id) {
return (Serializable)this.getHibernateTemplate().load(this.entityClass, id);
}
public T loadWithLock(PK id, LockMode lock) {
T t = (Serializable)this.getHibernateTemplate().load(this.entityClass, id, lock);
if(t != null) {
this.flush();
}
return t;
}
public List<T> loadAll() {
return this.getHibernateTemplate().loadAll(this.entityClass);
}
private void setEntityCommonProperty(T entity, String operation) {
((UUIDObject)entity).setPv_unq_seq_id(((UUIDObject)entity).getUnq_seq_id());
((UUIDObject)entity).setUnq_seq_id(GUIDGenerator.javaGUID());
((UUIDObject)entity).setOperation(operation);
((UUIDObject)entity).setOpe_tbl_name(entity.getClass().getSimpleName().toUpperCase());
((UUIDObject)entity).setSta_time_d(Util.getDoubleTime());
((UUIDObject)entity).setOpe_evt_name(AppContext.getCurrServiceName());
((UUIDObject)entity).setOpe_evt_node(LocalUtil.getLocalInfo().getIp());
((UUIDObject)entity).setOpe_evt_usr(LocalUtil.getLocalInfo().getHostName());
((UUIDObject)entity).setOpe_evt_no(AppContext.getCurrEventNumber());
}
private void setEntityCommonPropertyNew(Collection<T> entities, String operation) {
Iterator var3 = entities.iterator();
while(var3.hasNext()) {
T entity = (Serializable)var3.next();
((UUIDObject)entity).setPv_unq_seq_id(((UUIDObject)entity).getUnq_seq_id());
((UUIDObject)entity).setUnq_seq_id(GUIDGenerator.javaGUID());
((UUIDObject)entity).setOperation(operation);
((UUIDObject)entity).setOpe_tbl_name(entity.getClass().getSimpleName().toUpperCase());
((UUIDObject)entity).setSta_time_d(Util.getDoubleTime());
((UUIDObject)entity).setOpe_evt_name(AppContext.getCurrServiceName());
((UUIDObject)entity).setOpe_evt_node(LocalUtil.getLocalInfo().getIp());
((UUIDObject)entity).setOpe_evt_usr(LocalUtil.getLocalInfo().getHostName());
((UUIDObject)entity).setOpe_evt_no(AppContext.getCurrEventNumber());
}
}
public List<T> find(String queryString) {
List<?> objects = this.getHibernateTemplate().find(queryString);
return (List)objects.stream().map((o) -> {
return (Serializable)o;
}).collect(Collectors.toList());
}
public List find(String queryString, Object[] values) {
return this.getHibernateTemplate().find(queryString, values);
}
public void lock(T entity, LockMode lock) {
this.getHibernateTemplate().lock(entity, lock);
}
public void flush() {
this.getHibernateTemplate().flush();
}
public List listBySQL(String sql) {
Session session = this.getCrSession();
return session.createSQLQuery(sql).list();
}
public List findBySQL(String sql) {
Session s = this.getHibernateTemplate().getSessionFactory().getCurrentSession();
Query q = s.createSQLQuery(sql);
return q.list();
}
public List<T> findBySQL(String sql, Class clazz) {
Session s = this.getHibernateTemplate().getSessionFactory().getCurrentSession();
Query q = s.createSQLQuery(sql).addEntity(clazz);
return q.list();
}
public List<T> findBySQL(String sql, Class clazz, Object... args) {
Session s = this.getHibernateTemplate().getSessionFactory().getCurrentSession();
Query q = s.createSQLQuery(sql).addEntity(clazz);
return q.list();
}
public T findBySQLOnly(String sql) {
Session s = this.getHibernateTemplate().getSessionFactory().getCurrentSession();
Query q = s.createSQLQuery(sql);
return (Serializable)q.uniqueResult();
}
public List<String> findDistStringList(String strSql) {
Query query = this.getCrSession().createQuery(strSql);
return query.list();
}
public T comTblRead(String sql) {
Session s = this.getHibernateTemplate().getSessionFactory().getCurrentSession();
Query q = s.createQuery(sql);
Object obj = q.uniqueResult();
return (Serializable)obj;
}
public T comTblReadLock(String sql, String tbl_name) {
Session s = this.getHibernateTemplate().getSessionFactory().getCurrentSession();
Query q = s.createQuery(sql);
q.setLockMode(tbl_name, LockMode.READ);
Object obj = q.uniqueResult();
return (Serializable)obj;
}
public List comTblRead2nd(String sql) {
Session s = this.getHibernateTemplate().getSessionFactory().getCurrentSession();
Query q = s.createQuery(sql);
return q.list();
}
public T findOnlyOne(String queryString, Object[] values) {
return (Serializable)this.getHibernateTemplate().find(queryString, values).get(0);
}
public Session getCrSession() {
return this.getHibernateTemplate().getSessionFactory().getCurrentSession();
}
public void flushCurSession() {
Session curSession = this.getCrSession();
curSession.flush();
}
public long getCountBySql(String sql) {
return ((Long)this.getHibernateTemplate().iterate(sql).next()).longValue();
}
public List<T> list(String hql, Object... values) {
Query query = this.createQuery(hql, values);
return query.list();
}
public T uniqueResult(String hql, Object... values) {
Query query = this.createQuery(hql, values);
return (Serializable)query.uniqueResult();
}
protected Query createQuery(String hql, Object... values) {
Query query = this.getCrSession().createQuery(hql);
if(values != null) {
for(int i = 0; i < values.length; ++i) {
query.setParameter(i, values[i]);
}
}
return query;
}
public List<T> listWithLock(String hql, Object... values) {
Session session = this.getCrSession();
Query query = this.createQuery(hql, values);
List<T> ts = query.list();
Iterator var6 = ts.iterator();
while(var6.hasNext()) {
T t = (Serializable)var6.next();
session.lock(t, LockMode.UPGRADE);
}
return ts;
}
public T uniqueResultWithLock(String hql, Object... values) {
Session session = this.getCrSession();
Query query = this.createQuery(hql, values);
T t = (Serializable)query.uniqueResult();
if(t == null) {
return t;
} else {
session.lock(t, LockMode.UPGRADE);
return t;
}
}
}
com.dx.mes.common.core.dao.impl.GenericHibernateDao
package com.dx.mes.common.core.dao.impl;
import com.dx.mes.common.bean.entity.HisXml;
import com.dx.mes.common.bean.entity.TableHistoryConfig;
import com.dx.mes.common.bean.entity.UUIDObject;
import com.dx.mes.common.core.dao.GenericDao;
import com.dx.mes.common.core.redis.RedisManager;
import com.dx.mes.common.transcoder.util.AppContext;
import com.dx.mes.common.transcoder.util.GUIDGenerator;
import com.dx.mes.common.transcoder.util.JacksonUtil;
import com.dx.mes.common.transcoder.util.LocalUtil;
import com.dx.mes.common.transcoder.util.ObjectTranscoder;
import com.dx.mes.common.transcoder.util.Util;
import java.io.IOException;
import java.io.Serializable;
import java.io.StringWriter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.betwixt.io.BeanWriter;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import redis.clients.jedis.Jedis;
@Repository
public class GenericHibernateDao<T extends Serializable, PK extends Serializable> extends HibernateDaoSupport implements GenericDao<T, PK> {
private static final Logger logger = Logger.getLogger(RedisManager.class);
private static final String OPERATION_UPDATE = "UPDATE";
private static final String OPERATION_INSERT = "INSERT";
private static final String OPERATION_DELETE = "DELETE";
private static final String OPERATION_SAVE_OR_UPDATE = "IorU";
private static final String OPERATION_SAVE_OR_UPDATE_ALL = "IorUAL";
private Class<T> entityClass = null;
@Resource
private RedisManager redisManager;
@Resource
public void setSessionFactoryOverride(SessionFactory sessionFactory) {
super.setSessionFactory(sessionFactory);
}
public GenericHibernateDao() {
Class c = this.getClass();
Type t = c.getGenericSuperclass();
if(t instanceof ParameterizedType) {
Type[] p = ((ParameterizedType)t).getActualTypeArguments();
this.entityClass = (Class)p[0];
}
}
public TableHistoryConfig getTableHistoryConfig(String tableName) {
Jedis jedis = this.redisManager.getJedis();
TableHistoryConfig tableConfig = new TableHistoryConfig();
try {
String redisKey = "lodhis_config_" + tableName;
byte[] bs = jedis.get(redisKey.getBytes());
if(bs != null) {
tableConfig = (TableHistoryConfig)JacksonUtil.fromJson(new String(bs), TableHistoryConfig.class);
if(tableConfig == null) {
tableConfig = new TableHistoryConfig();
}
}
} catch (Exception var9) {
var9.printStackTrace();
} finally {
this.redisManager.returnResource(jedis);
}
return tableConfig;
}
public TableHistoryConfig getTableHistoryConfigWh(String tableName) {
Jedis jedis = this.redisManager.getJedis();
TableHistoryConfig tableConfig = new TableHistoryConfig();
try {
String redisKey = "wh_lodhis_config_" + tableName;
byte[] bs = jedis.get(redisKey.getBytes());
if(bs != null) {
tableConfig = (TableHistoryConfig)ObjectTranscoder.deserialize(bs);
if(tableConfig == null) {
tableConfig = new TableHistoryConfig();
}
}
} catch (IOException var9) {
var9.printStackTrace();
} finally {
this.redisManager.returnResource(jedis);
}
return tableConfig;
}
public void sendHistoryMessageToRedis(Object entity) {
String tableName = entity.getClass().getSimpleName().toUpperCase();
if(!StringUtils.isEmpty(tableName)) {
TableHistoryConfig tableHistoryConfig = this.getTableHistoryConfig(tableName);
if(tableHistoryConfig.isHasToSendHis()) {
String xmlInfo = this.hisQueryReport(entity);
if(xmlInfo != null) {
Jedis jedis = this.redisManager.getJedis();
new ArrayList();
try {
String redisKey = "tempData_for_MQ_" + AppContext.getCurrEventNumber();
byte[] bs = jedis.get(redisKey.getBytes());
Object hisXmlList;
if(bs != null) {
String redisValue = new String(bs);
hisXmlList = (List)JacksonUtil.fromJson(redisValue, List.class);
} else {
hisXmlList = new ArrayList();
}
((List)hisXmlList).add(new HisXml(tableHistoryConfig, xmlInfo));
logger.info("Send Redis's Key:" + redisKey);
jedis.setex(redisKey, 300, JacksonUtil.toJSONStr(hisXmlList));
logger.info("send info to redis end:");
} catch (Exception var13) {
var13.printStackTrace();
} finally {
this.redisManager.returnResource(jedis);
}
}
}
}
}
public void sendHistoryMessageToRedisWh(Object entity) {
String tableName = entity.getClass().getSimpleName().toUpperCase();
if(!StringUtils.isEmpty(tableName)) {
TableHistoryConfig tableHistoryConfig = this.getTableHistoryConfigWh(tableName);
if(tableHistoryConfig.isHasToSendHis()) {
String xmlInfo = this.hisQueryReport(entity);
if(xmlInfo != null) {
Jedis jedis = this.redisManager.getJedis();
new ArrayList();
try {
String redisKey = "lodhis_" + AppContext.getCurrEventNumber();
byte[] bs = jedis.get(redisKey.getBytes());
Object hisXmlList;
if(bs != null) {
hisXmlList = (List)ObjectTranscoder.deserialize(bs);
} else {
hisXmlList = new ArrayList();
}
((List)hisXmlList).add(new HisXml(tableHistoryConfig, xmlInfo));
jedis.setex(redisKey.getBytes(), 172800, ObjectTranscoder.serialize(hisXmlList));
} catch (IOException var12) {
var12.printStackTrace();
} finally {
this.redisManager.returnResource(jedis);
}
}
}
}
}
public void sendHistoryMessageToRedisNew(Collection<T> entities) {
String tableName = ((Serializable)entities.iterator().next()).getClass().getSimpleName().toUpperCase();
System.out.println(tableName);
if(!StringUtils.isEmpty(tableName)) {
TableHistoryConfig tableHistoryConfig = this.getTableHistoryConfig(tableName);
if(tableHistoryConfig.isHasToSendHis()) {
String xmlInfo = this.hisQueryReportNew(entities);
if(xmlInfo != null) {
Jedis jedis = this.redisManager.getJedis();
new ArrayList();
try {
String redisKey = "tempData_for_MQ_" + AppContext.getCurrEventNumber();
byte[] bs = jedis.get(redisKey.getBytes());
Object hisXmlList;
if(bs != null) {
String redisValue = new String(bs);
hisXmlList = (List)JacksonUtil.fromJson(redisValue, List.class);
} else {
hisXmlList = new ArrayList();
}
((List)hisXmlList).add(new HisXml(tableHistoryConfig, xmlInfo));
logger.info("Send Redis's Key:" + redisKey);
jedis.setex(redisKey, 300, JacksonUtil.toJSONStr(hisXmlList));
logger.info("send info to redis end:");
} catch (Exception var13) {
var13.printStackTrace();
} finally {
this.redisManager.returnResource(jedis);
}
}
}
}
}
public void sendHistoryMessageToRedisNewWh(Collection<T> entities) {
String tableName = ((Serializable)entities.iterator().next()).getClass().getSimpleName().toUpperCase();
System.out.println(tableName);
if(!StringUtils.isEmpty(tableName)) {
TableHistoryConfig tableHistoryConfig = this.getTableHistoryConfigWh(tableName);
if(tableHistoryConfig.isHasToSendHis()) {
String xmlInfo = this.hisQueryReportNew(entities);
if(xmlInfo != null) {
Jedis jedis = this.redisManager.getJedis();
new ArrayList();
try {
String redisKey = "lodhis_" + AppContext.getCurrEventNumber();
byte[] bs = jedis.get(redisKey.getBytes());
Object hisXmlList;
if(bs != null) {
hisXmlList = (List)ObjectTranscoder.deserialize(bs);
} else {
hisXmlList = new ArrayList();
}
((List)hisXmlList).add(new HisXml(tableHistoryConfig, xmlInfo));
jedis.setex(redisKey.getBytes(), 172800, ObjectTranscoder.serialize(hisXmlList));
} catch (IOException var12) {
var12.printStackTrace();
} finally {
this.redisManager.returnResource(jedis);
}
}
}
}
}
public String hisQueryReport(Object inObj) {
StringWriter sw = new StringWriter();
sw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?><transaction><trans_cnt>1</trans_cnt>");
String replacedOutXml = null;
BeanWriter beanWriter = new BeanWriter(sw);
beanWriter.setEndOfLine("");
beanWriter.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
beanWriter.getBindingConfiguration().setMapIDs(false);
try {
beanWriter.write("table", inObj);
sw.write("</transaction>");
replacedOutXml = StringUtils.replaceEach(sw.toString(), new String[]{"<id>", "</id>"}, new String[]{"", ""});
} catch (Exception var14) {
logger.error(var14.toString());
} finally {
try {
sw.close();
} catch (Exception var13) {
logger.error(var13.toString());
}
}
return replacedOutXml;
}
public String hisQueryReportNew(Collection<T> entities) {
StringWriter sw = new StringWriter();
sw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?><transaction><trans_cnt>" + entities.size() + "</trans_cnt>");
String replacedOutXml = null;
BeanWriter beanWriter = new BeanWriter(sw);
beanWriter.setEndOfLine("");
beanWriter.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
beanWriter.getBindingConfiguration().setMapIDs(false);
try {
Iterator var5 = entities.iterator();
while(var5.hasNext()) {
Object entity = var5.next();
beanWriter.write("table", entity);
}
sw.write("</transaction>");
replacedOutXml = StringUtils.replaceEach(sw.toString(), new String[]{"<id>", "</id>"}, new String[]{"", ""});
} catch (Exception var15) {
logger.error(var15.toString());
} finally {
try {
sw.close();
} catch (Exception var14) {
logger.error(var14.toString());
}
}
System.out.println(replacedOutXml);
return replacedOutXml;
}
public T get(PK id) {
return id == null?null:(Serializable)this.getHibernateTemplate().get(this.entityClass, id);
}
public T getWithLock(PK id, LockMode lock) {
if(id == null) {
return null;
} else {
T t = (Serializable)this.getHibernateTemplate().get(this.entityClass, id, lock);
if(t != null) {
this.flush();
}
return t;
}
}
public T load(PK id) {
return (Serializable)this.getHibernateTemplate().load(this.entityClass, id);
}
public T loadWithLock(PK id, LockMode lock) {
T t = (Serializable)this.getHibernateTemplate().load(this.entityClass, id, lock);
if(t != null) {
this.flush();
}
return t;
}
public List<T> loadAll() {
return this.getHibernateTemplate().loadAll(this.entityClass);
}
private void setEntityCommonProperty(T entity, String operation) {
((UUIDObject)entity).setPv_unq_seq_id(((UUIDObject)entity).getUnq_seq_id());
((UUIDObject)entity).setUnq_seq_id(GUIDGenerator.javaGUID());
((UUIDObject)entity).setOperation(operation);
((UUIDObject)entity).setOpe_tbl_name(entity.getClass().getSimpleName().toUpperCase());
((UUIDObject)entity).setSta_time_d(Util.getDoubleTime());
((UUIDObject)entity).setOpe_evt_name(AppContext.getCurrServiceName());
((UUIDObject)entity).setOpe_evt_node(LocalUtil.getLocalInfo().getIp());
((UUIDObject)entity).setOpe_evt_usr(LocalUtil.getLocalInfo().getHostName());
((UUIDObject)entity).setOpe_evt_no(AppContext.getCurrEventNumber());
}
private void setEntityCommonPropertyNew(Collection<T> entities, String operation) {
Iterator var3 = entities.iterator();
while(var3.hasNext()) {
T entity = (Serializable)var3.next();
((UUIDObject)entity).setPv_unq_seq_id(((UUIDObject)entity).getUnq_seq_id());
((UUIDObject)entity).setUnq_seq_id(GUIDGenerator.javaGUID());
((UUIDObject)entity).setOperation(operation);
((UUIDObject)entity).setOpe_tbl_name(entity.getClass().getSimpleName().toUpperCase());
((UUIDObject)entity).setSta_time_d(Util.getDoubleTime());
((UUIDObject)entity).setOpe_evt_name(AppContext.getCurrServiceName());
((UUIDObject)entity).setOpe_evt_node(LocalUtil.getLocalInfo().getIp());
((UUIDObject)entity).setOpe_evt_usr(LocalUtil.getLocalInfo().getHostName());
((UUIDObject)entity).setOpe_evt_no(AppContext.getCurrEventNumber());
}
}
public void update(T entity) {
this.setEntityCommonProperty(entity, "UPDATE");
this.getHibernateTemplate().update(entity);
this.flushCurSession();
this.sendHistoryMessageToRedis(entity);
}
public void updateWh(T entity) {
this.setEntityCommonProperty(entity, "UPDATE");
this.getHibernateTemplate().update(entity);
this.flushCurSession();
this.sendHistoryMessageToRedisWh(entity);
}
public void update2(T entity) {
this.setEntityCommonProperty(entity, "UPDATE");
this.getHibernateTemplate().update(entity);
this.sendHistoryMessageToRedis(entity);
}
public void save(T entity) {
this.setEntityCommonProperty(entity, "INSERT");
this.getHibernateTemplate().save(entity);
this.flushCurSession();
this.sendHistoryMessageToRedis(entity);
}
public void saveOrUpdate(T entity) {
this.setEntityCommonProperty(entity, "IorU");
this.getHibernateTemplate().saveOrUpdate(entity);
this.flushCurSession();
this.sendHistoryMessageToRedis(entity);
}
public void saveOrUpdate2(T entity) {
this.setEntityCommonProperty(entity, "IorU");
this.getHibernateTemplate().saveOrUpdate(entity);
this.sendHistoryMessageToRedis(entity);
}
public void saveOrUpdateAll(Collection<T> entities) {
this.getHibernateTemplate().saveOrUpdateAll(entities);
this.flushCurSession();
this.setEntityCommonPropertyNew(entities, "IorUAL");
this.sendHistoryMessageToRedisNew(entities);
}
public void saveOrUpdateAllWh(Collection<T> entities) {
this.getHibernateTemplate().saveOrUpdateAll(entities);
this.flushCurSession();
this.setEntityCommonPropertyNew(entities, "IorUAL");
this.sendHistoryMessageToRedisNewWh(entities);
}
public void delete(T entity) {
this.setEntityCommonProperty(entity, "DELETE");
this.getHibernateTemplate().delete(entity);
this.flushCurSession();
this.sendHistoryMessageToRedis(entity);
}
public void deleteByKey(PK id) {
this.delete(this.load(id));
}
public void deleteAll(Collection<T> entities) {
this.getHibernateTemplate().deleteAll(entities);
this.flushCurSession();
this.setEntityCommonPropertyNew(entities, "DELETE");
this.sendHistoryMessageToRedisNew(entities);
}
public List<T> find(String queryString) {
return this.getHibernateTemplate().find(queryString);
}
public List<T> find(String queryString, Object values) {
return this.getHibernateTemplate().find(queryString, values);
}
public List find(String queryString, Object[] values) {
return this.getHibernateTemplate().find(queryString, values);
}
public List<T> findByNamedParam(String queryString, String paramNames, Object values) {
return this.getHibernateTemplate().findByNamedParam(queryString, paramNames, values);
}
public void lock(T entity, LockMode lock) {
this.getHibernateTemplate().lock(entity, lock);
}
public void flush() {
this.getHibernateTemplate().flush();
}
public List listBySQL(String sql) {
Session session = this.getCrSession();
return session.createSQLQuery(sql).list();
}
public List findBySQL(String sql) {
Session s = this.getHibernateTemplate().getSessionFactory().getCurrentSession();
Query q = s.createSQLQuery(sql);
return q.list();
}
public List<T> findBySQL(String sql, Class clazz) {
Session s = this.getHibernateTemplate().getSessionFactory().getCurrentSession();
Query q = s.createSQLQuery(sql).addEntity(clazz);
return q.list();
}
public List<T> findBySQL(String sql, Class clazz, Object... args) {
Session s = this.getHibernateTemplate().getSessionFactory().getCurrentSession();
Query q = s.createSQLQuery(sql).addEntity(clazz);
return q.list();
}
public T findBySQLOnly(String sql) {
Session s = this.getHibernateTemplate().getSessionFactory().getCurrentSession();
Query q = s.createSQLQuery(sql);
return (Serializable)q.uniqueResult();
}
public List<String> findDistStringList(String strSql) {
Query query = this.getCrSession().createQuery(strSql);
return query.list();
}
public T comTblRead(String sql) {
Session s = this.getHibernateTemplate().getSessionFactory().getCurrentSession();
Query q = s.createQuery(sql);
Object obj = q.uniqueResult();
return (Serializable)obj;
}
public T comTblReadLock(String sql, String tbl_name) {
Session s = this.getHibernateTemplate().getSessionFactory().getCurrentSession();
Query q = s.createQuery(sql);
q.setLockMode(tbl_name, LockMode.READ);
Object obj = q.uniqueResult();
return (Serializable)obj;
}
public List comTblRead2nd(String sql) {
Session s = this.getHibernateTemplate().getSessionFactory().getCurrentSession();
Query q = s.createQuery(sql);
return q.list();
}
public T findOnlyOne(String queryString, Object[] values) {
return (Serializable)this.getHibernateTemplate().find(queryString, values).get(0);
}
public Session getCrSession() {
return this.getHibernateTemplate().getSessionFactory().getCurrentSession();
}
public void flushCurSession() {
Session curSession = this.getCrSession();
curSession.flush();
}
public long getCountBySql(String sql) {
return ((Long)this.getHibernateTemplate().iterate(sql).next()).longValue();
}
public List<T> list(String hql, Object... values) {
Query query = this.createQuery(hql, values);
return query.list();
}
public T uniqueResult(String hql, Object... values) {
Query query = this.createQuery(hql, values);
return (Serializable)query.uniqueResult();
}
protected Query createQuery(String hql, Object... values) {
Query query = this.getCrSession().createQuery(hql);
if(values != null) {
for(int i = 0; i < values.length; ++i) {
query.setParameter(i, values[i]);
}
}
return query;
}
public List<T> listWithLock(String hql, Object... values) {
Session session = this.getCrSession();
Query query = this.createQuery(hql, values);
List<T> ts = query.list();
Iterator var6 = ts.iterator();
while(var6.hasNext()) {
T t = (Serializable)var6.next();
session.lock(t, LockMode.UPGRADE);
}
return ts;
}
public T uniqueResultWithLock(String hql, Object... values) {
Session session = this.getCrSession();
Query query = this.createQuery(hql, values);
T t = (Serializable)query.uniqueResult();
if(t == null) {
return t;
} else {
session.lock(t, LockMode.UPGRADE);
return t;
}
}
}
com.dx.mes.common.core.his.HistoryManager
package com.dx.mes.common.core.his;
import com.alibaba.fastjson.JSON;
import com.dx.mes.common.bean.entity.HisXml;
import com.dx.mes.common.core.rabbitmq.RabbitmqManager;
import com.dx.mes.common.core.redis.RedisManager;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import redis.clients.jedis.Jedis;
public class HistoryManager {
@Resource
private RedisManager redisManager;
@Resource
private RabbitmqManager rabbitmqManager;
public static final String RETURN_CODE_DEF_XML = "0000000";
private static final Logger logger = Logger.getLogger(HistoryManager.class);
public HistoryManager() {
}
public boolean isTransactionSuccessed(String rtnMessage) {
return rtnMessage.indexOf("0000000") != -1;
}
public void sendHistoryMessageToRabbitMQ(String evt_no) {
Jedis jedis = null;
new ArrayList();
try {
jedis = this.redisManager.getJedis();
String redisKey = "tempData_for_MQ_" + evt_no;
logger.info("Send MQ's Key:" + redisKey);
String json_str = jedis.get(redisKey);
if(json_str != null) {
logger.info("Getted redis json");
List<HisXml> hisXmlList = JSON.parseArray(json_str, HisXml.class);
for(int i = 0; i < hisXmlList.size(); ++i) {
HisXml hisXml = (HisXml)hisXmlList.get(i);
this.rabbitmqManager.setMessage(hisXml.getTableHistoryConfig().getQueueName(), hisXml.getXml());
}
logger.info("Send info to MQ success");
jedis.del(redisKey);
}
} catch (Exception var11) {
var11.printStackTrace();
} finally {
this.redisManager.returnResource(jedis);
}
}
public void delMessageInRedis(String evt_no) {
Jedis jedis = null;
try {
jedis = this.redisManager.getJedis();
String redisKey = "tempData_for_MQ_" + evt_no;
byte[] bs = jedis.get(redisKey.getBytes());
if(bs != null) {
jedis.del(redisKey.getBytes());
}
} catch (Exception var8) {
var8.printStackTrace();
} finally {
this.redisManager.returnResource(jedis);
}
}
}
com.dx.mes.common.core.rabbitmq.BaseConnFactory
package com.dx.mes.common.core.rabbitmq;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.AMQP.BasicProperties;
import java.io.IOException;
import java.util.Map;
public class BaseConnFactory {
private String rabbitMQHost;
private Integer rabbitMQPort;
private String rabbitMQUserName;
private String rabbitMQUserPassword;
public BaseConnFactory() {
}
public String getRabbitMQHost() {
return this.rabbitMQHost;
}
public void setRabbitMQHost(String rabbitMQHost) {
this.rabbitMQHost = rabbitMQHost;
}
public Integer getRabbitMQPort() {
return this.rabbitMQPort;
}
public void setRabbitMQPort(Integer rabbitMQPort) {
this.rabbitMQPort = rabbitMQPort;
}
public String getRabbitMQUserName() {
return this.rabbitMQUserName;
}
public void setRabbitMQUserName(String rabbitMQUserName) {
this.rabbitMQUserName = rabbitMQUserName;
}
public String getRabbitMQUserPassword() {
return this.rabbitMQUserPassword;
}
public void setRabbitMQUserPassword(String rabbitMQUserPassword) {
this.rabbitMQUserPassword = rabbitMQUserPassword;
}
public ConnectionFactory creatConnectionFactory() throws IOException {
ConnectionFactory connFactory = new ConnectionFactory();
connFactory.setHost(this.rabbitMQHost);
connFactory.setPort(this.rabbitMQPort.intValue());
connFactory.setUsername(this.rabbitMQUserName);
connFactory.setPassword(this.rabbitMQUserPassword);
return connFactory;
}
public void addSAPREQProc(String qName, String sapreq) throws Exception {
Connection connection = this.creatConnectionFactory().newConnection();
Channel channel = connection.createChannel();
try {
channel.queueDeclare(qName, true, false, false, (Map)null);
channel.basicPublish("", qName, new BasicProperties(), sapreq.getBytes("UTF-8"));
} catch (Exception var9) {
throw var9;
} finally {
if(channel.isOpen()) {
channel.close();
}
if(connection.isOpen()) {
connection.close();
}
}
}
}
com.dx.mes.common.core.rabbitmq.RabbitmqManager
package com.dx.mes.common.core.rabbitmq;
import java.util.ArrayList;
import java.util.List;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
public class RabbitmqManager {
RabbitTemplate rabbitTemplate;
AmqpAdmin admin;
public RabbitmqManager() {
}
public void setAdmin(AmqpAdmin admin) {
this.admin = admin;
}
public void setRabbitTemplate(RabbitTemplate rabbitTemplate) {
this.rabbitTemplate = rabbitTemplate;
}
public void setMessage(String queuename, String message) {
Queue queue = new Queue(queuename, true);
this.admin.declareQueue(queue);
this.rabbitTemplate.convertAndSend(queuename, message);
}
public String recieveMessage(String queuename) {
try {
Queue queue = new Queue(queuename, true);
this.admin.declareQueue(queue);
return (String)this.rabbitTemplate.receiveAndConvert(queuename);
} catch (AmqpException var3) {
System.out.println("cannot get message " + var3.getMessage());
return null;
}
}
public List<String> recieveAllMessage(String queuename) {
try {
List<String> list = new ArrayList();
for(String message = this.recieveMessage(queuename); message != null; message = (String)this.rabbitTemplate.receiveAndConvert(queuename)) {
list.add(message);
TopicExchange exchange = new TopicExchange("Exchang_" + queuename, true, false);
Queue queue = new Queue(queuename, true);
this.admin.declareQueue(queue);
this.admin.declareBinding(BindingBuilder.bind(queue).to(exchange).with(queuename));
}
return list;
} catch (AmqpException var6) {
System.out.println("cannot get message " + var6.getMessage());
return null;
}
}
}
com.dx.mes.common.core.redis.RedisManager
package com.dx.mes.common.core.redis;
import org.apache.log4j.Logger;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class RedisManager {
private final Logger logger = Logger.getLogger(RedisManager.class);
private JedisPool jedisPool = null;
private String redis_addr;
private int redis_port;
private int max_active;
private int max_idle;
private int max_wait_millis;
private boolean test_on_borrow;
public RedisManager() {
}
public String getRedis_addr() {
return this.redis_addr;
}
public void setRedis_addr(String redis_addr) {
this.redis_addr = redis_addr;
}
public int getRedis_port() {
return this.redis_port;
}
public void setRedis_port(int redis_port) {
this.redis_port = redis_port;
}
public int getMax_active() {
return this.max_active;
}
public void setMax_active(int max_active) {
this.max_active = max_active;
}
public int getMax_idle() {
return this.max_idle;
}
public void setMax_idle(int max_idle) {
this.max_idle = max_idle;
}
public int getMax_wait_millis() {
return this.max_wait_millis;
}
public void setMax_wait_millis(int max_wait_millis) {
this.max_wait_millis = max_wait_millis;
}
public boolean isTest_on_borrow() {
return this.test_on_borrow;
}
public void setTest_on_borrow(boolean test_on_borrow) {
this.test_on_borrow = test_on_borrow;
}
public void initRedisPool() {
if(this.jedisPool == null) {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(this.max_active);
config.setMaxIdle(this.max_idle);
config.setMaxWaitMillis((long)this.max_wait_millis);
config.setTestOnBorrow(this.test_on_borrow);
this.jedisPool = new JedisPool(config, this.redis_addr, this.redis_port);
}
}
public Jedis getJedis() {
Jedis jedis = null;
if(this.jedisPool == null) {
return null;
} else {
try {
if(this.jedisPool != null) {
jedis = this.jedisPool.getResource();
}
} catch (Exception var3) {
this.logger.error("Get jedis error : " + var3);
}
return jedis;
}
}
public void returnResource(Jedis redis) {
if(redis != null) {
this.jedisPool.returnResource(redis);
}
}
}

浙公网安备 33010602011771号