提交
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
package com.chaozhanggui.system.cashierservice.util;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
|
||||
public class AESUtil {
|
||||
|
||||
|
||||
/**
|
||||
* AES算法加密
|
||||
* @Param:text原文
|
||||
* @Param:key密钥
|
||||
* */
|
||||
public static String aesEncrypt(String text,String key) throws Exception {
|
||||
// 创建AES加密算法实例(根据传入指定的秘钥进行加密)
|
||||
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
|
||||
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
|
||||
|
||||
// 初始化为加密模式,并将密钥注入到算法中
|
||||
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
|
||||
|
||||
// 将传入的文本加密
|
||||
byte[] encrypted = cipher.doFinal(text.getBytes());
|
||||
|
||||
//生成密文
|
||||
// 将密文进行Base64编码,方便传输
|
||||
System.out.println("加密后的字节数组:"+ Arrays.toString(encrypted));
|
||||
return Base64.getEncoder().encodeToString(encrypted);
|
||||
}
|
||||
|
||||
/**
|
||||
* AES算法解密
|
||||
* @Param:base64Encrypted密文
|
||||
* @Param:key密钥 (需要使用长度为16、24或32的字节数组作为AES算法的密钥,否则就会遇到java.security.InvalidKeyException异常)
|
||||
*
|
||||
* */
|
||||
public static String aesDecrypt(String base64Encrypted,String key)throws Exception{
|
||||
// 创建AES解密算法实例
|
||||
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
|
||||
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
|
||||
|
||||
// 初始化为解密模式,并将密钥注入到算法中
|
||||
cipher.init(Cipher.DECRYPT_MODE, keySpec);
|
||||
|
||||
// 将Base64编码的密文解码
|
||||
byte[] encrypted = Base64.getDecoder().decode(base64Encrypted);
|
||||
|
||||
// 解密
|
||||
byte[] decrypted = cipher.doFinal(encrypted);
|
||||
return new String(decrypted);
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
String encData= aesEncrypt("张少清","202311210926ojbk");
|
||||
System.out.println("加密后的数据:"+encData);
|
||||
System.out.println("解密数据:"+aesDecrypt(encData,"202311210926ojbk"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package com.chaozhanggui.system.cashierservice.util;
|
||||
|
||||
import org.apache.commons.beanutils.BeanUtils;
|
||||
import org.apache.commons.beanutils.PropertyUtilsBean;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import java.beans.BeanInfo;
|
||||
import java.beans.Introspector;
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.*;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
public class BeanUtil {
|
||||
|
||||
// Map --> Bean 2: 利用org.apache.commons.beanutils 工具类实现 Map --> Bean
|
||||
public static void transMap2Bean2(Map<String, Object> map, Object obj) {
|
||||
if (map == null || obj == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
BeanUtils.populate(obj, map);
|
||||
} catch (Exception e) {
|
||||
System.out.println("transMap2Bean2 Error " + e);
|
||||
}
|
||||
}
|
||||
|
||||
// Map --> Bean 1: 利用Introspector,PropertyDescriptor实现 Map --> Bean
|
||||
public static void transMap2Bean(Map<String, Object> map, Object obj) {
|
||||
try {
|
||||
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
|
||||
PropertyDescriptor[] propertyDescriptors = beanInfo
|
||||
.getPropertyDescriptors();
|
||||
|
||||
for (PropertyDescriptor property : propertyDescriptors) {
|
||||
String key = property.getName();
|
||||
|
||||
if (map.containsKey(key)) {
|
||||
Object value = map.get(key);
|
||||
// 得到property对应的setter方法
|
||||
Method setter = property.getWriteMethod();
|
||||
setter.invoke(obj, value);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
System.out.println("transMap2Bean Error " + e);
|
||||
}
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
// Bean --> Map 1: 利用Introspector和PropertyDescriptor 将Bean --> Map
|
||||
public static Map<String, Object> transBean2Map(Object obj) {
|
||||
if (obj == null) {
|
||||
return null;
|
||||
}
|
||||
Map<String, Object> map = new HashMap<String, Object>();
|
||||
try {
|
||||
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
|
||||
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
|
||||
for (PropertyDescriptor property : propertyDescriptors) {
|
||||
String key = property.getName();
|
||||
|
||||
// 过滤class属性
|
||||
if (!key.equals("class")) {
|
||||
// 得到property对应的getter方法
|
||||
Method getter = property.getReadMethod();
|
||||
Object value = getter.invoke(obj);
|
||||
if(null !=value && !"".equals(value))
|
||||
map.put(key, value);
|
||||
}
|
||||
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println("transBean2Map Error " + e);
|
||||
}
|
||||
return map;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public static LinkedHashMap<String, Object> transBeanMap(Object obj) {
|
||||
if (obj == null) {
|
||||
return null;
|
||||
}
|
||||
LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
|
||||
try {
|
||||
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
|
||||
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
|
||||
for (PropertyDescriptor property : propertyDescriptors) {
|
||||
String key = property.getName();
|
||||
|
||||
// 过滤class属性
|
||||
if (!key.equals("class")) {
|
||||
// 得到property对应的getter方法
|
||||
Method getter = property.getReadMethod();
|
||||
Object value = getter.invoke(obj);
|
||||
if(null !=value && !"".equals(value))
|
||||
map.put(key, value);
|
||||
}
|
||||
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println("transBean2Map Error " + e);
|
||||
}
|
||||
return map;
|
||||
|
||||
}
|
||||
|
||||
public static String mapOrderStr(Map<String, Object> map) {
|
||||
List<Entry<String, Object>> list = new ArrayList<Entry<String, Object>>(map.entrySet());
|
||||
Collections.sort(list, new Comparator<Entry<String, Object>>() {
|
||||
public int compare(Entry<String, Object> o1, Entry<String, Object> o2) {
|
||||
return o1.getKey().compareTo(o2.getKey());
|
||||
}
|
||||
});
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Entry<String, Object> mapping : list) {
|
||||
sb.append(mapping.getKey() + "=" + mapping.getValue() + "&");
|
||||
}
|
||||
return sb.substring(0, sb.length() - 1);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* 将源的属性复制到目标属性上去
|
||||
* @param src
|
||||
* @param dest
|
||||
* @lastModified
|
||||
* @history
|
||||
*/
|
||||
public static void copyProperties(Object dest,Object src) {
|
||||
if (src == null || dest == null) {
|
||||
return;
|
||||
}
|
||||
// 获取所有的get/set 方法对应的属性
|
||||
PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
|
||||
PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(src);
|
||||
|
||||
for (int i = 0; i < descriptors.length; i++) {
|
||||
PropertyDescriptor propItem = descriptors[i];
|
||||
// 过滤setclass/getclass属性
|
||||
if ("class".equals(propItem.getName())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
Method method = propItem.getReadMethod();
|
||||
// 通过get方法获取对应的值
|
||||
Object val = method.invoke(src);
|
||||
// 如果是空,不做处理
|
||||
if (null == val) {
|
||||
continue;
|
||||
}
|
||||
if(val instanceof String) {
|
||||
if(StringUtils.isBlank(val.toString())) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// 值复制
|
||||
PropertyDescriptor prop = propertyUtilsBean.getPropertyDescriptor(dest, propItem.getName());
|
||||
// 调用写方法,设置值
|
||||
if (null != prop && prop.getWriteMethod() != null) {
|
||||
prop.getWriteMethod().invoke(dest, val);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static <T> T mapToEntity(Map<String, Object> map, Class<T> entity) {
|
||||
T t = null;
|
||||
try {
|
||||
t = entity.newInstance();
|
||||
for(Field field : entity.getDeclaredFields()) {
|
||||
if (map.containsKey(field.getName())) {
|
||||
boolean flag = field.isAccessible();
|
||||
field.setAccessible(true);
|
||||
Object object = map.get(field.getName());
|
||||
if (object!= null && field.getType().isAssignableFrom(object.getClass())) {
|
||||
field.set(t, object);
|
||||
}
|
||||
field.setAccessible(flag);
|
||||
}
|
||||
}
|
||||
return t;
|
||||
} catch (InstantiationException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return t;
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.chaozhanggui.system.cashierservice.util;
|
||||
|
||||
import cn.hutool.core.codec.Base64;
|
||||
|
||||
import java.security.Key;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.SecretKeyFactory;
|
||||
import javax.crypto.spec.DESedeKeySpec;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
|
||||
|
||||
public class DESUtil {
|
||||
|
||||
private final static String secretKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwN6xgd6Ad8v2hIIsQVnbt8a3JituR8o4Tc3B5WlcFR55bz4OMqrG/356Ur3cPbc2Fe8ArNd/0gZbC9q56Eb16JTkVNA/fye4SXznWxdyBPR7+guuJZHc/VW2fKH2lfZ2P3Tt0QkKZZoawYOGSMdIvO+WqK44updyax0ikK6JlNQIDAQAB";
|
||||
// 向量
|
||||
private final static String iv = "ggboy123";
|
||||
// 加解密统一使用的编码方式
|
||||
private final static String encoding = "utf-8";
|
||||
|
||||
/**
|
||||
* @Title: encode
|
||||
* @Description: TODO(加密)
|
||||
* @param plainText
|
||||
* @author gangyu2
|
||||
* @date 2018年11月20日下午1:19:19
|
||||
*/
|
||||
public static String encode(String plainText){
|
||||
Key deskey = null;
|
||||
DESedeKeySpec spec;
|
||||
try {
|
||||
spec = new DESedeKeySpec(secretKey.getBytes());
|
||||
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
|
||||
deskey = keyfactory.generateSecret(spec);
|
||||
|
||||
Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
|
||||
IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
|
||||
cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
|
||||
byte[] encryptData = cipher.doFinal(plainText.getBytes(encoding));
|
||||
return Base64.encode(encryptData);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @Title: decode
|
||||
* @Description: TODO(解密)
|
||||
* @param encryptText
|
||||
* @author gangyu2
|
||||
* @date 2018年11月20日下午1:19:37
|
||||
*/
|
||||
public static String decode(String encryptText){
|
||||
try{
|
||||
|
||||
Key deskey = null;
|
||||
DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
|
||||
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
|
||||
deskey = keyfactory.generateSecret(spec);
|
||||
Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
|
||||
IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
|
||||
cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
|
||||
|
||||
byte[] decryptData = cipher.doFinal(Base64.decode(encryptText));
|
||||
|
||||
return new String(decryptData, encoding);
|
||||
}catch(Exception e){
|
||||
e.printStackTrace();
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,354 @@
|
||||
package com.chaozhanggui.system.cashierservice.util;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* Created by SEELE on 2018/4/19.
|
||||
*/
|
||||
public class DateUtils {
|
||||
|
||||
private final static SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");
|
||||
private final static SimpleDateFormat sdfDay = new SimpleDateFormat("yyyy-MM-dd");
|
||||
private final static SimpleDateFormat sdfDays = new SimpleDateFormat("yyyyMMdd");
|
||||
private final static SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
private final static SimpleDateFormat sdfTimeSS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
|
||||
private final static SimpleDateFormat sdfTimes = new SimpleDateFormat("yyyyMMddHHmmss");
|
||||
|
||||
|
||||
|
||||
|
||||
private final static SimpleDateFormat sdfday = new SimpleDateFormat("MM-dd HH:mm");
|
||||
|
||||
|
||||
public static Date getNewDate(Date date, Integer type, Integer interval) throws ParseException {
|
||||
Calendar c = Calendar.getInstance();
|
||||
c.setTime(date);
|
||||
switch (type) {
|
||||
case 1:
|
||||
c.set(Calendar.YEAR, (c.get(Calendar.YEAR) + interval));
|
||||
break;
|
||||
case 2:
|
||||
c.set(Calendar.MONTH, (c.get(Calendar.MONTH) + interval));
|
||||
break;
|
||||
case 3:
|
||||
c.set(Calendar.DATE, (c.get(Calendar.DATE) + interval));
|
||||
break;
|
||||
case 4:
|
||||
c.set(Calendar.HOUR, (c.get(Calendar.HOUR) + interval));
|
||||
break;
|
||||
case 5:
|
||||
c.set(Calendar.MINUTE, (c.get(Calendar.MINUTE) + interval));
|
||||
break;
|
||||
default:
|
||||
c.set(Calendar.SECOND, (c.get(Calendar.SECOND) + interval));
|
||||
break;
|
||||
}
|
||||
Date newDate = c.getTime();
|
||||
return sdfTime.parse(sdfTime.format(newDate));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取YYYY格式
|
||||
* @return
|
||||
*/
|
||||
public static String getSdfTimes() {
|
||||
return sdfTimes.format(new Date());
|
||||
}
|
||||
|
||||
|
||||
public static String getNextSdfTimes(Date date){
|
||||
return sdfTimes.format(date);
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static String getTimes(Date date){
|
||||
return sdfday.format(date);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取YYYY格式
|
||||
* @return
|
||||
*/
|
||||
public static String getYear() {
|
||||
return sdfYear.format(new Date());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取YYYY-MM-DD格式
|
||||
* @return
|
||||
*/
|
||||
public static String getDay() {
|
||||
return sdfDay.format(new Date());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取YYYYMMDD格式
|
||||
* @return
|
||||
*/
|
||||
public static String getDays(){
|
||||
return sdfDays.format(new Date());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取YYYY-MM-DD HH:mm:ss格式
|
||||
* @return
|
||||
*/
|
||||
public static String getTime(Date date) {
|
||||
return sdfTime.format(date);
|
||||
}
|
||||
|
||||
/**
|
||||
* @Title: compareDate
|
||||
* @Description: TODO(日期比较,如果s>=e 返回true 否则返回false)
|
||||
* @param s
|
||||
* @param e
|
||||
* @return boolean
|
||||
* @throws
|
||||
* @author fh
|
||||
*/
|
||||
public static boolean compareDate(String s, String e) {
|
||||
if(fomatDate(s)==null||fomatDate(e)==null){
|
||||
return false;
|
||||
}
|
||||
return fomatDate(s).getTime() >=fomatDate(e).getTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化日期
|
||||
* @return
|
||||
*/
|
||||
public static Date fomatDate(String date) {
|
||||
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
|
||||
try {
|
||||
return fmt.parse(date);
|
||||
} catch (ParseException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验日期是否合法
|
||||
* @return
|
||||
*/
|
||||
public static boolean isValidDate(String s) {
|
||||
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
|
||||
try {
|
||||
fmt.parse(s);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param startTime
|
||||
* @param endTime
|
||||
* @return
|
||||
*/
|
||||
public static int getDiffYear(String startTime,String endTime) {
|
||||
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
|
||||
try {
|
||||
//long aa=0;
|
||||
int years=(int) (((fmt.parse(endTime).getTime()-fmt.parse(startTime).getTime())/ (1000 * 60 * 60 * 24))/365);
|
||||
return years;
|
||||
} catch (Exception e) {
|
||||
// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* <li>功能描述:时间相减得到天数
|
||||
* @param beginDateStr
|
||||
* @param endDateStr
|
||||
* @return
|
||||
* long
|
||||
* @author Administrator
|
||||
*/
|
||||
public static long getDaySub(String beginDateStr,String endDateStr){
|
||||
long day=0;
|
||||
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
|
||||
Date beginDate = null;
|
||||
Date endDate = null;
|
||||
|
||||
try {
|
||||
beginDate = format.parse(beginDateStr);
|
||||
endDate= format.parse(endDateStr);
|
||||
} catch (ParseException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
day=(endDate.getTime()-beginDate.getTime())/(24*60*60*1000);
|
||||
//System.out.println("相隔的天数="+day);
|
||||
|
||||
return day;
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到n天之后的日期
|
||||
* @param days
|
||||
* @return
|
||||
*/
|
||||
public static String getAfterDayDate(String days) {
|
||||
int daysInt = Integer.parseInt(days);
|
||||
|
||||
Calendar canlendar = Calendar.getInstance(); // java.util包
|
||||
canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
|
||||
Date date = canlendar.getTime();
|
||||
|
||||
SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
String dateStr = sdfd.format(date);
|
||||
|
||||
return dateStr;
|
||||
}
|
||||
/**
|
||||
* 得到n天之后的日期
|
||||
* @param days
|
||||
* @return
|
||||
*/
|
||||
public static String getAfterDate(Date openDate,String days) {
|
||||
int daysInt = Integer.parseInt(days);
|
||||
|
||||
Calendar canlendar = Calendar.getInstance(); // java.util包
|
||||
canlendar.setTime(openDate);
|
||||
canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
|
||||
Date date = canlendar.getTime();
|
||||
SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
String dateStr = sdfd.format(date);
|
||||
return dateStr;
|
||||
}
|
||||
public static String getAfterDate1(Date openDate,String year) {
|
||||
int daysInt = Integer.parseInt(year);
|
||||
|
||||
Calendar canlendar = Calendar.getInstance(); // java.util包
|
||||
canlendar.setTime(openDate);
|
||||
canlendar.add(Calendar.YEAR, daysInt); // 日期减 如果不够减会将月变动
|
||||
Date date = canlendar.getTime();
|
||||
SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
String dateStr = sdfd.format(date);
|
||||
return dateStr;
|
||||
}
|
||||
public static Date getAfterDateStr(Date openDate,String days) {
|
||||
int daysInt = Integer.parseInt(days);
|
||||
|
||||
Calendar canlendar = Calendar.getInstance(); // java.util包
|
||||
canlendar.setTime(openDate);
|
||||
canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
|
||||
Date date = canlendar.getTime();
|
||||
return date;
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到n天之后是周几
|
||||
* @param days
|
||||
* @return
|
||||
*/
|
||||
public static String getAfterDayWeek(String days) {
|
||||
int daysInt = Integer.parseInt(days);
|
||||
Calendar canlendar = Calendar.getInstance(); // java.util包
|
||||
canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
|
||||
Date date = canlendar.getTime();
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("E");
|
||||
String dateStr = sdf.format(date);
|
||||
return dateStr;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println(getTimes(new Date()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化日期为时分秒
|
||||
* @param date
|
||||
* @return
|
||||
*/
|
||||
public static Date fomatDateTime(String date) {
|
||||
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
try {
|
||||
return fmt.parse(date);
|
||||
} catch (ParseException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static Date fomatDateTime1(String date) {
|
||||
DateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
|
||||
try {
|
||||
return fmt.parse(date);
|
||||
} catch (ParseException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static java.util.Date parse(String dateString, String dateFormat) {
|
||||
if ("".equals(dateString.trim()) || dateString == null) {
|
||||
return null;
|
||||
}
|
||||
DateFormat sdf = new SimpleDateFormat(dateFormat);
|
||||
Date date = null;
|
||||
try {
|
||||
date = sdf.parse(dateString);
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return date;
|
||||
}
|
||||
|
||||
|
||||
private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
|
||||
public static Date convertDate(String date) {
|
||||
try {
|
||||
return sdf.parse(date);
|
||||
} catch (ParseException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private final static SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
|
||||
public static Date convertDateByString(String str){
|
||||
StringBuilder sb=new StringBuilder();
|
||||
sb.append(str.substring(0,4));
|
||||
sb.append("-");
|
||||
sb.append(str.substring(4,6));
|
||||
sb.append("-");
|
||||
sb.append(str.substring(6,8));
|
||||
sb.append(" ");
|
||||
sb.append(str.substring(8,10));
|
||||
sb.append(":");
|
||||
sb.append(str.substring(10,12));
|
||||
sb.append(":");
|
||||
sb.append(str.substring(12,14));
|
||||
|
||||
return convertDate1(sb.toString());
|
||||
}
|
||||
|
||||
public static Date convertDate1(String date) {
|
||||
try {
|
||||
return sdf1.parse(date);
|
||||
} catch (ParseException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static String formatDateToStr(Date date) {
|
||||
return sdfTime.format(date);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package com.chaozhanggui.system.cashierservice.util;
|
||||
|
||||
|
||||
import org.apache.commons.codec.digest.DigestUtils;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.NameValuePair;
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class FeieyunPrintUtil {
|
||||
|
||||
public static final String URL = "http://api.feieyun.cn/Api/Open/";//不需要修改
|
||||
|
||||
public static final String USER = "chaozhanggui2022@163.com";//*必填*:账号名
|
||||
public static final String UKEY = "UfWkhXxSkeSSscsU";//*必填*: 飞鹅云后台注册账号后生成的UKEY 【备注:这不是填打印机的KEY】
|
||||
public static final String SN = "960238952";//*必填*:打印机编号,必须要在管理后台里添加打印机或调用API接口添加之后,才能调用API
|
||||
|
||||
|
||||
|
||||
public static String printLabelMsg(String sn,String masterId,String productName,Integer number,String date,String money,String remark){
|
||||
|
||||
StringBuffer sb=new StringBuffer();
|
||||
sb.append("<DIRECTION>1</DIRECTION>");
|
||||
sb.append("<TEXT x='120' y='10' font='32*48' w='1' h='1' r='0'>");
|
||||
sb.append(masterId);
|
||||
char paddingCharacter = ' ';
|
||||
sb.append("</TEXT><TEXT x='0' y='80' font='48*48' w='1' h='1' r='0'>");
|
||||
sb.append(productName);
|
||||
sb.append(" ");
|
||||
sb.append(number);
|
||||
sb.append("</TEXT><TEXT x='0' y='120' font='48*48' w='1' h='1' r='0'>");
|
||||
sb.append(remark);
|
||||
|
||||
sb.append("</TEXT><TEXT x='9' y='180' font='12' w='1' h='1' r='0'>");
|
||||
sb.append(date);
|
||||
sb.append(" ");
|
||||
sb.append("¥");
|
||||
sb.append(money);
|
||||
|
||||
String content=sb.toString();
|
||||
|
||||
//通过POST请求,发送打印信息到服务器
|
||||
RequestConfig requestConfig = RequestConfig.custom()
|
||||
.setSocketTimeout(30000)//读取超时
|
||||
.setConnectTimeout(30000)//连接超时
|
||||
.build();
|
||||
|
||||
CloseableHttpClient httpClient = HttpClients.custom()
|
||||
.setDefaultRequestConfig(requestConfig)
|
||||
.build();
|
||||
|
||||
HttpPost post = new HttpPost(URL);
|
||||
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
|
||||
nvps.add(new BasicNameValuePair("user",USER));
|
||||
String STIME = String.valueOf(System.currentTimeMillis()/1000);
|
||||
nvps.add(new BasicNameValuePair("stime",STIME));
|
||||
nvps.add(new BasicNameValuePair("sig",signature(USER,UKEY,STIME)));
|
||||
nvps.add(new BasicNameValuePair("apiname","Open_printLabelMsg"));//固定值,不需要修改
|
||||
nvps.add(new BasicNameValuePair("sn",sn));
|
||||
nvps.add(new BasicNameValuePair("content",content));
|
||||
nvps.add(new BasicNameValuePair("times","1"));//打印联数
|
||||
|
||||
CloseableHttpResponse response = null;
|
||||
String result = null;
|
||||
try
|
||||
{
|
||||
post.setEntity(new UrlEncodedFormEntity(nvps,"utf-8"));
|
||||
response = httpClient.execute(post);
|
||||
int statecode = response.getStatusLine().getStatusCode();
|
||||
if(statecode == 200){
|
||||
HttpEntity httpentity = response.getEntity();
|
||||
if (httpentity != null){
|
||||
//服务器返回的JSON字符串,建议要当做日志记录起来
|
||||
result = EntityUtils.toString(httpentity);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
}
|
||||
finally{
|
||||
try {
|
||||
if(response!=null){
|
||||
response.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
try {
|
||||
post.abort();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
try {
|
||||
httpClient.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return result;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static int getProducrName(String str){
|
||||
int count = 0;
|
||||
int digitCount=0;
|
||||
for (int i=0;i<str.length();i++){
|
||||
if ((str.charAt(i)>='a' && str.charAt(i)<='z') || (str.charAt(i)>='A' && str.charAt(i)<='Z')){
|
||||
count++;
|
||||
}
|
||||
|
||||
if (Character.isDigit(str.charAt(i))) {
|
||||
digitCount++;
|
||||
}
|
||||
}
|
||||
return count+digitCount;
|
||||
}
|
||||
|
||||
private static String signature(String USER,String UKEY,String STIME){
|
||||
String s = DigestUtils.sha1Hex(USER+UKEY+STIME);
|
||||
return s;
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args){
|
||||
printLabelMsg("960238952","#A9","甜橙马黛茶",5,"03-11 15:21","90","加糖");
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package com.chaozhanggui.system.cashierservice.util;
|
||||
|
||||
import org.apache.http.NameValuePair;
|
||||
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.client.utils.URIBuilder;
|
||||
import org.apache.http.entity.ContentType;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class HttpClientUtil {
|
||||
|
||||
|
||||
public static String doGet(String url, Map<String, String> param) {
|
||||
|
||||
// 创建Httpclient对象
|
||||
CloseableHttpClient httpclient = HttpClients.createDefault();
|
||||
|
||||
String resultString = "";
|
||||
CloseableHttpResponse response = null;
|
||||
try {
|
||||
// 创建uri
|
||||
URIBuilder builder = new URIBuilder(url);
|
||||
if (param != null) {
|
||||
for (String key : param.keySet()) {
|
||||
builder.addParameter(key, param.get(key));
|
||||
}
|
||||
}
|
||||
URI uri = builder.build();
|
||||
|
||||
// 创建http GET请求
|
||||
HttpGet httpGet = new HttpGet(uri);
|
||||
|
||||
// 执行请求
|
||||
response = httpclient.execute(httpGet);
|
||||
// 判断返回状态是否为200
|
||||
if (response.getStatusLine().getStatusCode() == 200) {
|
||||
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
try {
|
||||
if (response != null) {
|
||||
response.close();
|
||||
}
|
||||
httpclient.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return resultString;
|
||||
}
|
||||
|
||||
public static String doGet(String url) {
|
||||
return doGet(url, null);
|
||||
}
|
||||
|
||||
public static String doPost(String url, Map<String, String> param) {
|
||||
// 创建Httpclient对象
|
||||
CloseableHttpClient httpClient = HttpClients.createDefault();
|
||||
CloseableHttpResponse response = null;
|
||||
String resultString = "";
|
||||
try {
|
||||
// 创建Http Post请求
|
||||
HttpPost httpPost = new HttpPost(url);
|
||||
// 创建参数列表
|
||||
if (param != null) {
|
||||
List<NameValuePair> paramList = new ArrayList<>();
|
||||
for (String key : param.keySet()) {
|
||||
paramList.add(new BasicNameValuePair(key, param.get(key)));
|
||||
}
|
||||
// 模拟表单
|
||||
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
|
||||
httpPost.setEntity(entity);
|
||||
}
|
||||
// 执行http请求
|
||||
response = httpClient.execute(httpPost);
|
||||
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
try {
|
||||
response.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
return resultString;
|
||||
}
|
||||
|
||||
public static String doPost(String url) {
|
||||
return doPost(url, null);
|
||||
}
|
||||
|
||||
public static String doPostJson(String url, String json) {
|
||||
// 创建Httpclient对象
|
||||
CloseableHttpClient httpClient = HttpClients.createDefault();
|
||||
CloseableHttpResponse response = null;
|
||||
String resultString = "";
|
||||
try {
|
||||
// 创建Http Post请求
|
||||
HttpPost httpPost = new HttpPost(url);
|
||||
// 创建请求内容
|
||||
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
|
||||
httpPost.setEntity(entity);
|
||||
// 执行http请求
|
||||
response = httpClient.execute(httpPost);
|
||||
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
try {
|
||||
response.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
return resultString;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.chaozhanggui.system.cashierservice.util;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
|
||||
/**
|
||||
* @title: IpUtil
|
||||
* @Description TODO
|
||||
* @Author sixic
|
||||
* @Date 2022/11/9 16:00
|
||||
*/
|
||||
public class IpUtil {
|
||||
|
||||
private static final String UNKNOWN = "unknown";
|
||||
private static final String LOCALHOST = "127.0.0.1";
|
||||
private static final String SEPARATOR = ",";
|
||||
|
||||
public static String getIpAddr(HttpServletRequest request) {
|
||||
System.out.println(request);
|
||||
String ipAddress;
|
||||
try {
|
||||
ipAddress = request.getHeader("x-forwarded-for");
|
||||
if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("Proxy-Client-IP");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("WL-Proxy-Client-IP");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getRemoteAddr();
|
||||
if (LOCALHOST.equals(ipAddress)) {
|
||||
InetAddress inet = null;
|
||||
try {
|
||||
inet = InetAddress.getLocalHost();
|
||||
} catch (UnknownHostException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
ipAddress = inet.getHostAddress();
|
||||
}
|
||||
}
|
||||
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
|
||||
// "***.***.***.***".length()
|
||||
if (ipAddress != null && ipAddress.length() > 15) {
|
||||
if (ipAddress.indexOf(SEPARATOR) > 0) {
|
||||
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
ipAddress = "";
|
||||
}
|
||||
return ipAddress;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取ip地址
|
||||
*
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
public static String getIpAddr2(HttpServletRequest request) {
|
||||
String ip = request.getHeader("X-Real-IP");
|
||||
if (ip != null && !"".equals(ip) && !"unknown".equalsIgnoreCase(ip)) {
|
||||
return ip;
|
||||
}
|
||||
ip = request.getHeader("X-Forwarded-For");
|
||||
if (ip != null && !"".equals(ip) && !"unknown".equalsIgnoreCase(ip)) {
|
||||
int index = ip.indexOf(',');
|
||||
if (index != -1) {
|
||||
return ip.substring(0, index);
|
||||
} else {
|
||||
return ip;
|
||||
}
|
||||
} else {
|
||||
return request.getRemoteAddr();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package com.chaozhanggui.system.cashierservice.util;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.alibaba.fastjson.serializer.SerializeConfig;
|
||||
import com.alibaba.fastjson.serializer.SerializerFeature;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author Stone
|
||||
* @version V1.0.0
|
||||
* @date 2020/2/12
|
||||
*/
|
||||
public class JSONUtil {
|
||||
|
||||
|
||||
/**
|
||||
* 将对象转为JSON字符串
|
||||
*
|
||||
* @param obj 被转的对象
|
||||
* @param dateFormat 日期格式,当传null或空串时,则被格式化为时间戳,否则返回指定的格式。例子:yyyy-MM-dd HH:mm:ss(不合法的日期格式会格式化出错)
|
||||
* @param ignoreNull 是否忽略null字段。true时,且当字段的值是null,则不输出该字段
|
||||
* @param noRef 是否不转换成ref。例如false,当字段间是相同的引用之时,则将出现$ref之类的符号替代冗余的值
|
||||
* @param pretty 是否格式化JSON字符串以便有更好的可读性
|
||||
* @return JSON字符串,出异常时抛出
|
||||
*/
|
||||
public static String toJSONString0(Object obj,
|
||||
String dateFormat,
|
||||
boolean ignoreNull,
|
||||
boolean noRef,
|
||||
boolean pretty) {
|
||||
try {
|
||||
List<SerializerFeature> featureList = new ArrayList<>();
|
||||
|
||||
// 当传null时,则返回默认的时间戳,否则则返回指定的格式
|
||||
if (dateFormat != null && dateFormat.length() > 0) {
|
||||
featureList.add(SerializerFeature.WriteDateUseDateFormat);
|
||||
}
|
||||
if (!ignoreNull) {
|
||||
// 当字段的值是null时,依然出现这个字段,即不忽略
|
||||
featureList.add(SerializerFeature.WriteMapNullValue);
|
||||
}
|
||||
if (noRef) {
|
||||
featureList.add(SerializerFeature.DisableCircularReferenceDetect);
|
||||
}
|
||||
if (pretty) {
|
||||
featureList.add(SerializerFeature.PrettyFormat);
|
||||
}
|
||||
|
||||
SerializerFeature[] featureArr = featureList.toArray(new SerializerFeature[featureList.size()]);
|
||||
return JSONObject.toJSONString(obj, SerializeConfig.globalInstance, null, dateFormat,
|
||||
JSON.DEFAULT_GENERATE_FEATURE, featureArr);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Convert object to JSON string, error[" + obj + "]", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将对象转为JSON字符串。
|
||||
* 日期转为特别的格式,不忽略null值的字段,不格式化JSON字符串
|
||||
*
|
||||
* @param obj 被转换的对象
|
||||
* @return JSON字符串,发送异常时抛出
|
||||
*/
|
||||
public static String toJSONString(Object obj) {
|
||||
return toJSONString0(obj, "yyyy-MM-dd HH:mm:ss", false, true, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将对象转为JSON字符串。不抛出异常,专用于日志打印
|
||||
*
|
||||
* @param obj 被转换的对象
|
||||
* @return JSON字符串,出异常时返回null
|
||||
*/
|
||||
public static String toJSONStringNoThrows(Object obj) {
|
||||
try {
|
||||
return toJSONString0(obj, "yyyy-MM-dd HH:mm:ss", false, true, false);
|
||||
} catch (Exception e) {
|
||||
logError(e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析JSON字符串成为一个Object,结果可能是JSONArray(多个)或JSONObject(单个)
|
||||
* (该方法可用于对json字符串不知道是对象还是列表的时候之用)
|
||||
* (假设json字符串多了某个字段,可能是新加上去的,显然转换成JSONEntity会有这个字段)
|
||||
*
|
||||
* @param jsonStr 要解析的JSON字符串
|
||||
* @return 返回JSONEntity,当jsonArrayFlag 为true,表示它是 JSONArray,否则是JSONObject
|
||||
*/
|
||||
public static JSONEntity parseJSONStr2JSONEntity(String jsonStr) {
|
||||
try {
|
||||
Object value = JSON.parse(jsonStr);
|
||||
boolean jsonArrayFlag = false;
|
||||
if (value instanceof JSONArray) {
|
||||
jsonArrayFlag = true;
|
||||
}
|
||||
return new JSONEntity(jsonArrayFlag, value);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Invalid jsonStr,parse error:" + jsonStr, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 字符串转为JSON对象,注意数组类型会抛异常[{name:\"Stone\"}]
|
||||
* (假设json字符串多了某个字段,可能是新加上去的,显然转换成JSONObject时会有这个字段,因为JSONObject就相当于map)
|
||||
*
|
||||
* @param jsonStr 传入的JSON字串
|
||||
* @return 返回转换结果。传入的JSON字串必须是对象而非数组,否则会抛出异常
|
||||
* @author Stone
|
||||
*/
|
||||
public static JSONObject parseJSONStr2JSONObject(String jsonStr) {
|
||||
try {
|
||||
return (JSONObject) JSONObject.parse(jsonStr);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Invalid jsonStr,parse error:" + jsonStr, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 字符串转为JSON数组,注意对象类型,非数组的会抛异常{name:\"Stone\"}
|
||||
* (假设json字符串多了某个字段,可能是新加上去的,显然转换成JSONArray时,其元素会有这个字段,因为JSONArray的元素JSONObject就相当于map)
|
||||
*
|
||||
* @param jsonStr 传入的JSON字串
|
||||
* @return 返回转换结果。当传入的JSON字串是非数组形式时,会抛出异常
|
||||
* @author Stone
|
||||
*/
|
||||
public static JSONArray parseJSONStr2JSONArray(String jsonStr) {
|
||||
try {
|
||||
return (JSONArray) JSONArray.parse(jsonStr);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Invalid jsonStr,parse error:" + jsonStr, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 字符串转为某个类
|
||||
* (日期字段不管是时间戳形式还是yyyy-MM-dd HH:mm:ss的形式都能成功转换)
|
||||
* (假设json字符串多了某个字段,可能是新加上去的,T类没有,转换成T对象的时候,不会抛出异常)
|
||||
*
|
||||
* @param jsonStr 传入的JSON字串
|
||||
* @param clazz 转为什么类型
|
||||
* @return 返回转换结果。当传入的JSON字串是数组形式时,会抛出异常
|
||||
* @author Stone
|
||||
*/
|
||||
public static <T> T parseJSONStr2T(String jsonStr, Class<T> clazz) {
|
||||
try {
|
||||
return JSONObject.parseObject(jsonStr, clazz);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Invalid jsonStr,parse error:" + jsonStr, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 字符串转为某个类的列表
|
||||
* (日期字段不管是时间戳形式还是yyyy-MM-dd HH:mm:ss的形式都能成功转换)
|
||||
* (假设json字符串多了某个字段,可能是新加上去的,T类没有,转换成T对象的时候,不会抛出异常)
|
||||
*
|
||||
* @param jsonStr 传入的JSON字串
|
||||
* @param clazz List里装的元素的类型
|
||||
* @return 返回转换结果。当传入的JSON字串是非数组的形式时会抛出异常
|
||||
* @author Stone
|
||||
*/
|
||||
public static <T> List<T> parseJSONStr2TList(String jsonStr, Class<T> clazz) {
|
||||
try {
|
||||
return JSONObject.parseArray(jsonStr, clazz);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Invalid jsonStr,parse error:" + jsonStr, e);
|
||||
}
|
||||
}
|
||||
|
||||
public static class JSONEntity {
|
||||
public JSONEntity() {
|
||||
}
|
||||
|
||||
public JSONEntity(boolean jsonArrayFlag, Object value) {
|
||||
this.jsonArrayFlag = jsonArrayFlag;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
private boolean jsonArrayFlag;
|
||||
private Object value;
|
||||
|
||||
public boolean getJsonArrayFlag() {
|
||||
return jsonArrayFlag;
|
||||
}
|
||||
|
||||
public Object getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "JSONEntity{" +
|
||||
"jsonArrayFlag=" + jsonArrayFlag +
|
||||
", value=" + value +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
|
||||
private static void logError(Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
package com.chaozhanggui.system.cashierservice.util;
|
||||
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import cn.hutool.json.JSONUtil;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class MD5Util {
|
||||
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(MD5Util.class);
|
||||
|
||||
private static final String hexDigIts[] = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
|
||||
|
||||
public static String encrypt(String plainText) {
|
||||
try {
|
||||
return encrypt(plainText,true);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
log.error("MD5加密异常:",e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @Title: encrypt
|
||||
* @Description: TODO(16位或32位密码)
|
||||
* @param @param
|
||||
* plainText
|
||||
* @param @param
|
||||
* flag true为32位,false为16位
|
||||
* @throws UnsupportedEncodingException
|
||||
*/
|
||||
public static String encrypt(String plainText, boolean flag) throws UnsupportedEncodingException {
|
||||
try {
|
||||
if (ObjectUtil.isEmpty(plainText)) {
|
||||
return null;
|
||||
}
|
||||
MessageDigest md = MessageDigest.getInstance("MD5");
|
||||
String encrStr = byteArrayToHexString(md.digest(plainText.getBytes("UTF-8")));
|
||||
if (flag)
|
||||
return encrStr;
|
||||
else
|
||||
return encrStr.substring(8, 24);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static String encrypt(Object obj,String privateKey){
|
||||
if(obj==null){
|
||||
return null;
|
||||
}
|
||||
Map<String, Object> map = new HashMap<String,Object>();
|
||||
if(obj instanceof Map){
|
||||
map=(Map<String, Object>) obj;
|
||||
}else{
|
||||
map = BeanUtil.transBean2Map(obj);
|
||||
}
|
||||
return encrypt(map,privateKey,true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @Title: encrypt
|
||||
* @Description: TODO(16位或32位密码)
|
||||
* @param @param
|
||||
* plainText
|
||||
* @param @param
|
||||
* flag true为32位,false为16位
|
||||
* @throws UnsupportedEncodingException
|
||||
*/
|
||||
public static String encrypt(Map<String, Object> map, String privateKey,boolean flag) {
|
||||
String param = null;
|
||||
map.remove("sign");
|
||||
map.remove("encrypt");
|
||||
String result = BeanUtil.mapOrderStr(map);
|
||||
if (StringUtils.isEmpty(result)) {
|
||||
return null;
|
||||
}
|
||||
param = encrypt(encrypt(result)+privateKey);
|
||||
if (flag) {
|
||||
return param;
|
||||
} else {
|
||||
param = param.substring(8, 24);
|
||||
}
|
||||
return param;
|
||||
}
|
||||
|
||||
public static Map<String, Object> resultMap = new HashMap<String, Object>();
|
||||
@SuppressWarnings("unchecked")
|
||||
public static Map<String, Object> mapFn(Map<String, Object> map) {
|
||||
for (String key : map.keySet()) {
|
||||
if (map.get(key) != null && map.get(key) != "" && (!key.equals("BTYPE") && !key.equals("SIGN"))) {
|
||||
if (key.equals("INPUT")) {
|
||||
if (map.get(key) != null) {
|
||||
mapFn((Map<String, Object>) map.get(key));
|
||||
}
|
||||
} else {
|
||||
resultMap.put(key, map.get(key));
|
||||
}
|
||||
}
|
||||
}
|
||||
return resultMap;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static boolean check(Object obj,String privateKey){
|
||||
Map<String,Object> map=new HashMap<String,Object>();
|
||||
if(obj==null){
|
||||
return false;
|
||||
}
|
||||
if(obj instanceof Map){
|
||||
map=(Map<String, Object>) obj;
|
||||
}else{
|
||||
map = BeanUtil.transBean2Map(obj);
|
||||
}
|
||||
System.out.println("check:"+ JSONUtil.toJsonStr(map));
|
||||
String sign=(String)map.get("sign");
|
||||
if(sign==null){
|
||||
return false;
|
||||
}
|
||||
String str=encrypt(obj,privateKey);
|
||||
System.out.println("check: "+str);
|
||||
|
||||
return sign.equals(str)?true:false;
|
||||
}
|
||||
|
||||
public static String byteArrayToHexString(byte b[]){
|
||||
StringBuffer resultSb = new StringBuffer();
|
||||
for(int i = 0; i < b.length; i++){
|
||||
resultSb.append(byteToHexString(b[i]));
|
||||
}
|
||||
return resultSb.toString();
|
||||
}
|
||||
|
||||
public static String byteToHexString(byte b){
|
||||
int n = b;
|
||||
if(n < 0){
|
||||
n += 256;
|
||||
}
|
||||
int d1 = n / 16;
|
||||
int d2 = n % 16;
|
||||
return hexDigIts[d1] + hexDigIts[d2];
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.chaozhanggui.system.cashierservice.util;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
|
||||
// 如果第一个参数与第二个参数相等返回0。
|
||||
// 如果第一个参数小于第二个参数返回 -1。
|
||||
// 如果第一个参数大于第二个参数返回 1。
|
||||
public class N {
|
||||
|
||||
public static final int SCALE = 2;
|
||||
|
||||
public static final boolean isZero(BigDecimal num) {
|
||||
return num == null || BigDecimal.ZERO.compareTo(num) == 0;
|
||||
}
|
||||
|
||||
public static final boolean isNull(BigDecimal num) {
|
||||
return num == null;
|
||||
}
|
||||
|
||||
|
||||
public static final boolean eq(BigDecimal n1, BigDecimal n2) {
|
||||
return (!isNull(n1) && !isNull(n2) && n1.compareTo(n2) == 0);//n1==n2
|
||||
}
|
||||
|
||||
public static final boolean gt(BigDecimal n1, BigDecimal n2) {
|
||||
return (!isNull(n1) && !isNull(n2) && n1.compareTo(n2) > 0);//n1>n2
|
||||
}
|
||||
|
||||
public static final boolean egt(BigDecimal n1, BigDecimal n2) {
|
||||
return (!isNull(n1) && !isNull(n2) && n1.compareTo(n2) >= 0);
|
||||
}
|
||||
|
||||
|
||||
public static final BigDecimal mul(BigDecimal b1, BigDecimal b2) {
|
||||
if (isNull(b1) || isNull(b2)) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
return b1.multiply(b2).setScale(SCALE, BigDecimal.ROUND_HALF_UP);
|
||||
}
|
||||
|
||||
|
||||
public static final BigDecimal div(BigDecimal b1, BigDecimal b2) {
|
||||
if (isNull(b1) || isZero(b2)) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
return b1.divide(b2, SCALE, BigDecimal.ROUND_HALF_UP);
|
||||
}
|
||||
|
||||
// public static void main(String[] args){
|
||||
// System.out.println(N.mul(new BigDecimal(0.6),BigDecimal.ONE));
|
||||
// }
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
package com.chaozhanggui.system.cashierservice.util;
|
||||
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.chaozhanggui.system.cashierservice.model.HandoverInfo;
|
||||
import com.chaozhanggui.system.cashierservice.model.OrderDetailPO;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 打印机
|
||||
*/
|
||||
public class PrinterUtils {
|
||||
|
||||
//请求地址
|
||||
private static final String URL_STR = "https://ioe.car900.com/v1/openApi/dev/customPrint.json";
|
||||
//APPID
|
||||
private static final String APP_ID = "ZF544";
|
||||
//USERCODE
|
||||
private static final String USER_CODE = "ZF544";
|
||||
//APPSECRET
|
||||
private static final String APP_SECRET = "2022bsjZF544GAH";
|
||||
|
||||
/**
|
||||
* 获取TOKEN值
|
||||
* @param timestamp 时间戳,13位
|
||||
* @param requestId 请求ID,自定义
|
||||
* @return
|
||||
*/
|
||||
private static Map<String, String> getToken(String timestamp, String requestId) {
|
||||
String token = "";
|
||||
String encode = "";
|
||||
SortedMap<String, Object> map = new TreeMap();
|
||||
map.put("appId", APP_ID);
|
||||
map.put("timestamp", timestamp);
|
||||
map.put("requestId", requestId);
|
||||
map.put("userCode", USER_CODE);
|
||||
Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Map.Entry<String, Object> next = iterator.next();
|
||||
String key = next.getKey();
|
||||
Object value = next.getValue();
|
||||
token += key + value;
|
||||
encode += key + "=" + value + "&";
|
||||
}
|
||||
System.out.println("token"+token);
|
||||
Map<String, String> finalMap = new HashMap<>();
|
||||
finalMap.put("ENCODE",encode);
|
||||
System.out.println("+++++++++++++++"+token + APP_SECRET);
|
||||
finalMap.put("TOKEN", MD5Util.encrypt(token + APP_SECRET).toUpperCase());
|
||||
return finalMap;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 厨房打印机
|
||||
* @param pickupNumber
|
||||
* @param date
|
||||
* @param productName
|
||||
* @param number
|
||||
* @param remark
|
||||
* @return
|
||||
*/
|
||||
public static String getPrintData(String pickupNumber,String date,String productName,Integer number,String remark) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
|
||||
builder.append("<C><B>"+pickupNumber+"</B></C><BR><BR>");
|
||||
builder.append("<S><L>时间: "+date+" </L></S><BR><BR><BR>");
|
||||
|
||||
if(productName.length()>4||remark.length()>4){
|
||||
builder.append("<CS:32>"+productName+" "+number+"</CS><BR>");
|
||||
builder.append("<CS:32>"+remark+" </CS><BR>");
|
||||
}else {
|
||||
builder.append("<B>"+productName+" "+number+"</B><BR>");
|
||||
builder.append("<B>"+remark+" </B><BR>");
|
||||
}
|
||||
builder.append("<OUT:150>");
|
||||
builder.append("<PCUT>");
|
||||
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
|
||||
public static String getCashPrintData(OrderDetailPO detailPO,String type,String orderType){
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
sb.append("<C><B>"+detailPO.getMerchantName()+"</B></C><BR><BR>");
|
||||
sb.append("<C><BOLD>"+type+"【"+detailPO.getMasterId()+"】</BOLD></C><BR><BR>");
|
||||
sb.append("<S><L>订单号: "+detailPO.getOrderNo()+" </L></S><BR>");
|
||||
sb.append("<S><L>交易时间: "+detailPO.getTradeDate()+" </L></S><BR>");
|
||||
sb.append("<S><L>收银员: "+detailPO.getOperator()+" </L></S><BR><BR><BR>");
|
||||
sb.append("------------------------<BR>");
|
||||
char paddingCharacter = ' ';
|
||||
sb.append("<S>"+String.format("%-15s","品名").replace(' ', paddingCharacter)+String.format("%-4s","数量").replace(' ', paddingCharacter)+String.format("%4s","小计").replace(' ', paddingCharacter)+"</S><BR>");
|
||||
for (OrderDetailPO.Detail detail : detailPO.getDetailList()) {
|
||||
if(detail.getProductName().length()>4){
|
||||
|
||||
int count=getProducrName(detail.getProductName());
|
||||
if(count<=0){
|
||||
int length=15-(detail.getProductName().length()-4);
|
||||
sb.append("<S>"+String.format("%-"+length+"s",detail.getProductName()).replace(' ', paddingCharacter)+String.format("%-4s",detail.getNumber()).replace(' ', paddingCharacter)+String.format("%8s",detail.getAmount()).replace(' ', paddingCharacter)+"</S><BR>");
|
||||
}else {
|
||||
int length=15+count-(detail.getProductName().length()-4);
|
||||
sb.append("<S>"+String.format("%-"+length+"s",detail.getProductName()).replace(' ', paddingCharacter)+String.format("%-4s",detail.getNumber()).replace(' ', paddingCharacter)+String.format("%8s",detail.getAmount()).replace(' ', paddingCharacter)+"</S><BR>");
|
||||
}
|
||||
|
||||
}else {
|
||||
sb.append("<S>"+String.format("%-15s",detail.getProductName()).replace(' ', paddingCharacter)+String.format("%-4s",detail.getNumber()).replace(' ', paddingCharacter)+String.format("%8s",detail.getAmount()).replace(' ', paddingCharacter)+"</S><BR>");
|
||||
}
|
||||
|
||||
if(detail.getSpec()!=null&& ObjectUtil.isNotEmpty(detail.getSpec())){
|
||||
sb.append("<S>规格:"+detail.getSpec()+"</S><BR>");
|
||||
}
|
||||
|
||||
sb.append("<BR>");
|
||||
|
||||
}
|
||||
sb.append("------------------------<BR>");
|
||||
String t="¥"+detailPO.getReceiptsAmount();
|
||||
t=String.format("%11s",t).replace(' ', paddingCharacter);
|
||||
if(orderType.equals("return")){
|
||||
sb.append("<F>应退"+t+"</F><BR>");
|
||||
}else {
|
||||
sb.append("<F>应收"+t+"</F><BR>");
|
||||
}
|
||||
if(ObjectUtil.isNotEmpty(detailPO.getPayType())&&ObjectUtil.isNotNull(detailPO.getPayType())&&detailPO.getPayType().equals("deposit")){
|
||||
sb.append("<S>储值¥"+detailPO.getReceiptsAmount()+" </S><BR>");
|
||||
sb.append("------------------------<BR>");
|
||||
sb.append("<S>积分:"+detailPO.getIntegral()+"</S><BR>");
|
||||
}
|
||||
|
||||
sb.append("<S>余额:"+detailPO.getBalance()+"</S><BR>");
|
||||
sb.append("------------------------<BR>");
|
||||
|
||||
if(ObjectUtil.isNotEmpty(detailPO.getRemark())&&ObjectUtil.isNotNull(detailPO.getRemark())){
|
||||
sb.append("<L>备注:"+detailPO.getRemark()+"</L><BR>");
|
||||
}
|
||||
|
||||
|
||||
|
||||
sb.append("<S>打印时间:"+DateUtils.getTime(new Date())+"</S><BR>");
|
||||
|
||||
sb.append("<OUT:180>");
|
||||
sb.append("<PCUT>");
|
||||
return sb.toString();
|
||||
|
||||
}
|
||||
|
||||
|
||||
public static String handoverprintData(HandoverInfo handoverInfo){
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
sb.append("<C><B>"+handoverInfo.getMerchantName()+"</B></C><BR><BR>");
|
||||
sb.append("<C> </C><BR><BR>");
|
||||
sb.append("<C><S><L>交班小票</L></S></C><BR>");
|
||||
sb.append("<S>当班时间: "+handoverInfo.getStartTime()+"</S><BR>");
|
||||
sb.append("<S>交班时间: "+handoverInfo.getEndTime()+"</S><BR>");
|
||||
sb.append("<S>收银员: "+handoverInfo.getStaff()+"</S><BR>");
|
||||
sb.append("<S>当班收入: "+handoverInfo.getTotalAmount()+"</S><BR>");
|
||||
if(ObjectUtil.isNotEmpty(handoverInfo.getPayInfos())&&handoverInfo.getPayInfos().size()>0){
|
||||
for (HandoverInfo.PayInfo payInfo : handoverInfo.getPayInfos()) {
|
||||
sb.append("<S> "+payInfo.getPayType()+": "+payInfo.getAmount()+"</S><BR>");
|
||||
}
|
||||
}
|
||||
sb.append("<S>会员数据</S><BR>");
|
||||
if(ObjectUtil.isNotEmpty(handoverInfo.getMemberData())&&handoverInfo.getMemberData().size()>0){
|
||||
for (HandoverInfo.MemberData memberDatum : handoverInfo.getMemberData()) {
|
||||
sb.append("<S> "+memberDatum.getDeposit()+": "+memberDatum.getAmount()+"</S><BR>");
|
||||
}
|
||||
}
|
||||
sb.append("<S>总收入: "+handoverInfo.getTotalAmount()+"</S><BR>");
|
||||
sb.append("<S>备用金: "+handoverInfo.getImprest()+"</S><BR>");
|
||||
sb.append("<S>应交金额: "+handoverInfo.getPayable()+"</S><BR>");
|
||||
sb.append("<S>上交金额: "+handoverInfo.getHandIn()+"</S><BR>");
|
||||
|
||||
sb.append("<C> </C><BR><BR>");
|
||||
sb.append("<S>总订单数:"+handoverInfo.getOrderNum()+"</S><BR>");
|
||||
sb.append("<S>打印时间:"+DateUtils.getTime(new Date())+"</S><BR>");
|
||||
|
||||
sb.append("<OUT:180>");
|
||||
sb.append("<PCUT>");
|
||||
return sb.toString();
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 打印票据
|
||||
* @throws Exception
|
||||
*/
|
||||
public static void printTickets(Integer actWay ,Integer cn,String devName,String data) {
|
||||
//设备名称
|
||||
//行为方式 1:只打印数据 2:只播放信息 3:打印数据并播放信息
|
||||
// actWay = 3;
|
||||
// //打印联数
|
||||
// int cn = 1;
|
||||
//打印内容
|
||||
//播报语音数据体,字段参考文档IOT_XY_API11001
|
||||
|
||||
String voiceJson = "{\"bizType\":\"2\",\"content\":\"您有一笔新的订单,请及时处理\"}";
|
||||
String time = String.valueOf(System.currentTimeMillis());
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
|
||||
Map<String, String> param = getToken(time, uuid);
|
||||
//参数
|
||||
MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
|
||||
multiValueMap.add("token",param.get("TOKEN"));
|
||||
multiValueMap.add("devName",devName);
|
||||
multiValueMap.add("actWay",actWay);
|
||||
multiValueMap.add("cn",cn);
|
||||
multiValueMap.add("data",data);
|
||||
multiValueMap.add("voiceJson",voiceJson);
|
||||
multiValueMap.add("appId",APP_ID);
|
||||
multiValueMap.add("timestamp",time);
|
||||
multiValueMap.add("requestId",uuid);
|
||||
multiValueMap.add("userCode",USER_CODE);
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
HttpHeaders header = new HttpHeaders();
|
||||
header.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
|
||||
|
||||
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(multiValueMap,header);
|
||||
String httpResponse = restTemplate.postForObject(URL_STR,
|
||||
httpEntity, String.class);
|
||||
|
||||
System.out.println("map"+httpResponse);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public static int getProducrName(String str){
|
||||
int count = 0;
|
||||
int digitCount=0;
|
||||
for (int i=0;i<str.length();i++){
|
||||
if ((str.charAt(i)>='a' && str.charAt(i)<='z') || (str.charAt(i)>='A' && str.charAt(i)<='Z')){
|
||||
count++;
|
||||
}
|
||||
|
||||
if (Character.isDigit(str.charAt(i))) {
|
||||
digitCount++;
|
||||
}
|
||||
}
|
||||
return count+digitCount;
|
||||
}
|
||||
|
||||
public static void main(String[] args)throws Exception {
|
||||
|
||||
//
|
||||
// List<HandoverInfo.PayInfo> payInfos=new ArrayList<>();
|
||||
//
|
||||
// payInfos.add(new HandoverInfo.PayInfo("现金","39.00"));
|
||||
// payInfos.add(new HandoverInfo.PayInfo("微信支付","0.01"));
|
||||
// payInfos.add(new HandoverInfo.PayInfo("储值卡支付","43.00"));
|
||||
// payInfos.add(new HandoverInfo.PayInfo("银行卡支付","20.00"));
|
||||
//
|
||||
// List<HandoverInfo.MemberData> memberDatas=new ArrayList<>();
|
||||
// memberDatas.add(new HandoverInfo.MemberData("43.00","会员消费"));
|
||||
// memberDatas.add(new HandoverInfo.MemberData("43.00","储值支付"));
|
||||
//
|
||||
//
|
||||
//
|
||||
//
|
||||
// HandoverInfo handoverInfo=new HandoverInfo("冠军","2024-03-15 14:57:00","2024-03-15 14:59:00","【POS-1】 001",payInfos,memberDatas,"102.01","0.00","39.00","39.00","4");
|
||||
//
|
||||
//
|
||||
// printTickets(3,1,"ZF544PG03W00002",handoverprintData(handoverInfo));
|
||||
|
||||
|
||||
List<OrderDetailPO.Detail> detailList= new ArrayList<>();
|
||||
OrderDetailPO.Detail detail=new OrderDetailPO.Detail("花香水牛拿铁","1","19000.90","不甜,麻辣");
|
||||
|
||||
OrderDetailPO.Detail detail3=new OrderDetailPO.Detail("单位iiii","4","40000.00",null);
|
||||
OrderDetailPO.Detail detail4=new OrderDetailPO.Detail("喔喔奶茶","1","19000.90","微甜,微辣");
|
||||
detailList.add(detail);
|
||||
detailList.add(detail3);
|
||||
detailList.add(detail4);
|
||||
OrderDetailPO detailPO=new OrderDetailPO("牛叉闪闪","普通打印","#365","DD20240306134718468","2024-03-06 15:00:00","【POS-1】001","79000.80","5049758.96","deposit","0",detailList,"变态辣");
|
||||
|
||||
|
||||
printTickets(1,1,"ZF544PG03W00002",getCashPrintData(detailPO,"结算单",""));
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package com.chaozhanggui.system.cashierservice.util;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
import java.security.Signature;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import javax.crypto.Cipher;
|
||||
import org.apache.tomcat.util.codec.binary.Base64;
|
||||
|
||||
public class RSAUtils {
|
||||
|
||||
|
||||
/**
|
||||
* RSA最大加密明文大小
|
||||
*/
|
||||
private static final int MAX_ENCRYPT_BLOCK = 117;
|
||||
|
||||
/**
|
||||
* RSA最大解密密文大小
|
||||
*/
|
||||
private static final int MAX_DECRYPT_BLOCK = 128;
|
||||
|
||||
/**
|
||||
* 获取密钥对
|
||||
*
|
||||
* @return 密钥对
|
||||
*/
|
||||
public static KeyPair getKeyPair() throws Exception {
|
||||
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
|
||||
generator.initialize(1024);
|
||||
return generator.generateKeyPair();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取私钥
|
||||
*
|
||||
* @param privateKey 私钥字符串
|
||||
* @return
|
||||
*/
|
||||
public static PrivateKey getPrivateKey(String privateKey) throws Exception {
|
||||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||
byte[] decodedKey = Base64.decodeBase64(privateKey.getBytes());
|
||||
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
|
||||
return keyFactory.generatePrivate(keySpec);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取公钥
|
||||
*
|
||||
* @param publicKey 公钥字符串
|
||||
* @return
|
||||
*/
|
||||
public static PublicKey getPublicKey(String publicKey) throws Exception {
|
||||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||
byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes());
|
||||
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
|
||||
return keyFactory.generatePublic(keySpec);
|
||||
}
|
||||
|
||||
/**
|
||||
* RSA加密
|
||||
*
|
||||
* @param data 待加密数据
|
||||
* @param publicKey 公钥
|
||||
* @return
|
||||
*/
|
||||
public static String encrypt(String data, PublicKey publicKey) throws Exception {
|
||||
Cipher cipher = Cipher.getInstance("RSA");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
|
||||
int inputLen = data.getBytes().length;
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
int offset = 0;
|
||||
byte[] cache;
|
||||
int i = 0;
|
||||
// 对数据分段加密
|
||||
while (inputLen - offset > 0) {
|
||||
if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
|
||||
cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
|
||||
} else {
|
||||
cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
|
||||
}
|
||||
out.write(cache, 0, cache.length);
|
||||
i++;
|
||||
offset = i * MAX_ENCRYPT_BLOCK;
|
||||
}
|
||||
byte[] encryptedData = out.toByteArray();
|
||||
out.close();
|
||||
// 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串
|
||||
// 加密后的字符串
|
||||
return new String(Base64.encodeBase64String(encryptedData));
|
||||
}
|
||||
|
||||
/**
|
||||
* RSA解密
|
||||
*
|
||||
* @param data 待解密数据
|
||||
* @param privateKey 私钥
|
||||
* @return
|
||||
*/
|
||||
public static String decrypt(String data, PrivateKey privateKey) throws Exception {
|
||||
Cipher cipher = Cipher.getInstance("RSA");
|
||||
cipher.init(Cipher.DECRYPT_MODE, privateKey);
|
||||
byte[] dataBytes = Base64.decodeBase64(data);
|
||||
int inputLen = dataBytes.length;
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
int offset = 0;
|
||||
byte[] cache;
|
||||
int i = 0;
|
||||
// 对数据分段解密
|
||||
while (inputLen - offset > 0) {
|
||||
if (inputLen - offset > MAX_DECRYPT_BLOCK) {
|
||||
cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);
|
||||
} else {
|
||||
cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
|
||||
}
|
||||
out.write(cache, 0, cache.length);
|
||||
i++;
|
||||
offset = i * MAX_DECRYPT_BLOCK;
|
||||
}
|
||||
byte[] decryptedData = out.toByteArray();
|
||||
out.close();
|
||||
// 解密后的内容
|
||||
return new String(decryptedData, "UTF-8");
|
||||
}
|
||||
|
||||
/**
|
||||
* 签名
|
||||
*
|
||||
* @param data 待签名数据
|
||||
* @param privateKey 私钥
|
||||
* @return 签名
|
||||
*/
|
||||
public static String sign(String data, PrivateKey privateKey) throws Exception {
|
||||
byte[] keyBytes = privateKey.getEncoded();
|
||||
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
|
||||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||
PrivateKey key = keyFactory.generatePrivate(keySpec);
|
||||
Signature signature = Signature.getInstance("MD5withRSA");
|
||||
signature.initSign(key);
|
||||
signature.update(data.getBytes());
|
||||
return new String(Base64.encodeBase64(signature.sign()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 验签
|
||||
*
|
||||
* @param srcData 原始字符串
|
||||
* @param publicKey 公钥
|
||||
* @param sign 签名
|
||||
* @return 是否验签通过
|
||||
*/
|
||||
public static boolean verify(String srcData, PublicKey publicKey, String sign) throws Exception {
|
||||
byte[] keyBytes = publicKey.getEncoded();
|
||||
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
|
||||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||
PublicKey key = keyFactory.generatePublic(keySpec);
|
||||
Signature signature = Signature.getInstance("MD5withRSA");
|
||||
signature.initVerify(key);
|
||||
signature.update(srcData.getBytes());
|
||||
Boolean flag=signature.verify(Base64.decodeBase64(sign.getBytes()));
|
||||
return flag;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
// 生成密钥对
|
||||
// KeyPair keyPair = getKeyPair();
|
||||
// String privateKey = new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded()));
|
||||
// String publicKey = new String(Base64.encodeBase64(keyPair.getPublic().getEncoded()));
|
||||
// System.out.println("私钥:" + privateKey);
|
||||
// System.out.println("公钥:" + publicKey);
|
||||
|
||||
|
||||
String publicKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCMx5HH2xWlwPMPzsO4NTQoWoqZGkrHRvg/15EvBAuMyIfOlP7onES97TXiw8qIw4arDCknke3fld7mpA012TvJSINBYteBOFyBOkVPTlgVRlHYbibgkZh0LJMvQ47uHdk/HSTLjm056MfTgzmMR4IGzmXhhNBWOgeHvxriW4HPLwIDAQAB";
|
||||
String privateKey="MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIzHkcfbFaXA8w/Ow7g1NChaipkaSsdG+D/XkS8EC4zIh86U/uicRL3tNeLDyojDhqsMKSeR7d+V3uakDTXZO8lIg0Fi14E4XIE6RU9OWBVGUdhuJuCRmHQsky9Dju4d2T8dJMuObTnox9ODOYxHggbOZeGE0FY6B4e/GuJbgc8vAgMBAAECgYBEDcFyLH1leEXHkXtZlBaXn1U6t9QIS018hze+06TFtLa57ZrgVZKBgac37M/+lw6Fp0ZJw6iLGgb71bgxHMdiSVPYlSVHLxp42isgafHwty82nt5I47P3+1OQHUD1LUV2HQpMYp7ptQV4jIymZik9ubM79fjT6z3posnrNWAVSQJBAMmkuWaHj8sS13Uz9B9t0jNHtRormxXe2nGiMbV/aQiFx6TvAGR8zEismR2fy0hkMfmH6GXProIimq8ZE5ksiCUCQQCyuquhBPHeRddnUUCjWEwyQV7ChjXdGto+NJ8Bf7LdqXsmdsQR21G1J557gWASZDz3UJcmm6pPxxXlXpziMT/DAkB1OcJfDOhXkriXdoCx1NKi5Ukv0bHzYP91mGl1roCNZ9jM1fVQdgz9IvpQ8pjnmPhErPI6XiaBmUR8DwQJxI3RAkA0mTkfRwxDRLySvFfQepDaDWDs0ICTlG579hKBZ2plT5ZdiIBFXQ0byhAa+sUiRHuosP/6rb8egVGRUhnLe4DvAkBKKr32EI+GSNSrfXktBTaWEkBRW21C6orlCvU7cpoJWb+KBHQzcRCsbDUH2/LM4uM0kuBSz0zK6H6VSWkY8VeR";
|
||||
|
||||
// RSA加密
|
||||
String data = "{\"name\":\"张三\"}";
|
||||
String encryptData = encrypt(data, getPublicKey(publicKey));
|
||||
System.out.println("加密后内容:" + encryptData);
|
||||
// RSA解密
|
||||
String decryptData = decrypt(encryptData, getPrivateKey(privateKey));
|
||||
System.out.println("解密后内容:" + decryptData);
|
||||
|
||||
// RSA签名
|
||||
String sign = sign(data, getPrivateKey(privateKey));
|
||||
|
||||
System.out.println("签名:"+sign);
|
||||
// RSA验签
|
||||
boolean result = verify(data, getPublicKey(publicKey), sign);
|
||||
System.out.print("验签结果:" + result);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
System.out.print("加解密异常");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.chaozhanggui.system.cashierservice.util;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
|
||||
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
|
||||
import org.springframework.data.redis.serializer.RedisSerializer;
|
||||
import redis.clients.jedis.JedisPool;
|
||||
import redis.clients.jedis.JedisPoolConfig;
|
||||
|
||||
/**
|
||||
* @ClassName RedisConfig
|
||||
* @Author Administrator
|
||||
* @Date 2020/08/04
|
||||
* @Version 1.0
|
||||
* @Description
|
||||
*/
|
||||
@Configuration
|
||||
public class RedisConfig {
|
||||
|
||||
// 实例-单例模式
|
||||
private static RedisConfig redisConfig;
|
||||
|
||||
@Value("${spring.redis.host}")
|
||||
private String host;
|
||||
|
||||
@Value("${spring.redis.port}")
|
||||
private int port;
|
||||
|
||||
@Value("${spring.redis.timeout}")
|
||||
private int timeout;
|
||||
|
||||
@Value("${spring.redis.password}")
|
||||
private String password;
|
||||
|
||||
@Value("${spring.redis.jedis.pool.max-idle}")
|
||||
private int maxIdle;
|
||||
|
||||
@Value("${spring.redis.jedis.pool.max-wait}")
|
||||
private long maxWaitMillis;
|
||||
|
||||
@Value("${spring.redis.block-when-exhausted}")
|
||||
private boolean blockWhenExhausted;
|
||||
|
||||
@Value("${spring.redis.database}")
|
||||
private int database;
|
||||
|
||||
/**
|
||||
* 更换序列化器springSession默认序列化
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
@Bean("springSessionDefaultRedisSerializer")
|
||||
public RedisSerializer setSerializer() {
|
||||
return new GenericJackson2JsonRedisSerializer();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public JedisPool redisPoolFactory() {
|
||||
JedisPool jedisPool = new JedisPool();
|
||||
try {
|
||||
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
|
||||
jedisPoolConfig.setMaxIdle(maxIdle);
|
||||
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
|
||||
// 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
|
||||
jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted);
|
||||
// 是否启用pool的jmx管理功能, 默认true
|
||||
jedisPoolConfig.setJmxEnabled(true);
|
||||
jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout,password,database);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return jedisPool;
|
||||
}
|
||||
@Bean
|
||||
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
|
||||
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
|
||||
container.setConnectionFactory(connectionFactory);
|
||||
return container;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.chaozhanggui.system.cashierservice.util;
|
||||
|
||||
/** 功能描述:redis前缀
|
||||
* @params:
|
||||
* @return:
|
||||
* @Author: wgc
|
||||
* @Date: 2020-12-19 15:02
|
||||
*/
|
||||
public class RedisCst {
|
||||
|
||||
|
||||
//在线用户
|
||||
public static final String ONLINE_USER = "ONLINE:USER";
|
||||
public static final String CART = "CZG:CART:";
|
||||
|
||||
}
|
||||
@@ -0,0 +1,580 @@
|
||||
package com.chaozhanggui.system.cashierservice.util;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
import redis.clients.jedis.Jedis;
|
||||
import redis.clients.jedis.JedisPool;
|
||||
import redis.clients.jedis.params.SetParams;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* @ClassName RedisUtil
|
||||
* @Author wgc
|
||||
* @Date 2019/12/9 14:28
|
||||
* @Version 1.0
|
||||
* @Description redis工具类
|
||||
*/
|
||||
@Component
|
||||
public class RedisUtil {
|
||||
// 成功标识
|
||||
private static final int REDIS_SUCCESS = 1;
|
||||
// 失败标识
|
||||
private static final int REDIS_FAILED = -1;
|
||||
@Value("${spring.redis.database}")
|
||||
private int database;
|
||||
|
||||
|
||||
@Autowired
|
||||
private JedisPool pool;
|
||||
|
||||
|
||||
/**
|
||||
* @param key
|
||||
* @param message
|
||||
* @return boolean
|
||||
* @Description: 保存StrinRedisConfigg信息
|
||||
* @author SLy
|
||||
* @date 2018-12-19 19:49
|
||||
*/
|
||||
public Integer saveMessage(String key, String message) {
|
||||
Jedis jedis = null;
|
||||
try {
|
||||
if (StringUtils.isEmpty(key)) {
|
||||
return REDIS_FAILED;
|
||||
}
|
||||
// 从jedis池中获取一个jedis实例
|
||||
jedis = pool.getResource();
|
||||
if (database != 0) {
|
||||
jedis.select(database);
|
||||
}
|
||||
|
||||
jedis.set(key, message);
|
||||
return REDIS_SUCCESS;
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
// 释放对象池,即获取jedis实例使用后要将对象还回去
|
||||
// 释放对象池,即获取jedis实例使用后要将对象还回去
|
||||
if (jedis != null) {
|
||||
jedis.close();
|
||||
}
|
||||
}
|
||||
return REDIS_FAILED;
|
||||
}
|
||||
|
||||
public boolean exists(String key) {
|
||||
Jedis jedis = null;
|
||||
boolean flag = false;
|
||||
try {
|
||||
// 从jedis池中获取一个jedis实例
|
||||
jedis = pool.getResource();
|
||||
if (database != 0) {
|
||||
jedis.select(database);
|
||||
}
|
||||
if (jedis.exists(key)) {
|
||||
return true;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
// 释放对象池,即获取jedis实例使用后要将对象还回去
|
||||
// 释放对象池,即获取jedis实例使用后要将对象还回去
|
||||
if (jedis != null) {
|
||||
jedis.close();
|
||||
}
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 尝试获取分布式锁
|
||||
*
|
||||
* @param jedis Redis客户端
|
||||
* @param lockKey 锁
|
||||
* @param requestId 请求标识
|
||||
* @param millisecondsToExpire 超期时间
|
||||
* @return 是否获取成功
|
||||
*/
|
||||
String luaLock =
|
||||
"local key = KEYS[1] " +
|
||||
"local requestId = KEYS[2] " +
|
||||
"local ttl = tonumber(KEYS[3]) " +
|
||||
"local result = redis.call('setnx', key, requestId) " +
|
||||
"if result == 1 then " +
|
||||
" redis.call('pexpire', key, ttl) " +
|
||||
"else " +
|
||||
" result = -1; " +
|
||||
" local value = redis.call('get', key) " +
|
||||
" if (value == requestId) then " +
|
||||
" result = 1; " +
|
||||
" redis.call('pexpire', key, ttl) " +
|
||||
" end " +
|
||||
"end " +
|
||||
"return result ";
|
||||
|
||||
public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, long millisecondsToExpire) {
|
||||
|
||||
String result = jedis.set(lockKey, requestId, SetParams.setParams().nx().px(millisecondsToExpire));
|
||||
|
||||
if ("OK".equals(result)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 释放分布式锁
|
||||
*
|
||||
* @param lockKey 锁
|
||||
* @param requestId 请求标识
|
||||
* @return 是否释放成功
|
||||
*/
|
||||
public boolean releaseDistributedLock(String lockKey, String requestId) {
|
||||
Jedis jedis = null;
|
||||
try {
|
||||
// 从jedis池中获取一个jedis实例
|
||||
jedis = pool.getResource();
|
||||
if (database != 0) {
|
||||
jedis.select(database);
|
||||
}
|
||||
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
|
||||
Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));
|
||||
if ("true".equals(result)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
// 释放对象池,即获取jedis实例使用后要将对象还回去
|
||||
// 释放对象池,即获取jedis实例使用后要将对象还回去
|
||||
if (jedis != null) {
|
||||
jedis.close();
|
||||
}
|
||||
}
|
||||
return false;
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param key
|
||||
* @param message
|
||||
* @param expire
|
||||
* @return
|
||||
* @Description: 保存String信息(生命周期单位秒)
|
||||
* @author wgc
|
||||
* @date 2018-12-19 19:49
|
||||
*/
|
||||
public Integer saveMessage(String key, String message, int expire) {
|
||||
Jedis jedis = null;
|
||||
try {
|
||||
if (StringUtils.isEmpty(key)) {
|
||||
return REDIS_FAILED;
|
||||
}
|
||||
// 从jedis池中获取一个jedis实例
|
||||
jedis = pool.getResource();
|
||||
if (database != 0) {
|
||||
jedis.select(database);
|
||||
}
|
||||
jedis.set(key, message);
|
||||
jedis.expire(key, expire);
|
||||
|
||||
return REDIS_SUCCESS;
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
// 释放对象池,即获取jedis实例使用后要将对象还回去
|
||||
// 释放对象池,即获取jedis实例使用后要将对象还回去
|
||||
if (jedis != null) {
|
||||
jedis.close();
|
||||
}
|
||||
}
|
||||
return REDIS_FAILED;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param key
|
||||
* @param message
|
||||
* @return
|
||||
* @Description: 保存byte[]信息
|
||||
* @author SLy
|
||||
* @date 2018-12-19 19:49
|
||||
*/
|
||||
public Integer saveMessage(String key, byte[] message) {
|
||||
Jedis jedis = null;
|
||||
try {
|
||||
if (StringUtils.isEmpty(key)) {
|
||||
return REDIS_FAILED;
|
||||
}
|
||||
|
||||
// 从jedis池中获取一个jedis实例
|
||||
jedis = pool.getResource();
|
||||
if (database != 0) {
|
||||
jedis.select(database);
|
||||
}
|
||||
jedis.set(key.getBytes(), message);
|
||||
return REDIS_SUCCESS;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
// 释放对象池,即获取jedis实例使用后要将对象还回去
|
||||
// 释放对象池,即获取jedis实例使用后要将对象还回去
|
||||
if (jedis != null) {
|
||||
jedis.close();
|
||||
}
|
||||
}
|
||||
return REDIS_FAILED;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param key
|
||||
* @return
|
||||
* @Description: 获取String对象类型值
|
||||
* @author SLy
|
||||
* @date 2018-12-19 19:49
|
||||
*/
|
||||
public String getMessage(String key) {
|
||||
Jedis jedis = null;
|
||||
try {
|
||||
if (StringUtils.isEmpty(key)) {
|
||||
return null;
|
||||
}
|
||||
// 从jedis池中获取一个jedis实例
|
||||
jedis = pool.getResource();
|
||||
// 获取jedis实例后可以对redis服务进行一系列的操作
|
||||
if (database != 0) {
|
||||
jedis.select(database);
|
||||
}
|
||||
String value = jedis.get(key);
|
||||
|
||||
return value;
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
// 释放对象池,即获取jedis实例使用后要将对象还回去
|
||||
// 释放对象池,即获取jedis实例使用后要将对象还回去
|
||||
if (jedis != null) {
|
||||
jedis.close();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param key
|
||||
* @return
|
||||
* @Description: 获取String对象类型值
|
||||
* @author SLy
|
||||
* @date 2018-12-19 19:49
|
||||
*/
|
||||
public Set<String> getAllMessage(String key) {
|
||||
Jedis jedis = null;
|
||||
try {
|
||||
if (StringUtils.isEmpty(key)) {
|
||||
return null;
|
||||
}
|
||||
// 从jedis池中获取一个jedis实例
|
||||
jedis = pool.getResource();
|
||||
// 获取jedis实例后可以对redis服务进行一系列的操作
|
||||
if (database != 0) {
|
||||
jedis.select(database);
|
||||
}
|
||||
Set<String> value = jedis.keys(key);
|
||||
|
||||
return value;
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
// 释放对象池,即获取jedis实例使用后要将对象还回去
|
||||
// 释放对象池,即获取jedis实例使用后要将对象还回去
|
||||
if (jedis != null) {
|
||||
jedis.close();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param key
|
||||
* @return
|
||||
* @Description: 通过key删除数据
|
||||
* @author SLy
|
||||
* @date 2018-12-19 19:49
|
||||
*/
|
||||
public Integer deleteByKey(String key) {
|
||||
Jedis jedis = null;
|
||||
try {
|
||||
if (StringUtils.isEmpty(key)) {
|
||||
return REDIS_FAILED;
|
||||
}
|
||||
// 从jedis池中获取一个jedis实例
|
||||
jedis = pool.getResource();
|
||||
if (database != 0) {
|
||||
jedis.select(database);
|
||||
}
|
||||
jedis.del(key);
|
||||
return REDIS_SUCCESS;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
// 释放对象池,即获取jedis实例使用后要将对象还回去
|
||||
if (jedis != null) {
|
||||
jedis.close();
|
||||
}
|
||||
}
|
||||
return REDIS_FAILED;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param key
|
||||
* @return
|
||||
* @Description: 通过key删除数据
|
||||
* @author SLy
|
||||
* @date 2018-12-19 19:49
|
||||
*/
|
||||
public TreeSet<String> keys(String key) {
|
||||
Jedis jedis = null;
|
||||
TreeSet<String> keys = new TreeSet<>();
|
||||
try {
|
||||
if (StringUtils.isEmpty(key)) {
|
||||
return null;
|
||||
}
|
||||
// 从jedis池中获取一个jedis实例
|
||||
jedis = pool.getResource();
|
||||
if (database != 0) {
|
||||
jedis.select(database);
|
||||
}
|
||||
keys.addAll(jedis.keys(key));
|
||||
return keys;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
// 释放对象池,即获取jedis实例使用后要将对象还回去
|
||||
if (jedis != null) {
|
||||
jedis.close();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public int getIncrementNum(String key, String message) {
|
||||
Jedis jedis = null;
|
||||
try {
|
||||
// 从jedis池中获取一个jedis实例
|
||||
jedis = pool.getResource();
|
||||
if (database != 0) {
|
||||
jedis.select(database);
|
||||
}
|
||||
String sss = jedis.get(key);
|
||||
if (StringUtils.isBlank(jedis.get(key))) {
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.add(Calendar.DAY_OF_YEAR, 1);
|
||||
cal.set(Calendar.HOUR_OF_DAY, 0);
|
||||
cal.set(Calendar.SECOND, 0);
|
||||
cal.set(Calendar.MINUTE, 0);
|
||||
cal.set(Calendar.MILLISECOND, 0);
|
||||
long aa = (cal.getTimeInMillis() - System.currentTimeMillis()) / 1000;
|
||||
int time = new Long(aa).intValue();
|
||||
jedis.set(key, message);
|
||||
jedis.expire(key, time);
|
||||
}
|
||||
jedis.incr(key);
|
||||
return REDIS_SUCCESS;
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
// 释放对象池,即获取jedis实例使用后要将对象还回去
|
||||
if (jedis != null) {
|
||||
jedis.close();
|
||||
}
|
||||
}
|
||||
|
||||
return REDIS_FAILED;
|
||||
}
|
||||
|
||||
public int getIncrNum(String key, String message) {
|
||||
Jedis jedis = null;
|
||||
try {
|
||||
// 从jedis池中获取一个jedis实例
|
||||
jedis = pool.getResource();
|
||||
if (database != 0) {
|
||||
jedis.select(database);
|
||||
}
|
||||
if (message.equals("1")) {
|
||||
jedis.decr(key);
|
||||
} else {
|
||||
jedis.incr(key);
|
||||
}
|
||||
return REDIS_SUCCESS;
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
// 释放对象池,即获取jedis实例使用后要将对象还回去
|
||||
if (jedis != null) {
|
||||
jedis.close();
|
||||
}
|
||||
}
|
||||
|
||||
return REDIS_FAILED;
|
||||
}
|
||||
|
||||
public int getTicketNum(String key) {
|
||||
Jedis jedis = null;
|
||||
try {
|
||||
// 从jedis池中获取一个jedis实例
|
||||
jedis = pool.getResource();
|
||||
if (database != 0) {
|
||||
jedis.select(database);
|
||||
}
|
||||
jedis.incr(key);
|
||||
return REDIS_SUCCESS;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
// 释放对象池,即获取jedis实例使用后要将对象还回去
|
||||
if (jedis != null) {
|
||||
jedis.close();
|
||||
}
|
||||
}
|
||||
return REDIS_FAILED;
|
||||
}
|
||||
|
||||
//添加元素
|
||||
public void addToCart(String key, String spec, int quantity) {
|
||||
Jedis jedis = null;
|
||||
try {
|
||||
jedis.zincrby(key, quantity, spec);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
// 释放对象池,即获取jedis实例使用后要将对象还回去
|
||||
if (jedis != null) {
|
||||
jedis.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 删除元素
|
||||
public void removeFromCart(String key, String spec, int quantity) {
|
||||
Jedis jedis = null;
|
||||
try {
|
||||
jedis.zincrby(key, -quantity, spec);
|
||||
|
||||
// 检查是否为零,如果为零,则删除该规格
|
||||
double newQuantity = jedis.zscore(key, spec);
|
||||
if (newQuantity <= 0) {
|
||||
jedis.zrem(key, spec);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
// 释放对象池,即获取jedis实例使用后要将对象还回去
|
||||
if (jedis != null) {
|
||||
jedis.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 获取集合元素
|
||||
public void getCartContents(String key) {
|
||||
Jedis jedis = null;
|
||||
try {
|
||||
jedis.zrangeWithScores(key, 0, -1).forEach(item -> {
|
||||
System.out.println("Spec: " + item.getElement() + ", Quantity: " + (int) item.getScore());
|
||||
});
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
// 释放对象池,即获取jedis实例使用后要将对象还回去
|
||||
if (jedis != null) {
|
||||
jedis.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Set<String> getSet(String key ){
|
||||
Jedis jedis = null ;
|
||||
Set<String> set = null ;
|
||||
try {
|
||||
jedis = pool.getResource();
|
||||
set = jedis.smembers(key);
|
||||
}catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
// 释放对象池,即获取jedis实例使用后要将对象还回去
|
||||
if (jedis != null) {
|
||||
jedis.close();
|
||||
}
|
||||
}
|
||||
return set ;
|
||||
}
|
||||
/**
|
||||
* 往set中添加数据
|
||||
* @param key
|
||||
* @param values
|
||||
* @return
|
||||
*/
|
||||
public Long addSet(String key , String... values ){
|
||||
Jedis jedis = null ;
|
||||
try {
|
||||
jedis = pool.getResource();
|
||||
return jedis.sadd(key,values);
|
||||
}catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
// 释放对象池,即获取jedis实例使用后要将对象还回去
|
||||
if (jedis != null) {
|
||||
jedis.close();
|
||||
}
|
||||
}
|
||||
return 0L ;
|
||||
}
|
||||
/**
|
||||
* 删除数据
|
||||
* @param key
|
||||
* @param values
|
||||
* @return
|
||||
*/
|
||||
public Boolean execsSet(String key,String values){
|
||||
Jedis jedis = null ;
|
||||
try {
|
||||
jedis = pool.getResource();
|
||||
return jedis.sismember(key,values);
|
||||
}catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
// 释放对象池,即获取jedis实例使用后要将对象还回去
|
||||
if (jedis != null) {
|
||||
jedis.close();
|
||||
}
|
||||
}
|
||||
return false ;
|
||||
}
|
||||
public Long delSet(String key , String... values ){
|
||||
Jedis jedis = null ;
|
||||
try {
|
||||
jedis = pool.getResource();
|
||||
return jedis.srem(key,values);
|
||||
}catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
// 释放对象池,即获取jedis实例使用后要将对象还回去
|
||||
if (jedis != null) {
|
||||
jedis.close();
|
||||
}
|
||||
}
|
||||
return 0L ;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.chaozhanggui.system.cashierservice.util;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
|
||||
public class SHA1Util {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(SHA1Util.class);
|
||||
public static String encrypt(String str){
|
||||
if (null == str || 0 == str.length()){
|
||||
return null;
|
||||
}
|
||||
char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
|
||||
'a', 'b', 'c', 'd', 'e', 'f'};
|
||||
try {
|
||||
MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
|
||||
mdTemp.update(new String(str.getBytes("iso8859-1"), "utf-8").getBytes());
|
||||
byte[] md = mdTemp.digest();
|
||||
int j = md.length;
|
||||
char[] buf = new char[j * 2];
|
||||
int k = 0;
|
||||
for (int i = 0; i < j; i++) {
|
||||
byte byte0 = md[i];
|
||||
buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
|
||||
buf[k++] = hexDigits[byte0 & 0xf];
|
||||
}
|
||||
return new String(buf);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
log.error("SHA1加密异常:",e);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
log.error("SHA1加密异常:",e);
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static String encrypt(Object obj) {
|
||||
if(obj==null){
|
||||
return null;
|
||||
}
|
||||
Map<String, Object> map = new HashMap<String,Object>();
|
||||
if(obj instanceof Map){
|
||||
map=(Map<String, Object>) obj;
|
||||
}else{
|
||||
map = BeanUtil.transBean2Map(obj);
|
||||
}
|
||||
map.remove("sign");
|
||||
map.remove("encrypt");
|
||||
String result = BeanUtil.mapOrderStr(map);
|
||||
if (StringUtils.isEmpty(result)) {
|
||||
return null;
|
||||
}
|
||||
return encrypt(result);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static boolean check(Object obj){
|
||||
Map<String,Object> map=new HashMap<String,Object>();
|
||||
if(obj==null){
|
||||
return false;
|
||||
}
|
||||
if(obj instanceof Map){
|
||||
map=(Map<String, Object>) obj;
|
||||
}else{
|
||||
map = BeanUtil.transBean2Map(obj);
|
||||
}
|
||||
String sign=(String)map.get("sign");
|
||||
if(sign==null){
|
||||
return false;
|
||||
}
|
||||
String str=encrypt(obj);
|
||||
return sign.equals(str)?true:false;
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package com.chaozhanggui.system.cashierservice.util;
|
||||
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.tomcat.util.codec.binary.Base64;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
/**
|
||||
* 签名工具类
|
||||
*/
|
||||
@Slf4j
|
||||
public class SignUtils {
|
||||
|
||||
/**
|
||||
* 获取签名之前的源串 按照ASCII 排序
|
||||
*
|
||||
* @param object
|
||||
* @return
|
||||
*/
|
||||
public static String getSignContent(JSONObject object) {
|
||||
TreeMap<String, Object> map = JSONObject.parseObject(JSONObject.toJSONString(object), TreeMap.class);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Map.Entry<String, Object> o : map.entrySet()) {
|
||||
String key = o.getKey();
|
||||
Object value = o.getValue();
|
||||
if ("sign".contains(key)) {
|
||||
continue;
|
||||
}
|
||||
if (value != null) {
|
||||
sb.append(key).append("=").append(value).append("&");
|
||||
// if(value instanceof ArrayList || value instanceof Map){
|
||||
// sb.append(key).append("=").append(JSON.toJSONString(value)).append("&");
|
||||
// }else{
|
||||
// sb.append(key).append("=").append(value).append("&");
|
||||
// }
|
||||
}
|
||||
}
|
||||
sb.deleteCharAt(sb.length() - 1);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static String wapGetSign(JSONObject object,String key) {
|
||||
String checkSign = MD5Util.encrypt(getSignContent(object) + "&key=" + key, "UTF-8");
|
||||
return checkSign;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取签名之前的源串 按照ASCII 排序
|
||||
*
|
||||
* @param object
|
||||
* @return
|
||||
*/
|
||||
public static String getYSSignContent(JSONObject object) {
|
||||
String s = JSONObject.toJSONString(object);
|
||||
TreeMap<String, Object> map = JSONObject.parseObject(s, TreeMap.class);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Map.Entry<String, Object> o : map.entrySet()) {
|
||||
String key = o.getKey();
|
||||
Object value = o.getValue();
|
||||
if ("sign".contains(key)) {
|
||||
continue;
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(value)) {
|
||||
sb.append(key).append("=").append(value).append("&");
|
||||
}
|
||||
}
|
||||
sb.deleteCharAt(sb.length() - 1);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static String getSignContent1(JSONObject object,String appSerct) {
|
||||
TreeMap<String, Object> map = JSONObject.parseObject(JSONObject.toJSONString(object), TreeMap.class);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Map.Entry<String, Object> o : map.entrySet()) {
|
||||
String key = o.getKey();
|
||||
Object value = o.getValue();
|
||||
if ("sign".contains(key)) {
|
||||
continue;
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(value)) {
|
||||
sb.append(key).append(value);
|
||||
}
|
||||
}
|
||||
sb.append(appSerct);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static String sha1Encrypt(String str) {
|
||||
if (str == null || str.length() == 0) {
|
||||
return null;
|
||||
}
|
||||
char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
|
||||
'a', 'b', 'c', 'd', 'e', 'f' };
|
||||
try {
|
||||
MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
|
||||
mdTemp.update(str.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
byte[] md = mdTemp.digest();
|
||||
int j = md.length;
|
||||
char[] buf = new char[j * 2];
|
||||
int k = 0;
|
||||
|
||||
for (byte byte0 : md) {
|
||||
buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
|
||||
buf[k++] = hexDigits[byte0 & 0xf];
|
||||
}
|
||||
return new String(buf);
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
public static String HMACSHA256BYTE(String data, String key) {
|
||||
String hash = "";
|
||||
try {
|
||||
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
|
||||
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), "HmacSHA256");
|
||||
sha256_HMAC.init(secret_key);
|
||||
byte[] array = sha256_HMAC.doFinal(data.getBytes());
|
||||
hash = Base64.encodeBase64String(array);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
public static String getSignSha256(JSONObject params, String accessKeySecret) {
|
||||
return HMACSHA256BYTE(getSignContent(params),accessKeySecret);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.chaozhanggui.system.cashierservice.util;
|
||||
|
||||
import cn.hutool.core.lang.Snowflake;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Random;
|
||||
|
||||
/**
|
||||
* @author Exrickx
|
||||
*/
|
||||
@Slf4j
|
||||
public class SnowFlakeUtil {
|
||||
|
||||
/**
|
||||
* 派号器workid:0~31
|
||||
* 机房datacenterid:0~31
|
||||
*/
|
||||
private static Snowflake snowflake = IdUtil.createSnowflake(1, 1);
|
||||
|
||||
public static Long nextId() {
|
||||
return snowflake.nextId();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public static String generateOrderNo(){
|
||||
String dateFormat="yyyyMMddHHmmssSSS";
|
||||
SimpleDateFormat sm=new SimpleDateFormat(dateFormat);
|
||||
|
||||
String currentDate=sm.format(new Date());
|
||||
|
||||
Random rm=new Random();
|
||||
int suffix=rm.nextInt(9999999);
|
||||
|
||||
return currentDate.concat(String.format("%07d",suffix));
|
||||
}
|
||||
|
||||
public static void main(String[] args){
|
||||
for(int i=0;i<10;i++){
|
||||
System.out.println(SnowFlakeUtil.generateOrderNo());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.chaozhanggui.system.cashierservice.util;
|
||||
|
||||
import cn.hutool.json.JSONArray;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import org.springframework.cglib.beans.BeanMap;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* @author admin
|
||||
* @date 2020/8/6 13:04
|
||||
*/
|
||||
public class TokenUtil {
|
||||
|
||||
/**
|
||||
* 设置过期时间
|
||||
*/
|
||||
public static final long EXPIRE_DATE=24*60*60*1000*365;
|
||||
/**
|
||||
* token秘钥
|
||||
*/
|
||||
private static final String TOKEN_SECRET = "BBDFSDFHFGHSGSRTRESDFSDFS";
|
||||
|
||||
/**
|
||||
*
|
||||
* @param accountId
|
||||
* @param loginName
|
||||
* @param clientType
|
||||
* @param shopId
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static String generateToken(String accountId,String loginName,String clientType,
|
||||
String shopId,String staffId,String code) throws Exception {
|
||||
Map<String, Object> claims = new HashMap<>(1);
|
||||
claims.put("accountId", accountId);
|
||||
claims.put("loginName",loginName);
|
||||
claims.put("clientType",clientType);
|
||||
claims.put("shopId",shopId);
|
||||
claims.put("staffId",staffId);
|
||||
claims.put("code",code);
|
||||
return generateToken(claims);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成token
|
||||
* @param claims
|
||||
* @return String
|
||||
*/
|
||||
private static String generateToken(Map<String, Object> claims) throws Exception {
|
||||
return Jwts.builder()
|
||||
.setClaims(claims)
|
||||
.setExpiration(new Date(System.currentTimeMillis()+EXPIRE_DATE))
|
||||
.setIssuedAt(new Date())
|
||||
.signWith(SignatureAlgorithm.HS256,TOKEN_SECRET)
|
||||
.compact();
|
||||
}
|
||||
|
||||
public static String refreshToken(String token) {
|
||||
String refreshedToken;
|
||||
try {
|
||||
final Claims claims = Jwts.parser()
|
||||
.setSigningKey(TOKEN_SECRET)
|
||||
.parseClaimsJws(token)
|
||||
.getBody();
|
||||
refreshedToken = generateToken(claims);
|
||||
} catch (Exception e) {
|
||||
refreshedToken = null;
|
||||
}
|
||||
return refreshedToken;
|
||||
}
|
||||
|
||||
public static String verifyToken(String token) {
|
||||
String result = "";
|
||||
try {
|
||||
Claims claims = Jwts.parser()
|
||||
.setSigningKey(TOKEN_SECRET)
|
||||
.parseClaimsJws(token)
|
||||
.getBody();
|
||||
result = "1";
|
||||
} catch (Exception e) {
|
||||
result = "0";
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从token获取用户信息
|
||||
* @param token token
|
||||
* @return 用户Id
|
||||
*/
|
||||
public static JSONObject parseParamFromToken(final String token) {
|
||||
Claims claims = Jwts.parser()
|
||||
.setSigningKey(TOKEN_SECRET)
|
||||
.parseClaimsJws(token)
|
||||
.getBody();
|
||||
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(claims);
|
||||
return jsonObject;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
parseParamFromToken("eyJhbGciOiJIUzI1NiJ9.eyJhY2NvdW50SWQiOiI2IiwiY2xpZW50VHlwZSI6InBjIiwic2hvcElkIjoiMTUiLCJleHAiOjE3MTA1ODc3NjAsImlhdCI6MTcwOTExNjUzMSwibG9naW5OYW1lIjoiMTg4MjE3Nzc4OCJ9.RXfyRgkfC13JGVypd9TQvbNNl_-btyQ-7xnvlj3ej0M");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user