CalculateUtil.java package com.dudu.tools;import java.util.Random;public class CalculateUtil {//随机码字典集 private static final String RANDOM_STR="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; /** * 取某个范围的
package com.dudu.tools;
import java.util.Random;
public class CalculateUtil {
//随机码字典集
private static final String RANDOM_STR="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
/**
* 取某个范围的任意数
* @param min
* @param max
* @return
*/
public static int getNext(int min, int max) {
Random random = new Random();
int s = random.nextInt(max) % (max - min + 1) + min;
return s;
}
/**
* 取某个范围的任意数
* @param min
* @param max
* @return
*/
public static int getNext(int max) {
Random random = new Random();
int s = random.nextInt(max) ;
return s;
}
/**
* 生成sum位随机码
* @return
*/
public static String generateDigitRandomCode(int sum){
Random rd = new Random();
String n = "";
int getNum;
do {
getNum = Math.abs(rd.nextInt(Integer.MAX_VALUE)) % 10 + 48;// 产生数字0-9的随机数
char num1 = (char) getNum;
String dn = Character.toString(num1);
n += dn;
} while (n.length() < sum);
return n;
}
/**
* 生成sum位数字字母随机码
* @param sum
* @return
*/
public static String generateMixRandomCode(int sum){
Random random = new Random();
StringBuffer sb = new StringBuffer();
for(int i = 0 ; i < sum; ++i){
int number = random.nextInt(62);//[0,62)
sb.append(RANDOM_STR.charAt(number));
}
return sb.toString();
}
/**
* IP 地址转换成 long 数据
* @param ipAddress
* @return
*/
public static long ipAddressToLong(String ipAddress) {
long ipInt = 0;
if (ValidatorUtil.isIPv4Address(ipAddress)) {
String[] ipArr = ipAddress.split("\\.");
if (ipArr.length == 3) {
ipAddress = ipAddress + ".0";
}
ipArr = ipAddress.split("\\.");
long p1 = Long.parseLong(ipArr[0]) * 256 * 256 * 256;
long p2 = Long.parseLong(ipArr[1]) * 256 * 256;
long p3 = Long.parseLong(ipArr[2]) * 256;
long p4 = Long.parseLong(ipArr[3]);
ipInt = p1 + p2 + p3 + p4;
}
return ipInt;
}
}
DateUtil.java
package com.dudu.tools;
import org.apache.commons.lang3.time.DateFormatUtils;
import java.util.Date;
import java.util.Random;
/**
* 项目名称:账号安全中心(all)
* 类名称:DateUtil
* 类描述: 时间操作工具
* 创建人:linwu
* 创建时间:2014-12-17 上午10:43:08
* @version
*/
public class DateUtil {
/**
* 生成ISO-8601 规范的时间格式
* @param date
* @return
*/
public static String formatISO8601DateString(Date date){
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
return DateFormatUtils.format(date, pattern);
}
/**
* 获取反时间戳
* @return
*/
public static Long getCurrentReverseTime(){
long longTime = System.currentTimeMillis()*1000000 + CalculateUtil.getNext(999999);
return Long.MAX_VALUE - longTime;
}
/**
* 获取原时间戳
* @param reverseTime
* @return
*/
public static Long recoverReverseTime(Long reverseTime){
long longTime = Long.MAX_VALUE - reverseTime;
return longTime/1000000;
}
/**
* 生成页面普通展示时间
* @param date
* @return
*/
public static String formatNormalDateString(Date date){
String pattern = "yyyy-MM-dd HH:mm:ss";
return DateFormatUtils.format(date, pattern);
}
}
ErrorCode.java
package com.dudu.tools;
public enum ErrorCode {
ID_IS_NULL(400,"ID_IS_NULL", "ID为空!"),
ENT_CODE_IS_NULL(400,"ENT_CODE_IS_NULL","企业编码为空!"),
ADMIN_ACCOUNT_IS_NULL(400,"ADMIN_ACCOUNT_IS_NULL"," 企业管理员账号为空!"),
UUID_IS_NULL(400,"UUID_IS_NULL"," UUID为空!"), MODIFY_FAIL(400,"MODIFY_FAIL","修改失败!"),
//题库
TEST_CATALOG_NAME_IS_NULL(400,"TEST_CATALOG_NAME_IS_NULL","题库名称为空!"),
TEST_CATALOG_NAME_TOO_LONG(400,"TEST_CATALOG_TOO_LONG","题库名称长度过长!"),
TEST_CATALOG_NAME_EXIST(400,"TEST_CATALOG_NAME_EXIST","题库名称已存在!"),
TEST_CATALOG_NOT_EXIST(400,"TEST_CATALOG_NOT_EXIST","题库不存在!"),
TEST_CATALOG_ACTIVE_FAIL(400,"TEST_CATALOG_ACTIVE_FAIL","题库激活失败!"),
TEST_CATALOG_LOCK_FAIL(400,"TEST_CATALOG_LOCK_FAIL","题库禁用失败!"),
TEST_CATALOG_MEMO_TOO_LONG(400,"TEST_CATALOG_TOO_LONG","题库描述长度过长!"),
STATE_FORMAT_ERROR(400,"STATE_FORMAT_ERROR","状态参数格式有误!"),
STATE_IS_NULL(400,"STATE_IS_NULL","状态为空!"),
TEST_CATALOG_ADD_FAIL(400,"TEST_CATALOG_ADD_FAIL","题库信息添加失败!"),
TEST_CATALOG_DELETE_FAIL(400,"TEST_CATALOG_DELETE_FAIL","题库信息删除失败!"),
TEST_CATALOG_UPDATE_FAIL(400,"TEST_CATALOG_UPDATE_FAIL","题库信息修改失败!"),
OPT_IS_NULL(400,"OPT_IS_NULL","操作动作为空!");
// 成员变量
private int httpStatus;
private String code;
private String message;
private int res_code;
// 构造方法
private ErrorCode(int httpStatus, String code, String message) {
this.setHttpStatus(200);
this.setRes_code(httpStatus);
this.setCode(code);
this.setMessage(message);
}
private ErrorCode() {
this.setHttpStatus(httpStatus);
this.setCode(code);
this.setMessage(message);
}
public int getHttpStatus() {
return httpStatus;
}
public void setHttpStatus(int httpStatus) {
this.httpStatus = httpStatus;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getRes_code() {
return res_code;
}
public void setRes_code(int res_code) {
this.res_code = res_code;
}
}
StringUtil.java
package com.dudu.tools;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 字符串处理工具类
* @author ouzhb
*/
public class StringUtil {
/**
* 判断字符串是否为null、“ ”、“null”
* @param obj
* @return
*/
public static boolean isNull(String obj) {
if (obj == null){
return true;
}else if (obj.toString().trim().equals("")){
return true;
}else if(obj.toString().trim().toLowerCase().equals("null")){
return true;
}
return false;
}
/**
* 正则验证是否是数字
* @param str
* @return
*/
public static boolean isNumber(String str) {
Pattern pattern = Pattern.compile("[+-]?[0-9]+[0-9]*(\\.[0-9]+)?");
Matcher match = pattern.matcher(str);
return match.matches();
}
/**
* 将一个长整数转换位字节数组(8个字节),b[0]存储高位字符,大端
*
* @param l
* 长整数
* @return 代表长整数的字节数组
*/
public static byte[] longToBytes(long l) {
byte[] b = new byte[8];
b[0] = (byte) (l >>> 56);
b[1] = (byte) (l >>> 48);
b[2] = (byte) (l >>> 40);
b[3] = (byte) (l >>> 32);
b[4] = (byte) (l >>> 24);
b[5] = (byte) (l >>> 16);
b[6] = (byte) (l >>> 8);
b[7] = (byte) (l);
return b;
}
}
ValidatorUtil.java
package com.dudu.tools;
import org.apache.commons.lang3.StringUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 合法性校验工具
*
* @author Administrator
*
*/
public class ValidatorUtil {
/**
* 功能:手机号验证
*
* @param str
* @return
*/
public static boolean isMobile(String str) {
Pattern p = null;
Matcher m = null;
boolean b = false;
if (StringUtils.isBlank(str)) {
return b;
}
p = Pattern.compile("^[1][3,4,5,8][0-9]{9}$"); // 验证手机号
m = p.matcher(str);
b = m.matches();
return b;
}
/**
* 功能:数字判断
* @param str
* @return
*/
public static boolean isNumeric(String str) {
if (StringUtils.isBlank(str)) {
return false;
}
if (str.matches("\\d*")) {
return true;
} else {
return false;
}
}
/**
* 判断密码格式是否正确(只能是数组或者字母,并存长度为[6,12])
* @param passwd
* @return
* @author wyongjian
* @date 2014-11-18
*/
public static boolean isPasswd(String passwd){
if(StringUtils.isBlank(passwd))return false;
if(passwd.length()<6 || passwd.length()>12)return false;
String regEx="^[A-Za-z0-9_]+$";
Pattern p=Pattern.compile(regEx);
Matcher m=p.matcher(passwd);
return m.matches();
}
/**
* 判断是否是IPv4
* @param input
* @return
*/
public static boolean isIPv4Address(String input) {
Pattern IPV4_PATTERN = Pattern
.compile("^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$");
return IPV4_PATTERN.matcher(input).matches();
}
/**
* 判断是否是MAC地址
* @param mac
* @return
* @author wyongjian
* @date 2014-11-26
*/
public static boolean isMac(String mac){
if(StringUtils.isNotBlank(mac)){
mac = mac.toUpperCase();
//正则校验MAC合法性
String patternMac="^[A-F0-9]{2}(:[A-F0-9]{2}){5}$";
if(Pattern.compile(patternMac).matcher(mac).find()){
return true;
}
}
return false;
}
/**
* 判断用户名格式是否正确(只能是数组、字母或者下划线)
* @param username
* @return
*/
public static boolean isUsername(String username){
if(StringUtils.isBlank(username))return false;
String regEx="^[A-Za-z0-9_]+$";
Pattern p=Pattern.compile(regEx);
Matcher m=p.matcher(username);
return m.matches();
}
/**
* 字符串是否包含中文
* @param source
* @return
*/
public static boolean isContainsChinese(String source){
final String regEx = "[\u4e00-\u9fa5]";
final Pattern pat = Pattern.compile(regEx);
boolean flag = false;
Matcher matcher = pat.matcher(source);
if(matcher.find()) {
flag = true;
}
return flag;
}
public static boolean isEmail(String email){
// final String regEx="/[^@]+@[^@]/";
final String regEx="^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
final Pattern pat = Pattern.compile(regEx);
boolean flag = false;
Matcher matcher = pat.matcher(email);
flag = matcher.matches();
return flag;
}
}
ServletUtil.java
package com.dudu.tools;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
import org.apache.log4j.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ServletUtil {
//服务器标识
private static String hostName = "";
//响应的ContentType内容
private static final String RESPONSE_CONTENTTYPE = "application/json";
//响应编码
private static final String RESPONSE_CHARACTERENCODING = "utf-8";
//业务名称的缩写
private static final String BIZ_NAME = "";
private static Logger log = Logger.getLogger(ServletUtil.class);
static{
try {
InetAddress netAddress = InetAddress.getLocalHost();
hostName = netAddress.getHostName();
} catch (UnknownHostException e) {
log.error("netAddress.getHostName failed", e);
}
}
/**
* 生成系统异常错误报文
* @param response
*/
public static String createSysErrorResponse(HttpServletResponse response){
final String code = "INTERNAL_SERVER_ERROR";
String message = "服务器内部错误";
return createErrorResponse(500,500,code, message,response);
}
/**
* 生成参数不正确报文
* @param response
*/
public static String createParamErrorResponse(HttpServletResponse response) {
final String code = "REQUIRE_ARGUMENT";
String message = "缺少参数";
return createErrorResponse(400,400,code,message,response);
}
/**
* 生成参数不正确报文
* @param param 缺少的参数名称
* @param response
*/
public static String createParamErrorResponse(String param,HttpServletResponse response) {
final String code = "REQUIRE_ARGUMENT";
String message = "缺少参数:" + param;
return createErrorResponse(400,400,code,message,response);
}
/**
* 认证失败
* @param response
*/
public static String createAuthorizationErrorResponse(HttpServletResponse response) {
final String code = "AUTH_INVALID_TOKEN";
String message = "请求认证失败!请按规范在Header报文头中附上正确的Authorization认证属性!";
return createErrorResponse(401,401,code, message,response);
}
/**
* 授权失败
* @param response
*/
public static String createAuthorizeErrorResponse(HttpServletResponse response) {
final String code = "AUTH_DENIED";
String message = "请求失败,没有访问或操作该资源的权限!";
return createErrorResponse(403,403,code, message,response);
}
/**
* 授权失败
* @param response
*/
public static String createAuthorizeErrorResponse(HttpServletResponse response, String message) {
final String code = "AUTH_DENIED";
return createErrorResponse(403,403,code, message,response);
}
/**
* 路径不存在
* @param response
*/
public static String createNotFoundErrorResponse(HttpServletResponse response) {
final String code = "NOT_FOUND";
String message = "请求的URL路径不存在!";
return createErrorResponse(404,404,code, message,response);
}
/**
* 生成错误报文
* @param errorCode
* @param response
*/
public static String createErrorResponse(ErrorCode errorCode,
HttpServletResponse response){
return createErrorResponse(errorCode.getHttpStatus(),errorCode.getRes_code(),errorCode.getCode(),
errorCode.getMessage(),response);
}
/**
* 生成错误报文
* @param httpStatus
* @param code
* @param message
* @param response
*/
public static String createErrorResponse(Integer httpStatus, Object code,
String message, HttpServletResponse response){
code = BIZ_NAME + code;
PrintWriter printWriter = null;
String jsonString = "";
try {
response.setCharacterEncoding(RESPONSE_CHARACTERENCODING);
response.setContentType(RESPONSE_CONTENTTYPE);
response.setStatus(httpStatus);
Map
map = new HashMap
(); map.put("code", code); map.put("message", message); //map.put("request_id", requestId==null?"":requestId); //map.put("host_id", hostName); map.put("server_time", DateUtil.formatISO8601DateString(new Date())); printWriter = response.getWriter(); jsonString = JSON.toJSONString(map, SerializerFeature.WriteMapNullValue); printWriter.write(jsonString); printWriter.flush(); } catch (Exception e) { log.error("createResponse failed", e); } finally { if(null!=printWriter)printWriter.close(); } return jsonString; } /** * 生成错误报文 * @param httpStatus * @param res_code * @param code * @param message * @param response * @return */ public static String createErrorResponse(Integer httpStatus,Integer res_code, Object code, String message, HttpServletResponse response){ code = BIZ_NAME + code; PrintWriter printWriter = null; String jsonString = ""; try { response.setCharacterEncoding(RESPONSE_CHARACTERENCODING); response.setContentType(RESPONSE_CONTENTTYPE); response.setStatus(httpStatus); Map
map = new HashMap
(); map.put("code", code); map.put("message", message); //map.put("request_id", requestId==null?"":requestId); //map.put("host_id", hostName); map.put("res_code", res_code); map.put("server_time", DateUtil.formatISO8601DateString(new Date())); printWriter = response.getWriter(); jsonString = JSON.toJSONString(map, SerializerFeature.WriteMapNullValue); printWriter.write(jsonString); printWriter.flush(); } catch (Exception e) { log.error("createResponse failed", e); } finally { if(null!=printWriter)printWriter.close(); } return jsonString; } /** * 生成成功报文 * @param httpCode * @param result * @param response */ public static String createSuccessResponse(Integer httpCode, Object result, HttpServletResponse response){ return createSuccessResponse(httpCode, result, SerializerFeature.WriteMapNullValue,null,response); } public static String createSuccessResponse(Integer httpCode,String message,Object result,HttpServletResponse response){ return createSuccessResponse(httpCode,message,result, SerializerFeature.WriteMapNullValue,null,response); } /** * 生成登录传成功报文 * @param httpCode * @param result * @param response */ public static String createLoginSuccessResponse(Integer httpCode, Object result, HttpServletResponse response){ /*response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods","POST, GET, PATCH, DELETE, PUT"); response.setHeader("Access-Control-Allow-Headers",request.getHeader("Access-Control-Request-Headers"));*/ return createSuccessResponse(httpCode, result, SerializerFeature.WriteMapNullValue,null,response); } public static String createSuccessResponse(Integer httpCode, Object result, SerializeFilter filter, HttpServletResponse response){ return createSuccessResponse(httpCode, result, SerializerFeature.PrettyFormat,filter,response); } public static String createSuccessResponse(Integer httpCode, Object result, SerializerFeature serializerFeature, HttpServletResponse response){ return createSuccessResponse(httpCode, result,serializerFeature,null,response); } public static String createSuccessResponse(Integer httpCode, Object result, SerializerFeature serializerFeature, SerializeFilter filter, HttpServletResponse response){ PrintWriter printWriter = null; String jsonString = ""; try { response.setCharacterEncoding(RESPONSE_CHARACTERENCODING); response.setContentType(RESPONSE_CONTENTTYPE); response.setStatus(httpCode); printWriter = response.getWriter(); if(null != result){ if(null!=filter){ jsonString = JSONObject.toJSONString(result,filter,serializerFeature); }else{ // jsonString = JSONObject.toJSONString(result, serializerFeature); jsonString = JSONObject.toJSONStringWithDateFormat(result,"yyyy-MM-dd HH:ss:mm",serializerFeature); } printWriter.write(jsonString); } printWriter.flush(); } catch (Exception e) { log.error("createResponse failed", e); } finally { if(null!=printWriter)printWriter.close(); } return jsonString; } public static String createSuccessResponse(Integer httpCode, String message, Object result, SerializerFeature serializerFeature, SerializeFilter filter, HttpServletResponse response){ PrintWriter printWriter = null; String jsonString = ""; try { response.setCharacterEncoding(RESPONSE_CHARACTERENCODING); response.setContentType(RESPONSE_CONTENTTYPE); response.setStatus(httpCode); printWriter = response.getWriter(); SerializeConfig config = new SerializeConfig(); config.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd")); Map
map = new HashMap
(); if(null != result){ map.put("res_code", httpCode); map.put("message", message); map.put("data",result); if(null!=filter){ jsonString = JSONObject.toJSONString(map,filter,serializerFeature); }else{ // jsonString = JSONObject.toJSONString(map,config,serializerFeature); jsonString = JSONObject.toJSONStringWithDateFormat(map,"yyyy-MM-dd"); } printWriter.write(jsonString); } printWriter.flush(); } catch (Exception e) { log.error("createResponse failed", e); } finally { if(null!=printWriter)printWriter.close(); } return jsonString; } /** * 获取报文IP * @param request * @return */ public static String getRemortIP(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } if(ip.startsWith(",")){ ip = ip.substring(1, ip.length()); } return ip; } /** * 获取带参数的URL串 */ public static String getUrlWithParams(HttpServletRequest request) { String url = request.getRequestURI(); if (!StringUtil.isNull(request.getQueryString())) { url = url + "?" + request.getQueryString(); } return url; } /** * 获取AccessToken * @param request * @return */ public static String getAccessToken(HttpServletRequest request){ String accessToken = null; String authorization = request.getHeader("Authorization"); if(StringUtil.isNull(authorization)){ return accessToken; } if(authorization.startsWith("MAC")){ Pattern p = Pattern.compile("MAC id=\"(.*)\",nonce=\"(.*)\",mac=\"(.*)\""); Matcher m = p.matcher(authorization); if(m.find() && !StringUtil.isNull(m.group(1))){ return m.group(1); } }else if(authorization.startsWith("Bearer")){ Pattern p = Pattern.compile("Bearer \"(.*)\""); Matcher m = p.matcher(authorization); if(m.find() && !StringUtil.isNull(m.group(1))){ return m.group(1); } } return accessToken; } /** * 判断是否是Mac Token * @param request * @return */ public static boolean isExistMacToken(HttpServletRequest request){ String authorization = request.getHeader("Authorization"); if(!StringUtil.isNull(authorization) && authorization.startsWith("MAC id=")){ return true; } return false; } /** * 设置让浏览器弹出下载对话框的Header. * 根据浏览器的不同设置不同的编码格式 防止中文乱码 * @param fileName 下载后的文件名. */ public static void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response, String fileName) { try { //中文文件名支持 String encodedfileName = java.net.URLEncoder.encode(fileName,"UTF-8"); response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + "\""); response.setContentType("application/force-download"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }
