距离当前时间过去了多久:
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Date;
/**
* @author GuoChao
* 时间转换工具类
*/
public class TimeUtils {
protected static Long MIN=60000L;
protected static Long HOUR=3600000L;
protected static Long DAY=86400000L;
protected static Long MONTH=2592000000L;
protected static Long YEAR=31536000000L;
protected static Long MAX=946080000000L;
@Autowired
private AdMathUtils adMathUtils;
/**
* 传入上次登录时间计算距离当前时间过去了多久
* @param lastLoginTime
* @return
*/
public static String lastLoginFormat(Date lastLoginTime){
long time = lastLoginTime.getTime();
return lastLoginFormat(time);
}
/**
* 传入上次登录时间戳计算距离当前时间过去了多久
* @param lastLoginTime
* @return
*/
public static String lastLoginFormat(Long lastLoginTime){
if (lastLoginTime==null){
return null;
}
Long time=System.currentTimeMillis()-lastLoginTime;
//小于一分钟,回复在线
if (time<MIN){
return "On-line";
}
//大于一分钟小于一小时,回复XX分钟之前
if (time>MIN&time<HOUR){
long l = time / MIN;
if (l==1){return "a minute ago";}
return l+" minutes ago";
}
//大于一小时小于一天,回复XXX小时之前
if (time>HOUR&time<DAY){
long l = time / HOUR;
if (l==1){return "a hour ago";}
return l+" hours ago";
}
//大于一天小于一个月,回复XXX天之前
if (time>DAY&time<MONTH){
long l = time / DAY;
if (l==1){return "a day ago";}
return l+" days ago";
}
//大于一个月小于一年,回复XXX个月之前
if (time>MONTH&time<YEAR){
long l = time / MONTH;
if (l==1){return "a month ago";}
return l+" months";
}
//大于一年小于MAX,回复XXX年之前
if (time>YEAR&time<MAX){
long l = time / YEAR;
if (l==1){return "a year ago";}
return l+" years ago";
}
//其他回复,很久没有登录了
return "long time ago";
}
}
除法工具类:
import com.tencse.common.utils.StringLibs;
import org.springframework.stereotype.Service;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
@Service
public class AdMathUtils {
/**
* 计算实体百分比,剔除userId和id的判定
*
* @param object 需要计算内容量的对象
* @return 百分比(已*100)
*/
public Double getBf(Object object) {
try {
Class<?> aClass = object.getClass();
Field[] declaredFields = aClass.getDeclaredFields();
int count = 0;
int max = 0;
for (Field declaredField : declaredFields) {
declaredField.setAccessible(true);
String name = declaredField.getName();
if ("id".equals(name) || "userId".equals(name)) {
continue;
}
String moethodName = "get" + StringLibs.getCapital(declaredField.getName());
Method method = aClass.getMethod(moethodName);
Object value = method.invoke(object);
if (value != null) {
count++;
}
max++;
}
DecimalFormat decimalFormat = new DecimalFormat("0.00");
String format = decimalFormat.format((double) count / max);
return Double.parseDouble(format) * 100;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 计算除法
* @param d1 被除数
* @param d2 除数
* @param pattern 精度
* @return
*/
public String getCf(Double d1, Double d2, String pattern) {
DecimalFormat decimalFormat = new DecimalFormat(pattern);
return decimalFormat.format((d1 / d2));
}
}
二维码工具:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
/**
* 二维码工具类
* @author yanzc
*
*/
public class QRCodeUtil {
private static final Logger logger = LoggerFactory.getLogger(QRCodeUtil.class);
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
private static final int WIDTH = 120;
private static final int HEIGHT = 120;
/**
* 生成二维码
* @param text 二维码内容
* @return
*/
public static BufferedImage zxingCodeCreate(String text){
Map<EncodeHintType, String> his = new HashMap<EncodeHintType, String>();
//设置编码字符集
his.put(EncodeHintType.CHARACTER_SET, "utf-8");
try {
//1、生成二维码
BitMatrix encode = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, his);
//2、获取二维码宽高
int codeWidth = encode.getWidth();
int codeHeight = encode.getHeight();
//3、将二维码放入缓冲流
BufferedImage image = new BufferedImage(codeWidth, codeHeight, BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < codeWidth; i++) {
for (int j = 0; j < codeHeight; j++) {
//4、循环将二维码内容定入图片
image.setRGB(i, j, encode.get(i, j) ? BLACK : WHITE);
}
}
return image;
/*File outPutImage = new File(outPutPath);
//如果图片不存在创建图片,这里是缓存本地测试用的
if(!outPutImage.exists()){
outPutImage.createNewFile();}
//5、将二维码写入图片
ImageIO.write(image, imageType, outPutImage);*/
} catch (WriterException e) {
e.printStackTrace();
logger.info("二维码生成失败");
}
return null;
}
/**
* 二维码解析
* @param analyzePath 二维码路径
* @return
* @throws IOException
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static String zxingCodeAnalyze(String analyzePath) throws Exception{
MultiFormatReader formatReader = new MultiFormatReader();
String resultStr = null;
try {
File file = new File(analyzePath);
if (!file.exists()) {
return "二维码不存在";
}
BufferedImage image = ImageIO.read(file);
LuminanceSource source = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
Result result = formatReader.decode(binaryBitmap, hints);
resultStr = result.getText();
} catch (NotFoundException e) {
e.printStackTrace();
}
logger.info(resultStr);
return resultStr;
}
}
异常处理
public class Constants {
//成功标志
public static final String KEY_SUCCESS = "success";
//提示信息
public static final String KEY_MESSAGE = "message";
//错误码
public static final String KEY_CODE = "code";
//IP地址
public static final String KEY_IP_ADDRESS = "ipAddress";
//默认错误提示语
public static final String DEFAULT_FAIL_MESSAGE="系统出错了,请联系管理员";
//发生异常信息可以错误
public static final String SQL_EXCEPTION_MESSAGE_PREFIX = "java.sql";
//数据库发生异常默认报错
public static final String SQL_EXCEPTION_DEFAULT_MESSAGE = "数据库发生异常";
//服务实例不可用
public static final String NO_INSTANCE_AVAILABLE = "No instances available for";
//服务实例不可用错误信息
public static final String NO_INSTANCE_AVAILABLE_MESSAGE = "服务实例不可用";
/** 公共错误码定义start **/
//默认失败编码
public static final int DEFAULT_FAIL_CODE = -1;
//应用默认异常编码
public static final int DEFAULT_APPLICATION_FAIL_CODE = 10;
//默认成功编码
public static final int DEFAULT_SUCCESS_CODE = 0;
//请求参数错误
public static final int REQUEST_PARAMS_ERROR_CODE = 1001;
//token过期
public static final int ACCESSS_TOKEN_EXPIRED = 2001;
//数据库更新数据错误编码(更新的数据与预计的有出入)
public static final int SQL_UPDATE_ERROR_CODE = 3001;
/** 错误码定义end **/
}
枚举值校验
/**
* 查看一个参数是否在规定值之内
* @param eumParam 校验值
* @param paramList 约定范围
* @return
*/
public static Boolean checkEumParam(Object eumParam,Object[] paramList){
Boolean index=false;
for (Object o : paramList) {
if (eumParam.toString().equals(o.toString())){
index=true;
break;
}
}
return index;
}
}
前端来参校验:
/**
* 检查对象内部是否包含null
* 用于那些不允许有null值的参数
* @param t 需要判定的参数
* @param excludDfs 排除不判定的成员变量
* @param <T> 任意类型
* @return boolean
*/
public static <T> Boolean checkObject(T t, List<String> excludDfs) {
Class<?> aClass = t.getClass();
Field[] declaredFields = aClass.getDeclaredFields();
try {
for (Field declaredField : declaredFields) {
String name = declaredField.getName();
for (String excludDf : excludDfs) {
if (!name.equals(excludDf)){
String methodName = "get" + StringLibs.getCapital(name);
Method doMetod = aClass.getMethod(methodName);
Object invoke = doMetod.invoke(t);
if (invoke == null || "".equals(invoke.toString())) {
return false;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
一个简易的JSON响应工具
@Slf4j
public class AdJsonUtils {
public static void writJson(HttpServletResponse response,
HttpServletRequest request,
Object object) {
try {
response.setContentType("application/json;charset=UTF-8");
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Method","POST,GET");
PrintWriter writer = response.getWriter();
writer.write(new ObjectMapper().writeValueAsString(object));
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
log.error("转换json返回出现异常");
}
}
这里是使用:
//走到这表示redis存在剩余时间数据,进行判断,如果剩余时间大于当前时间
if (Long.parseLong(userRedisUnBanTime)>System.currentTimeMillis()){
//这里先进行响应码的设置
response.setStatus(403);
//里面获取到响应体,设置响应内容,由于这里是拦截器,拦截了响应,所以只会在下面通过请求以后进行响应的时候发送响应内容
AdJsonUtils.writJson(response,request,new MsgResult(false,CodeEnum.ACCOUNT_IS_BAN.getErrorMessage()));
return false;
}
List分页工具类
public static <T> List<T> listPageHelper(List<T> list, int page, int size){
int star=Math.min(((page-1)*size), list.size());
int end = Math.min((size * page), list.size());
return list.subList(star,end );
后端向前端写入文件的工具类
/**
* 文件Http操作工具类
*/
public class HttpFileUtils {
/**
* 向客户端写入文件
* @return
*/
public static boolean httpDownloadUtil(InputStream ins,HttpServletResponse response) throws IOException {
// 创建一个字节输出流,用来暂存数据
ByteArrayOutputStream bao = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
// 用于记录读了多少,当最后一次读取的时候会用到,用来判定是否读完,同时避免最后一次写入越界
int rec;
while ((rec = ins.read(buff, 0, buff.length))>0){
bao.write(buff,0,rec);
}
//转为字节数组
byte[] bytes = bao.toByteArray();
return httpDownloadUtil(bytes,response);
}
/**
* 向客户端写入文件
* @return
*/
public static boolean httpDownloadUtil(byte[] fileByte,HttpServletResponse response) throws IOException {
// 获取输出流
try {
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(fileByte);
outputStream.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}