提交
This commit is contained in:
@@ -0,0 +1,94 @@
|
||||
package com.chaozhanggui.system.cashierservice.util;
|
||||
|
||||
|
||||
import org.apache.tomcat.util.codec.binary.Base64;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class AESUtil {
|
||||
//AES:加密方式 CBC:工作模式 PKCS5Padding:填充模式
|
||||
private static final String CBC_PKCS5_PADDING = "AES/CBC/PKCS5Padding";
|
||||
private static final String AES = "AES";
|
||||
public static final String CODE_TYPE = "UTF-8"; // 编码方式
|
||||
/* AES 加密操作
|
||||
* @param content 待加密内容
|
||||
* @param key 加密密钥
|
||||
* @return 返回Base64转码后的加密数据
|
||||
*/
|
||||
public static String encrypt(String content, String key,String VIPARA) {
|
||||
if (content == null || "".equals(content)) {
|
||||
return content;
|
||||
}
|
||||
try {
|
||||
/*
|
||||
* 新建一个密码编译器的实例,由三部分构成,用"/"分隔,分别代表如下
|
||||
* 1. 加密的类型(如AES,DES,RC2等)
|
||||
* 2. 模式(AES中包含ECB,CBC,CFB,CTR,CTS等)
|
||||
* 3. 补码方式(包含nopadding/PKCS5Padding等等)
|
||||
* 依据这三个参数可以创建很多种加密方式
|
||||
*/
|
||||
Cipher cipher = Cipher.getInstance(CBC_PKCS5_PADDING);
|
||||
//偏移量
|
||||
IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes(CODE_TYPE));
|
||||
byte[] byteContent = content.getBytes(CODE_TYPE);
|
||||
//使用加密秘钥
|
||||
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(CODE_TYPE), AES);
|
||||
//SecretKeySpec skeySpec = getSecretKey(key);
|
||||
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, zeroIv);// 初始化为加密模式的密码器
|
||||
byte[] result = cipher.doFinal(byteContent);// 加密
|
||||
return Base64.encodeBase64String(result);//通过Base64转码返回
|
||||
} catch (Exception ex) {
|
||||
Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/* AES 解密操作
|
||||
* @param content
|
||||
* @param key
|
||||
*/
|
||||
public static String decrypt(String content, String key,String VIPARA) {
|
||||
if (content == null || "".equals(content)) {
|
||||
return content;
|
||||
}
|
||||
try {
|
||||
//实例化
|
||||
Cipher cipher = Cipher.getInstance(CBC_PKCS5_PADDING);
|
||||
IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes(CODE_TYPE));
|
||||
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(CODE_TYPE), AES);
|
||||
//SecretKeySpec skeySpec = getSecretKey(key);
|
||||
cipher.init(Cipher.DECRYPT_MODE, skeySpec, zeroIv);
|
||||
byte[] result = cipher.doFinal(Base64.decodeBase64(content));
|
||||
return new String(result, CODE_TYPE);
|
||||
} catch (Exception ex) {
|
||||
Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
// 生成加密秘钥
|
||||
private static SecretKeySpec getSecretKey(final String key) {
|
||||
//返回生成指定算法密钥生成器的 KeyGenerator 对象
|
||||
KeyGenerator kg = null;
|
||||
try {
|
||||
kg = KeyGenerator.getInstance(AES);
|
||||
//AES 要求密钥长度为 128
|
||||
kg.init(128, new SecureRandom(key.getBytes()));
|
||||
//生成一个密钥
|
||||
SecretKey secretKey = kg.generateKey();
|
||||
return new SecretKeySpec(secretKey.getEncoded(), AES);// 转换为AES专用密钥
|
||||
} catch (Exception ex) {
|
||||
Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static void main(String[] args){
|
||||
System.out.println(decrypt("f9IOB20vHdfjCggHG18OXbRYhPDQAM6EkO0Pppwh6ngXU8mLH6872iivD/sYhzALZ263ab8OSeudRrL/gegm4RUGwXdedE2gL76VMMCbYcsOPlzmj8qjMQQhjlLFVJNSYNoG5A7vFNVKuTXyTnnOaER50yJ2MNeA17SPC3nlHIWoVxrC5TqLMgWoULrdtPX1/nSgw87bXdmICPfIJfwR0w==","0a3pBp100pmmLR1VUZ0001QP500pBp1u","HVkKsTJBeIbQl8pNt17RXw=="));
|
||||
}
|
||||
}
|
||||
@@ -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,355 @@
|
||||
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));
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static String getTimes(Date date){
|
||||
return sdfday.format(date);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取YYYY格式
|
||||
* @return
|
||||
*/
|
||||
public static String getSdfTimes() {
|
||||
return sdfTimes.format(new Date());
|
||||
}
|
||||
|
||||
|
||||
public static String getNextSdfTimes(Date date){
|
||||
return sdfTimes.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() {
|
||||
return sdfTime.format(new 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(getTime());
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化日期为时分秒
|
||||
* @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 getTime(Date date) {
|
||||
return sdfTime.format(date);
|
||||
}
|
||||
|
||||
|
||||
public static String formatDateToStr(Date date) {
|
||||
return sdfTime.format(date);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
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();
|
||||
|
||||
System.out.println("yxprint 打印请求参数:"+content);
|
||||
|
||||
//通过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,83 @@
|
||||
package com.chaozhanggui.system.cashierservice.util;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
|
||||
public class MD5Utils {
|
||||
private 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();
|
||||
}
|
||||
|
||||
private 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];
|
||||
}
|
||||
|
||||
public static String MD5Encode(String origin, String charsetname) {
|
||||
String resultString = null;
|
||||
try {
|
||||
resultString = origin;
|
||||
MessageDigest md = MessageDigest.getInstance("MD5");
|
||||
if (charsetname == null || "".equals(charsetname))
|
||||
resultString = byteArrayToHexString(md.digest(resultString
|
||||
.getBytes()));
|
||||
else
|
||||
resultString = byteArrayToHexString(md.digest(resultString
|
||||
.getBytes(charsetname)));
|
||||
} catch (Exception exception) {
|
||||
}
|
||||
return resultString;
|
||||
}
|
||||
|
||||
private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
|
||||
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
|
||||
|
||||
/**
|
||||
* MD5指纹算法
|
||||
*
|
||||
* @param str
|
||||
* @return
|
||||
*/
|
||||
public static String md5(String str) {
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
|
||||
messageDigest.update(str.getBytes());
|
||||
return bytesToHexString(messageDigest.digest());
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 将二进制转换成16进制
|
||||
*
|
||||
* @param src
|
||||
* @return
|
||||
*/
|
||||
public static String bytesToHexString(byte[] src) {
|
||||
StringBuilder stringBuilder = new StringBuilder("");
|
||||
if (src == null || src.length <= 0) {
|
||||
return null;
|
||||
}
|
||||
for (int i = 0; i < src.length; i++) {
|
||||
int v = src[i] & 0xFF;
|
||||
String hv = Integer.toHexString(v);
|
||||
if (hv.length() < 2) {
|
||||
stringBuilder.append(0);
|
||||
}
|
||||
stringBuilder.append(hv);
|
||||
}
|
||||
return stringBuilder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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,225 @@
|
||||
package com.chaozhanggui.system.cashierservice.util;
|
||||
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
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){
|
||||
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.getRemark()!=null&& ObjectUtil.isNotEmpty(detail.getRemark())){
|
||||
sb.append("<S>规格:"+detail.getRemark()+"</S><BR>");
|
||||
}
|
||||
|
||||
sb.append("<BR>");
|
||||
|
||||
}
|
||||
sb.append("------------------------<BR>");
|
||||
String t="¥"+detailPO.getReceiptsAmount();
|
||||
t=String.format("%11s",t).replace(' ', paddingCharacter);
|
||||
sb.append("<F>应收"+t+"</F><BR>");
|
||||
if(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>");
|
||||
|
||||
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);
|
||||
System.out.println("yxprint 打印请求参数:"+JSONUtil.toJSONString(multiValueMap));
|
||||
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<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,"ZF544PG03W00001",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,776 @@
|
||||
package com.chaozhanggui.system.cashierservice.util;
|
||||
|
||||
/*
|
||||
* Copyright 2019-2020 Zheng Jie
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Sets;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Configurable;
|
||||
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.RedisConnection;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.core.*;
|
||||
import org.springframework.data.redis.core.script.DefaultRedisScript;
|
||||
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
|
||||
import org.springframework.data.redis.serializer.RedisSerializer;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.Resource;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* @author /
|
||||
*/
|
||||
@Component
|
||||
@SuppressWarnings({"unchecked", "all"})
|
||||
public class RedisUtils {
|
||||
private static final Logger log = LoggerFactory.getLogger(RedisUtils.class);
|
||||
private RedisTemplate<Object, Object> redisTemplate;
|
||||
@Value("${jwt.online-key}")
|
||||
private String onlineKey;
|
||||
/**
|
||||
* 指定缓存失效时间
|
||||
*
|
||||
* @param key 键
|
||||
* @param time 时间(秒)
|
||||
*/
|
||||
public boolean expire(String key, long time) {
|
||||
try {
|
||||
if (time > 0) {
|
||||
redisTemplate.expire(key, time, TimeUnit.SECONDS);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 指定缓存失效时间
|
||||
*
|
||||
* @param key 键
|
||||
* @param time 时间(秒)
|
||||
* @param timeUnit 单位
|
||||
*/
|
||||
public boolean expire(String key, long time, TimeUnit timeUnit) {
|
||||
try {
|
||||
if (time > 0) {
|
||||
redisTemplate.expire(key, time, timeUnit);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 key 获取过期时间
|
||||
*
|
||||
* @param key 键 不能为null
|
||||
* @return 时间(秒) 返回0代表为永久有效
|
||||
*/
|
||||
public long getExpire(Object key) {
|
||||
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找匹配key
|
||||
*
|
||||
* @param pattern key
|
||||
* @return /
|
||||
*/
|
||||
public List<String> scan(String pattern) {
|
||||
ScanOptions options = ScanOptions.scanOptions().match(pattern).build();
|
||||
RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
|
||||
RedisConnection rc = Objects.requireNonNull(factory).getConnection();
|
||||
Cursor<byte[]> cursor = rc.scan(options);
|
||||
List<String> result = new ArrayList<>();
|
||||
while (cursor.hasNext()) {
|
||||
result.add(new String(cursor.next()));
|
||||
}
|
||||
try {
|
||||
RedisConnectionUtils.releaseConnection(rc, factory);
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询 key
|
||||
*
|
||||
* @param patternKey key
|
||||
* @param page 页码
|
||||
* @param size 每页数目
|
||||
* @return /
|
||||
*/
|
||||
public List<String> findKeysForPage(String patternKey, int page, int size) {
|
||||
ScanOptions options = ScanOptions.scanOptions().match(patternKey).build();
|
||||
RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
|
||||
RedisConnection rc = Objects.requireNonNull(factory).getConnection();
|
||||
Cursor<byte[]> cursor = rc.scan(options);
|
||||
List<String> result = new ArrayList<>(size);
|
||||
int tmpIndex = 0;
|
||||
int fromIndex = page * size;
|
||||
int toIndex = page * size + size;
|
||||
while (cursor.hasNext()) {
|
||||
if (tmpIndex >= fromIndex && tmpIndex < toIndex) {
|
||||
result.add(new String(cursor.next()));
|
||||
tmpIndex++;
|
||||
continue;
|
||||
}
|
||||
// 获取到满足条件的数据后,就可以退出了
|
||||
if (tmpIndex >= toIndex) {
|
||||
break;
|
||||
}
|
||||
tmpIndex++;
|
||||
cursor.next();
|
||||
}
|
||||
try {
|
||||
RedisConnectionUtils.releaseConnection(rc, factory);
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断key是否存在
|
||||
*
|
||||
* @param key 键
|
||||
* @return true 存在 false不存在
|
||||
*/
|
||||
public boolean hasKey(String key) {
|
||||
try {
|
||||
return redisTemplate.hasKey(key);
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除缓存
|
||||
*
|
||||
* @param key 可以传一个值 或多个
|
||||
*/
|
||||
public void del(String... keys) {
|
||||
if (keys != null && keys.length > 0) {
|
||||
if (keys.length == 1) {
|
||||
boolean result = redisTemplate.delete(keys[0]);
|
||||
log.debug("--------------------------------------------");
|
||||
log.debug(new StringBuilder("删除缓存:").append(keys[0]).append(",结果:").append(result).toString());
|
||||
log.debug("--------------------------------------------");
|
||||
} else {
|
||||
Set<Object> keySet = new HashSet<>();
|
||||
for (String key : keys) {
|
||||
keySet.addAll(redisTemplate.keys(key));
|
||||
}
|
||||
long count = redisTemplate.delete(keySet);
|
||||
log.debug("--------------------------------------------");
|
||||
log.debug("成功删除缓存:" + keySet.toString());
|
||||
log.debug("缓存删除数量:" + count + "个");
|
||||
log.debug("--------------------------------------------");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================String=============================
|
||||
|
||||
/**
|
||||
* 普通缓存获取
|
||||
*
|
||||
* @param key 键
|
||||
* @return 值
|
||||
*/
|
||||
public Object get(String key) {
|
||||
return key == null ? null : redisTemplate.opsForValue().get(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量获取
|
||||
*
|
||||
* @param keys
|
||||
* @return
|
||||
*/
|
||||
public List<Object> multiGet(List<String> keys) {
|
||||
List list = redisTemplate.opsForValue().multiGet(Sets.newHashSet(keys));
|
||||
List resultList = Lists.newArrayList();
|
||||
Optional.ofNullable(list).ifPresent(e-> list.forEach(ele-> Optional.ofNullable(ele).ifPresent(resultList::add)));
|
||||
return resultList;
|
||||
}
|
||||
|
||||
/**
|
||||
* 普通缓存放入
|
||||
*
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @return true成功 false失败
|
||||
*/
|
||||
public boolean set(String key, Object value) {
|
||||
try {
|
||||
redisTemplate.opsForValue().set(key, value);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 普通缓存放入并设置时间
|
||||
*
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
|
||||
* @return true成功 false 失败
|
||||
*/
|
||||
public boolean set(String key, Object value, long time) {
|
||||
try {
|
||||
if (time > 0) {
|
||||
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
|
||||
} else {
|
||||
set(key, value);
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@Resource
|
||||
private StringRedisTemplate stringRedisTemplate;
|
||||
/**
|
||||
* 普通缓存放入并设置时间(重写)
|
||||
*
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @param time 时间
|
||||
* @param timeUnit 类型
|
||||
* @return true成功 false 失败
|
||||
*/
|
||||
public boolean setextend(String key, Object value, long time) {
|
||||
try {
|
||||
if (time > 0) {
|
||||
stringRedisTemplate.opsForValue().set(key, value.toString(), time);
|
||||
} else {
|
||||
set(key, value);
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 普通缓存放入并设置时间
|
||||
*
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @param time 时间
|
||||
* @param timeUnit 类型
|
||||
* @return true成功 false 失败
|
||||
*/
|
||||
public boolean set(String key, Object value, long time, TimeUnit timeUnit) {
|
||||
try {
|
||||
if (time > 0) {
|
||||
redisTemplate.opsForValue().set(key, value, time, timeUnit);
|
||||
} else {
|
||||
set(key, value);
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ================================Map=================================
|
||||
|
||||
/**
|
||||
* HashGet
|
||||
*
|
||||
* @param key 键 不能为null
|
||||
* @param item 项 不能为null
|
||||
* @return 值
|
||||
*/
|
||||
public Object hget(String key, String item) {
|
||||
return redisTemplate.opsForHash().get(key, item);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取hashKey对应的所有键值
|
||||
*
|
||||
* @param key 键
|
||||
* @return 对应的多个键值
|
||||
*/
|
||||
public Map<Object, Object> hmget(String key) {
|
||||
return redisTemplate.opsForHash().entries(key);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* HashSet
|
||||
*
|
||||
* @param key 键
|
||||
* @param map 对应多个键值
|
||||
* @return true 成功 false 失败
|
||||
*/
|
||||
public boolean hmset(String key, Map<String, Object> map) {
|
||||
try {
|
||||
redisTemplate.opsForHash().putAll(key, map);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* HashSet 并设置时间
|
||||
*
|
||||
* @param key 键
|
||||
* @param map 对应多个键值
|
||||
* @param time 时间(秒)
|
||||
* @return true成功 false失败
|
||||
*/
|
||||
public boolean hmset(String key, Map<String, Object> map, long time) {
|
||||
try {
|
||||
redisTemplate.opsForHash().putAll(key, map);
|
||||
if (time > 0) {
|
||||
expire(key, time);
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 向一张hash表中放入数据,如果不存在将创建
|
||||
*
|
||||
* @param key 键
|
||||
* @param item 项
|
||||
* @param value 值
|
||||
* @return true 成功 false失败
|
||||
*/
|
||||
public boolean hset(String key, String item, Object value) {
|
||||
try {
|
||||
redisTemplate.opsForHash().put(key, item, value);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 向一张hash表中放入数据,如果不存在将创建
|
||||
*
|
||||
* @param key 键
|
||||
* @param item 项
|
||||
* @param value 值
|
||||
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
|
||||
* @return true 成功 false失败
|
||||
*/
|
||||
public boolean hset(String key, String item, Object value, long time) {
|
||||
try {
|
||||
redisTemplate.opsForHash().put(key, item, value);
|
||||
if (time > 0) {
|
||||
expire(key, time);
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除hash表中的值
|
||||
*
|
||||
* @param key 键 不能为null
|
||||
* @param item 项 可以使多个 不能为null
|
||||
*/
|
||||
public void hdel(String key, Object... item) {
|
||||
redisTemplate.opsForHash().delete(key, item);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断hash表中是否有该项的值
|
||||
*
|
||||
* @param key 键 不能为null
|
||||
* @param item 项 不能为null
|
||||
* @return true 存在 false不存在
|
||||
*/
|
||||
public boolean hHasKey(String key, String item) {
|
||||
return redisTemplate.opsForHash().hasKey(key, item);
|
||||
}
|
||||
|
||||
/**
|
||||
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
|
||||
*
|
||||
* @param key 键
|
||||
* @param item 项
|
||||
* @param by 要增加几(大于0)
|
||||
* @return
|
||||
*/
|
||||
public double hincr(String key, String item, double by) {
|
||||
return redisTemplate.opsForHash().increment(key, item, by);
|
||||
}
|
||||
|
||||
/**
|
||||
* hash递减
|
||||
*
|
||||
* @param key 键
|
||||
* @param item 项
|
||||
* @param by 要减少记(小于0)
|
||||
* @return
|
||||
*/
|
||||
public double hdecr(String key, String item, double by) {
|
||||
return redisTemplate.opsForHash().increment(key, item, -by);
|
||||
}
|
||||
|
||||
// ============================set=============================
|
||||
|
||||
/**
|
||||
* 根据key获取Set中的所有值
|
||||
*
|
||||
* @param key 键
|
||||
* @return
|
||||
*/
|
||||
public Set<Object> sGet(String key) {
|
||||
try {
|
||||
return redisTemplate.opsForSet().members(key);
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据value从一个set中查询,是否存在
|
||||
*
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @return true 存在 false不存在
|
||||
*/
|
||||
public boolean sHasKey(String key, Object value) {
|
||||
try {
|
||||
return redisTemplate.opsForSet().isMember(key, value);
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将数据放入set缓存
|
||||
*
|
||||
* @param key 键
|
||||
* @param values 值 可以是多个
|
||||
* @return 成功个数
|
||||
*/
|
||||
public long sSet(String key, Object... values) {
|
||||
try {
|
||||
return redisTemplate.opsForSet().add(key, values);
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将set数据放入缓存
|
||||
*
|
||||
* @param key 键
|
||||
* @param time 时间(秒)
|
||||
* @param values 值 可以是多个
|
||||
* @return 成功个数
|
||||
*/
|
||||
public long sSetAndTime(String key, long time, Object... values) {
|
||||
try {
|
||||
Long count = redisTemplate.opsForSet().add(key, values);
|
||||
if (time > 0) {
|
||||
expire(key, time);
|
||||
}
|
||||
return count;
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取set缓存的长度
|
||||
*
|
||||
* @param key 键
|
||||
* @return
|
||||
*/
|
||||
public long sGetSetSize(String key) {
|
||||
try {
|
||||
return redisTemplate.opsForSet().size(key);
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除值为value的
|
||||
*
|
||||
* @param key 键
|
||||
* @param values 值 可以是多个
|
||||
* @return 移除的个数
|
||||
*/
|
||||
public long setRemove(String key, Object... values) {
|
||||
try {
|
||||
Long count = redisTemplate.opsForSet().remove(key, values);
|
||||
return count;
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// ===============================list=================================
|
||||
|
||||
/**
|
||||
* 获取list缓存的内容
|
||||
*
|
||||
* @param key 键
|
||||
* @param start 开始
|
||||
* @param end 结束 0 到 -1代表所有值
|
||||
* @return
|
||||
*/
|
||||
public List<Object> lGet(String key, long start, long end) {
|
||||
try {
|
||||
return redisTemplate.opsForList().range(key, start, end);
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取list缓存的长度
|
||||
*
|
||||
* @param key 键
|
||||
* @return
|
||||
*/
|
||||
public long lGetListSize(String key) {
|
||||
try {
|
||||
return redisTemplate.opsForList().size(key);
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过索引 获取list中的值
|
||||
*
|
||||
* @param key 键
|
||||
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
|
||||
* @return
|
||||
*/
|
||||
public Object lGetIndex(String key, long index) {
|
||||
try {
|
||||
return redisTemplate.opsForList().index(key, index);
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将list放入缓存
|
||||
*
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @return
|
||||
*/
|
||||
public boolean lSet(String key, Object value) {
|
||||
try {
|
||||
redisTemplate.opsForList().rightPush(key, value);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将list放入缓存
|
||||
*
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @param time 时间(秒)
|
||||
* @return
|
||||
*/
|
||||
public boolean lSet(String key, Object value, long time) {
|
||||
try {
|
||||
redisTemplate.opsForList().rightPush(key, value);
|
||||
if (time > 0) {
|
||||
expire(key, time);
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将list放入缓存
|
||||
*
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @return
|
||||
*/
|
||||
public boolean lSet(String key, List<Object> value) {
|
||||
try {
|
||||
redisTemplate.opsForList().rightPushAll(key, value);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将list放入缓存
|
||||
*
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @param time 时间(秒)
|
||||
* @return
|
||||
*/
|
||||
public boolean lSet(String key, List<Object> value, long time) {
|
||||
try {
|
||||
redisTemplate.opsForList().rightPushAll(key, value);
|
||||
if (time > 0) {
|
||||
expire(key, time);
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据索引修改list中的某条数据
|
||||
*
|
||||
* @param key 键
|
||||
* @param index 索引
|
||||
* @param value 值
|
||||
* @return /
|
||||
*/
|
||||
public boolean lUpdateIndex(String key, long index, Object value) {
|
||||
try {
|
||||
redisTemplate.opsForList().set(key, index, value);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除N个值为value
|
||||
*
|
||||
* @param key 键
|
||||
* @param count 移除多少个
|
||||
* @param value 值
|
||||
* @return 移除的个数
|
||||
*/
|
||||
public long lRemove(String key, long count, Object value) {
|
||||
try {
|
||||
return redisTemplate.opsForList().remove(key, count, value);
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param prefix 前缀
|
||||
* @param ids id
|
||||
*/
|
||||
public void delByKeys(String prefix, Set<Long> ids) {
|
||||
Set<Object> keys = new HashSet<>();
|
||||
for (Long id : ids) {
|
||||
keys.addAll(redisTemplate.keys(new StringBuffer(prefix).append(id).toString()));
|
||||
}
|
||||
long count = redisTemplate.delete(keys);
|
||||
// 此处提示可自行删除
|
||||
log.debug("--------------------------------------------");
|
||||
log.debug("成功删除缓存:" + keys.toString());
|
||||
log.debug("缓存删除数量:" + count + "个");
|
||||
log.debug("--------------------------------------------");
|
||||
}
|
||||
String secKillScript = "local userid=KEYS[1];\r\n" +
|
||||
"local prodid=KEYS[2];\r\n" +
|
||||
"local qtkey=prodid;\r\n" +
|
||||
"local usernum=KEYS[3];\r\n" +
|
||||
"local usersKey='sk:'..prodid..\":usr\";\r\n" +
|
||||
"local num= redis.call(\"get\" ,qtkey);\r\n" +
|
||||
"if tonumber(num)<tonumber(usernum) then \r\n" +
|
||||
" return 0;\r\n" +
|
||||
"end\r\n" +
|
||||
"if tonumber(num)<=0 then \r\n" +
|
||||
" return 0;\r\n" +
|
||||
"else \r\n" +
|
||||
" redis.call(\"DECRBY\",qtkey,tonumber(usernum));\r\n" +
|
||||
"end\r\n" +
|
||||
"return 1";
|
||||
public String seckill(String key, String prodid,String num,String uid) {
|
||||
DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
|
||||
redisScript.setResultType(Long.class);//返回类型是Long
|
||||
redisScript.setScriptText(secKillScript);
|
||||
Object execute = redisTemplate.execute(redisScript, Arrays.asList(uid, key,num), prodid);
|
||||
String reString = String.valueOf(execute);
|
||||
return reString;
|
||||
}
|
||||
String secAddScript = "local prodid=KEYS[1];\r\n" +
|
||||
"local usernum=KEYS[2];\r\n" +
|
||||
"local num= redis.call(\"get\" ,prodid);\r\n" +
|
||||
" redis.call(\"SET\",prodid,tonumber(usernum)+tonumber(num));\r\n" +
|
||||
"return 1";
|
||||
public String secAdd(String key,String num) {
|
||||
|
||||
DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
|
||||
redisScript.setResultType(Long.class);//返回类型是Long
|
||||
redisScript.setScriptText(secKillScript);
|
||||
Object execute = redisTemplate.execute(redisScript, Arrays.asList(key,num));
|
||||
String reString = String.valueOf(execute);
|
||||
return reString;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
package me.zhengjie.utils;
|
||||
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import javax.crypto.Cipher;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.security.*;
|
||||
import java.security.interfaces.RSAPrivateKey;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
|
||||
/**
|
||||
* @author https://www.cnblogs.com/nihaorz/p/10690643.html
|
||||
* @description Rsa 工具类,公钥私钥生成,加解密
|
||||
* @date 2020-05-18
|
||||
**/
|
||||
public class RsaUtil {
|
||||
|
||||
private static final String SRC = "123456";
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
System.out.println("\n");
|
||||
RsaKeyPair keyPair = generateKeyPair();
|
||||
System.out.println("公钥:" + keyPair.getPublicKey());
|
||||
System.out.println("私钥:" + keyPair.getPrivateKey());
|
||||
System.out.println("\n");
|
||||
test1(keyPair);
|
||||
System.out.println("\n");
|
||||
test2(keyPair);
|
||||
System.out.println("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* 公钥加密私钥解密
|
||||
*/
|
||||
private static void test1(RsaKeyPair keyPair) throws Exception {
|
||||
System.out.println("***************** 公钥加密私钥解密开始 *****************");
|
||||
String text1 = encryptByPublicKey(keyPair.getPublicKey(), RsaUtil.SRC);
|
||||
String text2 = decryptByPrivateKey(keyPair.getPrivateKey(), text1);
|
||||
System.out.println("加密前:" + RsaUtil.SRC);
|
||||
System.out.println("加密后:" + text1);
|
||||
System.out.println("解密后:" + text2);
|
||||
if (RsaUtil.SRC.equals(text2)) {
|
||||
System.out.println("解密字符串和原始字符串一致,解密成功");
|
||||
} else {
|
||||
System.out.println("解密字符串和原始字符串不一致,解密失败");
|
||||
}
|
||||
System.out.println("***************** 公钥加密私钥解密结束 *****************");
|
||||
}
|
||||
|
||||
/**
|
||||
* 私钥加密公钥解密
|
||||
* @throws Exception /
|
||||
*/
|
||||
private static void test2(RsaKeyPair keyPair) throws Exception {
|
||||
System.out.println("***************** 私钥加密公钥解密开始 *****************");
|
||||
String text1 = encryptByPrivateKey(keyPair.getPrivateKey(), RsaUtil.SRC);
|
||||
String text2 = decryptByPublicKey(keyPair.getPublicKey(), text1);
|
||||
System.out.println("加密前:" + RsaUtil.SRC);
|
||||
System.out.println("加密后:" + text1);
|
||||
System.out.println("解密后:" + text2);
|
||||
if (RsaUtil.SRC.equals(text2)) {
|
||||
System.out.println("解密字符串和原始字符串一致,解密成功");
|
||||
} else {
|
||||
System.out.println("解密字符串和原始字符串不一致,解密失败");
|
||||
}
|
||||
System.out.println("***************** 私钥加密公钥解密结束 *****************");
|
||||
}
|
||||
|
||||
/**
|
||||
* 公钥解密
|
||||
*
|
||||
* @param publicKeyText 公钥
|
||||
* @param text 待解密的信息
|
||||
* @return /
|
||||
* @throws Exception /
|
||||
*/
|
||||
public static String decryptByPublicKey(String publicKeyText, String text) throws Exception {
|
||||
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyText));
|
||||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
|
||||
Cipher cipher = Cipher.getInstance("RSA");
|
||||
cipher.init(Cipher.DECRYPT_MODE, publicKey);
|
||||
byte[] result = doLongerCipherFinal(Cipher.DECRYPT_MODE, cipher, Base64.decodeBase64(text));
|
||||
return new String(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 私钥加密
|
||||
*
|
||||
* @param privateKeyText 私钥
|
||||
* @param text 待加密的信息
|
||||
* @return /
|
||||
* @throws Exception /
|
||||
*/
|
||||
public static String encryptByPrivateKey(String privateKeyText, String text) throws Exception {
|
||||
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyText));
|
||||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
|
||||
Cipher cipher = Cipher.getInstance("RSA");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
|
||||
byte[] result = doLongerCipherFinal(Cipher.ENCRYPT_MODE, cipher, text.getBytes());
|
||||
return Base64.encodeBase64String(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 私钥解密
|
||||
*
|
||||
* @param privateKeyText 私钥
|
||||
* @param text 待解密的文本
|
||||
* @return /
|
||||
* @throws Exception /
|
||||
*/
|
||||
public static String decryptByPrivateKey(String privateKeyText, String text) throws Exception {
|
||||
PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyText));
|
||||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
|
||||
Cipher cipher = Cipher.getInstance("RSA");
|
||||
cipher.init(Cipher.DECRYPT_MODE, privateKey);
|
||||
byte[] result = doLongerCipherFinal(Cipher.DECRYPT_MODE, cipher, Base64.decodeBase64(text));
|
||||
return new String(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 公钥加密
|
||||
*
|
||||
* @param publicKeyText 公钥
|
||||
* @param text 待加密的文本
|
||||
* @return /
|
||||
*/
|
||||
public static String encryptByPublicKey(String publicKeyText, String text) throws Exception {
|
||||
X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyText));
|
||||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
|
||||
Cipher cipher = Cipher.getInstance("RSA");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
|
||||
byte[] result = doLongerCipherFinal(Cipher.ENCRYPT_MODE, cipher, text.getBytes());
|
||||
return Base64.encodeBase64String(result);
|
||||
}
|
||||
|
||||
private static byte[] doLongerCipherFinal(int opMode,Cipher cipher, byte[] source) throws Exception {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
if (opMode == Cipher.DECRYPT_MODE) {
|
||||
out.write(cipher.doFinal(source));
|
||||
} else {
|
||||
int offset = 0;
|
||||
int totalSize = source.length;
|
||||
while (totalSize - offset > 0) {
|
||||
int size = Math.min(cipher.getOutputSize(0) - 11, totalSize - offset);
|
||||
out.write(cipher.doFinal(source, offset, size));
|
||||
offset += size;
|
||||
}
|
||||
}
|
||||
out.close();
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建RSA密钥对
|
||||
*
|
||||
* @return /
|
||||
* @throws NoSuchAlgorithmException /
|
||||
*/
|
||||
public static RsaKeyPair generateKeyPair() throws NoSuchAlgorithmException {
|
||||
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
|
||||
keyPairGenerator.initialize(1024);
|
||||
KeyPair keyPair = keyPairGenerator.generateKeyPair();
|
||||
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
|
||||
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
|
||||
String publicKeyString = Base64.encodeBase64String(rsaPublicKey.getEncoded());
|
||||
String privateKeyString = Base64.encodeBase64String(rsaPrivateKey.getEncoded());
|
||||
return new RsaKeyPair(publicKeyString, privateKeyString);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* RSA密钥对对象
|
||||
*/
|
||||
public static class RsaKeyPair {
|
||||
|
||||
private final String publicKey;
|
||||
private final String privateKey;
|
||||
|
||||
public RsaKeyPair(String publicKey, String privateKey) {
|
||||
this.publicKey = publicKey;
|
||||
this.privateKey = privateKey;
|
||||
}
|
||||
|
||||
public String getPublicKey() {
|
||||
return publicKey;
|
||||
}
|
||||
|
||||
public String getPrivateKey() {
|
||||
return privateKey;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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 = MD5Utils.MD5Encode(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,33 @@
|
||||
package com.chaozhanggui.system.cashierservice.util;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
|
||||
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public class SpringUtils implements BeanFactoryPostProcessor {
|
||||
|
||||
//Spring应用上下文环境
|
||||
private static ConfigurableListableBeanFactory beanFactory;
|
||||
|
||||
@Override
|
||||
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
|
||||
SpringUtils.beanFactory = beanFactory;
|
||||
}
|
||||
|
||||
public static ConfigurableListableBeanFactory getBeanFactory() {
|
||||
return beanFactory;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> T getBean(String name) throws BeansException {
|
||||
return (T) getBeanFactory().getBean(name);
|
||||
}
|
||||
|
||||
public static <T> T
|
||||
getBean(Class<T> clz) throws BeansException {
|
||||
T result = (T) getBeanFactory().getBean(clz);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.chaozhanggui.system.cashierservice.util;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Random;
|
||||
|
||||
/**
|
||||
* @author lyf
|
||||
*/
|
||||
public class StringUtil {
|
||||
/**
|
||||
* 生成指定长度的随机数
|
||||
* @param length
|
||||
* @return
|
||||
*/
|
||||
public static String genRandomNum(int length) {
|
||||
int maxNum = 36;
|
||||
int i;
|
||||
int count = 0;
|
||||
char[] str = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
|
||||
'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
|
||||
'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
|
||||
StringBuffer pwd = new StringBuffer("");
|
||||
Random r = new Random();
|
||||
while (count < length) {
|
||||
i = Math.abs(r.nextInt(maxNum));
|
||||
pwd.append(str[i]);
|
||||
count++;
|
||||
}
|
||||
return pwd.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成订单号
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static synchronized String getBillno() {
|
||||
StringBuilder billno = new StringBuilder();
|
||||
|
||||
// 日期(格式:20080524)
|
||||
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
|
||||
billno.append(format.format(new Date()));
|
||||
return billno.toString();
|
||||
}
|
||||
public static JSONArray stringChangeList(String listString){
|
||||
// 使用Fastjson将JSON字符串转换为JSONArray对象
|
||||
return JSON.parseArray(listString);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package com.chaozhanggui.system.cashierservice.util;
|
||||
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.JwtBuilder;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @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";
|
||||
|
||||
private JwtBuilder jwtBuilder;
|
||||
|
||||
public static final String AUTHORITIES_KEY = "user";
|
||||
|
||||
/**
|
||||
* 初始化生成token的参数
|
||||
* @param userId
|
||||
* @param phone
|
||||
* @return
|
||||
*/
|
||||
public static String generateToken(Integer userId,String openId,String phone,String userName) throws Exception {
|
||||
Map<String, Object> claims = new HashMap<>(1);
|
||||
claims.put("userId", userId);
|
||||
if(ObjectUtil.isNotEmpty(openId)){
|
||||
claims.put("openId",openId);
|
||||
}
|
||||
|
||||
if(ObjectUtil.isNotEmpty(phone)){
|
||||
claims.put("phone",phone);
|
||||
}
|
||||
|
||||
if(ObjectUtil.isNotEmpty(userName)){
|
||||
claims.put("userName",userName);
|
||||
}
|
||||
|
||||
|
||||
|
||||
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 Object parseParamFromToken(final String token, final String paramName ) {
|
||||
Claims claims = Jwts.parser()
|
||||
.setSigningKey(TOKEN_SECRET)
|
||||
.parseClaimsJws(token)
|
||||
.getBody();
|
||||
return claims.get(paramName);
|
||||
}
|
||||
public static void main(String[] args){
|
||||
System.out.println(refreshToken("eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjE1OTY4Nzc5MjEsInN1YiI6ImRkZGRkIiwiaWF0IjoxNTk2Njk3OTIxfQ.lrg3KF9h9izbmyD2q5onqnZIKBqanWy9xCcroFpjxPKmJz6kz27G9lVlFpVanrL1I4SFf3Dz3q3Xu01DX2T_dw"));
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
||||
Calendar cld = Calendar.getInstance();
|
||||
cld.setTime(new Date());
|
||||
cld.set(Calendar.DATE, cld.get(Calendar.DATE)-1);
|
||||
System.out.println(sdf.format(cld.getTime()));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.chaozhanggui.system.cashierservice.util;
|
||||
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import io.jsonwebtoken.JwtBuilder;
|
||||
import org.apache.tomcat.util.net.openssl.ciphers.Authentication;
|
||||
|
||||
public class tokenProvider {
|
||||
private JwtBuilder jwtBuilder;
|
||||
// public String createToken(Authentication authentication) {
|
||||
// return jwtBuilder
|
||||
// // 加入ID确保生成的 Token 都不一致
|
||||
// .setId(IdUtil.simpleUUID())
|
||||
// .claim(AUTHORITIES_KEY, authentication.getName())
|
||||
// .setSubject(authentication.getName())
|
||||
// .compact();
|
||||
// }
|
||||
}
|
||||
Reference in New Issue
Block a user